code
stringlengths
2
1.05M
/*! * froala_editor v3.0.0-rc.2 (https://www.froala.com/wysiwyg-editor) * License https://froala.com/wysiwyg-editor/terms/ * Copyright 2014-2019 Froala Labs */ (function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? factory(require('froala-editor')) : typeof define === 'function' && define.amd ? define(['froala-editor'], factory) : (factory(global.FroalaEditor)); }(this, (function (FE) { 'use strict'; FE = FE && FE.hasOwnProperty('default') ? FE['default'] : FE; /** * English spoken in Canada */ FE.LANGUAGE['en_ca'] = { translation: { // Place holder 'Type something': 'Type something', // Basic formatting 'Bold': 'Bold', 'Italic': 'Italic', 'Underline': 'Underline', 'Strikethrough': 'Strikethrough', // Main buttons 'Insert': 'Insert', 'Delete': 'Delete', 'Cancel': 'Cancel', 'OK': 'OK', 'Back': 'Back', 'Remove': 'Remove', 'More': 'More', 'Update': 'Update', 'Style': 'Style', // Font 'Font Family': 'Font Family', 'Font Size': 'Font Size', // Colors 'Colors': 'Colours', 'Background': 'Background', 'Text': 'Text', 'HEX Color': 'HEX Colour', // Paragraphs 'Paragraph Format': 'Paragraph Format', 'Normal': 'Normal', 'Code': 'Code', 'Heading 1': 'Heading 1', 'Heading 2': 'Heading 2', 'Heading 3': 'Heading 3', 'Heading 4': 'Heading 4', // Style 'Paragraph Style': 'Paragraph Style', 'Inline Style': 'Inline Style', // Alignment 'Align': 'Align', 'Align Left': 'Align Left', 'Align Center': 'Align Centre', 'Align Right': 'Align Right', 'Align Justify': 'Align Justify', 'None': 'None', // Lists 'Ordered List': 'Ordered List', 'Unordered List': 'Unordered List', // Indent 'Decrease Indent': 'Decrease Indent', 'Increase Indent': 'Increase Indent', // Links 'Insert Link': 'Insert Link', 'Open in new tab': 'Open in new tab', 'Open Link': 'Open Link', 'Edit Link': 'Edit Link', 'Unlink': 'Unlink', 'Choose Link': 'Choose Link', // Images 'Insert Image': 'Insert Image', 'Upload Image': 'Upload Image', 'By URL': 'By URL', 'Browse': 'Browse', 'Drop image': 'Drop image', 'or click': 'or click', 'Manage Images': 'Manage Images', 'Loading': 'Loading', 'Deleting': 'Deleting', 'Tags': 'Tags', 'Are you sure? Image will be deleted.': 'Are you sure? Image will be deleted.', 'Replace': 'Replace', 'Uploading': 'Uploading', 'Loading image': 'Loading image', 'Display': 'Display', 'Inline': 'Inline', 'Break Text': 'Break Text', 'Alternative Text': 'Alternative Text', 'Change Size': 'Change Size', 'Width': 'Width', 'Height': 'Height', 'Something went wrong. Please try again.': 'Something went wrong. Please try again.', 'Image Caption': 'Image Caption', 'Advanced Edit': 'Advanced Edit', // Video 'Insert Video': 'Insert Video', 'Embedded Code': 'Embedded Code', 'Paste in a video URL': 'Paste in a video URL', 'Drop video': 'Drop video', 'Your browser does not support HTML5 video.': 'Your browser does not support HTML5 video.', 'Upload Video': 'Upload Video', // Tables 'Insert Table': 'Insert Table', 'Table Header': 'Table Header', 'Remove Table': 'Remove Table', 'Table Style': 'Table Style', 'Horizontal Align': 'Horizontal Align', 'Row': 'Row', 'Insert row above': 'Insert row above', 'Insert row below': 'Insert row below', 'Delete row': 'Delete row', 'Column': 'Column', 'Insert column before': 'Insert column before', 'Insert column after': 'Insert column after', 'Delete column': 'Delete column', 'Cell': 'Cell', 'Merge cells': 'Merge cells', 'Horizontal split': 'Horizontal split', 'Vertical split': 'Vertical split', 'Cell Background': 'Cell Background', 'Vertical Align': 'Vertical Align', 'Top': 'Top', 'Middle': 'Middle', 'Bottom': 'Bottom', 'Align Top': 'Align Top', 'Align Middle': 'Align Middle', 'Align Bottom': 'Align Bottom', 'Cell Style': 'Cell Style', // Files 'Upload File': 'Upload File', 'Drop file': 'Drop file', // Emoticons 'Emoticons': 'Emoticons', // Line breaker 'Break': 'Break', // Math 'Subscript': 'Subscript', 'Superscript': 'Superscript', // Full screen 'Fullscreen': 'Fullscreen', // Horizontal line 'Insert Horizontal Line': 'Insert Horizontal Line', // Clear formatting 'Clear Formatting': 'Clear Formatting', // Save 'Save': 'Save', // Undo, redo 'Undo': 'Undo', 'Redo': 'Redo', // Select all 'Select All': 'Select All', // Code view 'Code View': 'Code View', // Quote 'Quote': 'Quote', 'Increase': 'Increase', 'Decrease': 'Decrease', // Quick Insert 'Quick Insert': 'Quick Insert', // Spcial Characters 'Special Characters': 'Special Characters', 'Latin': 'Latin', 'Greek': 'Greek', 'Cyrillic': 'Cyrillic', 'Punctuation': 'Punctuation', 'Currency': 'Currency', 'Arrows': 'Arrows', 'Math': 'Math', 'Misc': 'Misc', // Print. 'Print': 'Print', // Spell Checker. 'Spell Checker': 'Spell Checker', // Help 'Help': 'Help', 'Shortcuts': 'Shortcuts', 'Inline Editor': 'Inline Editor', 'Show the editor': 'Show the editor', 'Common actions': 'Common actions', 'Copy': 'Copy', 'Cut': 'Cut', 'Paste': 'Paste', 'Basic Formatting': 'Basic Formatting', 'Increase quote level': 'Increase quote level', 'Decrease quote level': 'Decrease quote level', 'Image / Video': 'Image / Video', 'Resize larger': 'Resize larger', 'Resize smaller': 'Resize smaller', 'Table': 'Table', 'Select table cell': 'Select table cell', 'Extend selection one cell': 'Extend selection one cell', 'Extend selection one row': 'Extend selection one row', 'Navigation': 'Navigation', 'Focus popup / toolbar': 'Focus popup / toolbar', 'Return focus to previous position': 'Return focus to previous position', // Embed.ly 'Embed URL': 'Embed URL', 'Paste in a URL to embed': 'Paste in a URL to embed', // Word Paste. 'The pasted content is coming from a Microsoft Word document. Do you want to keep the format or clean it up?': 'The pasted content is coming from a Microsoft Word document. Do you want to keep the format or clean it up?', 'Keep': 'Keep', 'Clean': 'Clean', 'Word Paste Detected': 'Word Paste Detected', // Character Counter 'Characters': 'Characters', // More Buttons 'More Text': 'More Text', 'More Paragraph': 'More Paragraph', 'More Rich': 'More Rich', 'More Misc': 'More Misc' }, direction: 'ltr' }; }))); //# sourceMappingURL=en_ca.js.map
// Controller for post digest PostsSingledayController = RouteController.extend({ template: getTemplate('singleDay'), onBeforeAction: function () { this.render(getTemplate('postListTop'), {to: 'postListTop'}); this.next(); }, data: function() { var currentDate = this.params.day ? new Date(this.params.year, this.params.month-1, this.params.day) : Session.get('today'); Session.set('currentDate', currentDate); }, getTitle: function () { return i18n.t('single_day'); }, getDescription: function () { return i18n.t('posts_of_a_single_day'); }, fastRender: true }); Meteor.startup(function () { // Digest Router.route('/day/:year/:month/:day', { name: 'postsSingleDay', controller: PostsSingledayController }); Router.route('/day', { name: 'postsSingleDayDefault', controller: PostsSingledayController }); });
version https://git-lfs.github.com/spec/v1 oid sha256:2193df412ad76a1f54bc248bbcad8b3ab5f511ff9bb19a4750cc2627b6dd519b size 469
//= require jquery //= require jquery_ujs //= require turbolinks //= require spina //= require ./aviary //= require ./pages //= require ./account //= require ./confirm_delete
/* eslint-disable */ ;(function(root, factory) { if (typeof define === 'function' && define.amd) { // AMD define(['../core'], factory); } else if (typeof exports === 'object') { // Node.js module.exports = factory(require('../core')); } else { // Browser root.Blockly.Msg = factory(root.Blockly); } }(this, function(Blockly) { var Blockly = {};Blockly.Msg={};// This file was automatically generated. Do not modify. 'use strict'; Blockly.Msg["ADD_COMMENT"] = "افزودن نظر"; Blockly.Msg["CANNOT_DELETE_VARIABLE_PROCEDURE"] = "متغیر '%1' را نمی‌توان پاک کرد، زیرا جزیی از تعریف تابع '%2' می‌باشد"; Blockly.Msg["CHANGE_VALUE_TITLE"] = "تغییر مقدار:"; Blockly.Msg["CLEAN_UP"] = "تمیز کردن بلوک‌ها"; Blockly.Msg["COLLAPSED_WARNINGS_WARNING"] = "Collapsed blocks contain warnings."; // untranslated Blockly.Msg["COLLAPSE_ALL"] = "فروپاشی بلوک‌ها"; Blockly.Msg["COLLAPSE_BLOCK"] = "فروپاشی بلوک"; Blockly.Msg["COLOUR_BLEND_COLOUR1"] = "رنگ ۱"; Blockly.Msg["COLOUR_BLEND_COLOUR2"] = "رنگ ۲"; Blockly.Msg["COLOUR_BLEND_HELPURL"] = "https://meyerweb.com/eric/tools/color-blend/#:::rgbp"; // untranslated Blockly.Msg["COLOUR_BLEND_RATIO"] = "نسبت"; Blockly.Msg["COLOUR_BLEND_TITLE"] = "مخلوط"; Blockly.Msg["COLOUR_BLEND_TOOLTIP"] = "دو رنگ را با نسبت مشخص‌شده مخلوط می‌کند (۰٫۰ - ۱٫۰)"; Blockly.Msg["COLOUR_PICKER_HELPURL"] = "https://fa.wikipedia.org/wiki/%D8%B1%D9%86%DA%AF"; Blockly.Msg["COLOUR_PICKER_TOOLTIP"] = "انتخاب یک رنگ از تخته‌رنگ."; Blockly.Msg["COLOUR_RANDOM_HELPURL"] = "http://randomcolour.com"; // untranslated Blockly.Msg["COLOUR_RANDOM_TITLE"] = "رنگ تصادفی"; Blockly.Msg["COLOUR_RANDOM_TOOLTIP"] = "انتخاب یک رنگ به شکل تصادفی."; Blockly.Msg["COLOUR_RGB_BLUE"] = "آبی"; Blockly.Msg["COLOUR_RGB_GREEN"] = "سبز"; Blockly.Msg["COLOUR_RGB_HELPURL"] = "https://www.december.com/html/spec/colorpercompact.html"; // untranslated Blockly.Msg["COLOUR_RGB_RED"] = "قرمز"; Blockly.Msg["COLOUR_RGB_TITLE"] = "رنگ با"; Blockly.Msg["COLOUR_RGB_TOOLTIP"] = "ساخت یک رنگ با مقدار مشخص‌شده‌ای از قرمز، سبز و آبی. همهٔ مقادیر باید بین ۰ تا ۱۰۰ باشند."; Blockly.Msg["CONTROLS_FLOW_STATEMENTS_HELPURL"] = "https://github.com/google/blockly/wiki/Loops#loop-termination-blocks"; // untranslated Blockly.Msg["CONTROLS_FLOW_STATEMENTS_OPERATOR_BREAK"] = "خروج از حلقه"; Blockly.Msg["CONTROLS_FLOW_STATEMENTS_OPERATOR_CONTINUE"] = "ادامه با تکرار بعدی حلقه"; Blockly.Msg["CONTROLS_FLOW_STATEMENTS_TOOLTIP_BREAK"] = "شکستن حلقهٔ شامل."; Blockly.Msg["CONTROLS_FLOW_STATEMENTS_TOOLTIP_CONTINUE"] = "پریدن از بقیهٔ حلقه و ادامه با تکرار بعدی."; Blockly.Msg["CONTROLS_FLOW_STATEMENTS_WARNING"] = "اخطار: این بلوک ممکن است فقط داخل یک حلقه استفاده شود."; Blockly.Msg["CONTROLS_FOREACH_HELPURL"] = "https://github.com/google/blockly/wiki/Loops#for-each"; // untranslated Blockly.Msg["CONTROLS_FOREACH_TITLE"] = "برای هر مورد %1 در فهرست %2"; Blockly.Msg["CONTROLS_FOREACH_TOOLTIP"] = "برای هر مورد در این فهرست، تنظیم متغیر «%1» به مورد و انجام تعدادی عبارت."; Blockly.Msg["CONTROLS_FOR_HELPURL"] = "https://github.com/google/blockly/wiki/Loops#count-with"; // untranslated Blockly.Msg["CONTROLS_FOR_TITLE"] = "با تعداد %1 از %2 به %3 با گام‌های %4"; Blockly.Msg["CONTROLS_FOR_TOOLTIP"] = "متغیر %1 را در مقادیر شروع‌شده از عدد انتهای به عدد انتهایی را دارد، با فواصل مشخص‌شده می‌شمارد و این بلوک مشخص‌شده را انجام می‌دهد."; Blockly.Msg["CONTROLS_IF_ELSEIF_TOOLTIP"] = "افزودن یک شرط به بلوک اگر."; Blockly.Msg["CONTROLS_IF_ELSE_TOOLTIP"] = "اضافه کردن نهایی، گرفتن همهٔ شرایط به بلوک اگر."; Blockly.Msg["CONTROLS_IF_HELPURL"] = "https://github.com/google/blockly/wiki/IfElse"; // untranslated Blockly.Msg["CONTROLS_IF_IF_TOOLTIP"] = "افزودن، حذف یا بازمرتب‌سازی قسمت‌ها برای پیکربندی دوبارهٔ این بلوک اگر."; Blockly.Msg["CONTROLS_IF_MSG_ELSE"] = "درغیر اینصورت"; Blockly.Msg["CONTROLS_IF_MSG_ELSEIF"] = "درغیر اینصورت اگر"; Blockly.Msg["CONTROLS_IF_MSG_IF"] = "اگر"; Blockly.Msg["CONTROLS_IF_TOOLTIP_1"] = "اگر یک مقدار صحیح است، سپس چند عبارت را انجام بده."; Blockly.Msg["CONTROLS_IF_TOOLTIP_2"] = "اگر یک مقدار صحیح است، اول بلوک اول عبارات را انجام بده. در غیر این صورت بلوک دوم عبارات انجام بده."; Blockly.Msg["CONTROLS_IF_TOOLTIP_3"] = "اگر مقدار اول صحیح بود، از آن بلوک اول عبارات را انجام بده. در غیر این صورت، اگر مقدار دوم صحیح است، بلوک دوم عبارات را انجام بده."; Blockly.Msg["CONTROLS_IF_TOOLTIP_4"] = "اگر مقدار اول درست است، بلوک اول عبارات را انجام بده. در غیر این صورت، اگر مقدار دوم درست باشد بلوک دوم عبارات را انجام بده. اگر هیچ از مقادیر درست نبود، آخرین بلوک عبارات را انجام بده."; Blockly.Msg["CONTROLS_REPEAT_HELPURL"] = "https://fa.wikipedia.org/wiki/%D8%AD%D9%84%D9%82%D9%87_%D9%81%D9%88%D8%B1"; Blockly.Msg["CONTROLS_REPEAT_INPUT_DO"] = "انجام"; Blockly.Msg["CONTROLS_REPEAT_TITLE"] = "%1 بار تکرار"; Blockly.Msg["CONTROLS_REPEAT_TOOLTIP"] = "انجام چند عبارت چندین بار."; Blockly.Msg["CONTROLS_WHILEUNTIL_HELPURL"] = "https://github.com/google/blockly/wiki/Loops#repeat"; // untranslated Blockly.Msg["CONTROLS_WHILEUNTIL_OPERATOR_UNTIL"] = "تکرار تا زمانی که"; Blockly.Msg["CONTROLS_WHILEUNTIL_OPERATOR_WHILE"] = "تکرار در حالی که"; Blockly.Msg["CONTROLS_WHILEUNTIL_TOOLTIP_UNTIL"] = "تا زمانی که یک مقدار ناصحیح است، چند عبارت را انجام بده."; Blockly.Msg["CONTROLS_WHILEUNTIL_TOOLTIP_WHILE"] = "تا زمانی که یک مقدار صحیح است، چند عبارت را انجام بده."; Blockly.Msg["DELETE_ALL_BLOCKS"] = "حذف همهٔ بلاک‌های %1؟"; Blockly.Msg["DELETE_BLOCK"] = "حذف بلوک"; Blockly.Msg["DELETE_VARIABLE"] = "متغیر '%1'را پاک کنید"; Blockly.Msg["DELETE_VARIABLE_CONFIRMATION"] = "تعداد %1 استفاده از متغیر '%2' پاک شود؟"; Blockly.Msg["DELETE_X_BLOCKS"] = "حذف بلوک‌های %1"; Blockly.Msg["DISABLE_BLOCK"] = "غیرفعال‌سازی بلوک"; Blockly.Msg["DUPLICATE_BLOCK"] = "تکراری"; Blockly.Msg["DUPLICATE_COMMENT"] = "Duplicate Comment"; // untranslated Blockly.Msg["ENABLE_BLOCK"] = "فعال‌سازی بلوک"; Blockly.Msg["EXPAND_ALL"] = "گسترش بلوک‌ها"; Blockly.Msg["EXPAND_BLOCK"] = "گسترش بلوک"; Blockly.Msg["EXTERNAL_INPUTS"] = "ورودی‌های خارجی"; Blockly.Msg["HELP"] = "راهنما"; Blockly.Msg["INLINE_INPUTS"] = "ورودی‌های درون خطی"; Blockly.Msg["IOS_CANCEL"] = "لغو"; Blockly.Msg["IOS_ERROR"] = "خطا"; Blockly.Msg["IOS_OK"] = "تأیید"; Blockly.Msg["IOS_PROCEDURES_ADD_INPUT"] = "+ افزودن ورودی"; Blockly.Msg["IOS_PROCEDURES_ALLOW_STATEMENTS"] = "اجازه اظهارات"; Blockly.Msg["IOS_PROCEDURES_DUPLICATE_INPUTS_ERROR"] = "این تابع دارای ورودی‌های تکراری است."; Blockly.Msg["IOS_PROCEDURES_INPUTS"] = "ورودی‌ها"; Blockly.Msg["IOS_VARIABLES_ADD_BUTTON"] = "افزودن"; Blockly.Msg["IOS_VARIABLES_ADD_VARIABLE"] = "+ افزودن متغیر"; Blockly.Msg["IOS_VARIABLES_DELETE_BUTTON"] = "حذف"; Blockly.Msg["IOS_VARIABLES_EMPTY_NAME_ERROR"] = "نام متغیر نمی‌تواند خالی باشد"; Blockly.Msg["IOS_VARIABLES_RENAME_BUTTON"] = "تغییر نام"; Blockly.Msg["IOS_VARIABLES_VARIABLE_NAME"] = "نام متغیر"; Blockly.Msg["LISTS_CREATE_EMPTY_HELPURL"] = "https://github.com/google/blockly/wiki/Lists#create-empty-list"; // untranslated Blockly.Msg["LISTS_CREATE_EMPTY_TITLE"] = "ایجاد فهرست خالی"; Blockly.Msg["LISTS_CREATE_EMPTY_TOOLTIP"] = "فهرستی با طول صفر شامل هیچ رکورد داده‌ای بر می‌گرداند."; Blockly.Msg["LISTS_CREATE_WITH_CONTAINER_TITLE_ADD"] = "فهرست"; Blockly.Msg["LISTS_CREATE_WITH_CONTAINER_TOOLTIP"] = "اضافه کردن، حذف کردن یا ترتیب‌سازی مجدد بخش‌ها این بلوک فهرستی."; Blockly.Msg["LISTS_CREATE_WITH_HELPURL"] = "https://github.com/google/blockly/wiki/Lists#create-list-with"; // untranslated Blockly.Msg["LISTS_CREATE_WITH_INPUT_WITH"] = "ایجاد فهرست با"; Blockly.Msg["LISTS_CREATE_WITH_ITEM_TOOLTIP"] = "اضافه کردن یک مورد به فهرست."; Blockly.Msg["LISTS_CREATE_WITH_TOOLTIP"] = "فهرستی از هر عددی از موارد می‌سازد."; Blockly.Msg["LISTS_GET_INDEX_FIRST"] = "اولین"; Blockly.Msg["LISTS_GET_INDEX_FROM_END"] = "# از انتها"; Blockly.Msg["LISTS_GET_INDEX_FROM_START"] = "#"; // untranslated Blockly.Msg["LISTS_GET_INDEX_GET"] = "گرفتن"; Blockly.Msg["LISTS_GET_INDEX_GET_REMOVE"] = "گرفتن و حذف‌کردن"; Blockly.Msg["LISTS_GET_INDEX_LAST"] = "آخرین"; Blockly.Msg["LISTS_GET_INDEX_RANDOM"] = "تصادفی"; Blockly.Msg["LISTS_GET_INDEX_REMOVE"] = "حذف‌کردن"; Blockly.Msg["LISTS_GET_INDEX_TAIL"] = ""; // untranslated Blockly.Msg["LISTS_GET_INDEX_TOOLTIP_GET_FIRST"] = "اولین مورد یک فهرست را بر می‌گرداند."; Blockly.Msg["LISTS_GET_INDEX_TOOLTIP_GET_FROM"] = "موردی در محل مشخص‌شده بر می‌گرداند."; Blockly.Msg["LISTS_GET_INDEX_TOOLTIP_GET_LAST"] = "آخرین مورد در یک فهرست را بر می‌گرداند."; Blockly.Msg["LISTS_GET_INDEX_TOOLTIP_GET_RANDOM"] = "یک مورد تصادفی در یک فهرست بر می‌گرداند."; Blockly.Msg["LISTS_GET_INDEX_TOOLTIP_GET_REMOVE_FIRST"] = "اولین مورد مشخص‌شده در فهرست را حذف و بر می‌گرداند."; Blockly.Msg["LISTS_GET_INDEX_TOOLTIP_GET_REMOVE_FROM"] = "مورد در محل مشخص‌شده در فهرست را حذف و بر می‌گرداند."; Blockly.Msg["LISTS_GET_INDEX_TOOLTIP_GET_REMOVE_LAST"] = "آخرین مورد مشخص‌شده در فهرست را حذف و بر می‌گرداند."; Blockly.Msg["LISTS_GET_INDEX_TOOLTIP_GET_REMOVE_RANDOM"] = "مورد تصادفی‌ای را در فهرست حذف و بر می‌گرداند."; Blockly.Msg["LISTS_GET_INDEX_TOOLTIP_REMOVE_FIRST"] = "اولین مورد را در یک فهرست حذف می‌کند."; Blockly.Msg["LISTS_GET_INDEX_TOOLTIP_REMOVE_FROM"] = "مورد مشخص‌شده در موقعیت مشخص در یک فهرست را حذف و بر می‌گرداند."; Blockly.Msg["LISTS_GET_INDEX_TOOLTIP_REMOVE_LAST"] = "آخرین مورد را در یک فهرست حذف می‌کند."; Blockly.Msg["LISTS_GET_INDEX_TOOLTIP_REMOVE_RANDOM"] = "یک مورد تصادفی را یک فهرست حذف می‌کند."; Blockly.Msg["LISTS_GET_SUBLIST_END_FROM_END"] = "به # از انتها"; Blockly.Msg["LISTS_GET_SUBLIST_END_FROM_START"] = "به #"; Blockly.Msg["LISTS_GET_SUBLIST_END_LAST"] = "به آخرین"; Blockly.Msg["LISTS_GET_SUBLIST_HELPURL"] = "https://github.com/google/blockly/wiki/Lists#getting-a-sublist"; // untranslated Blockly.Msg["LISTS_GET_SUBLIST_START_FIRST"] = "گرفتن زیرمجموعه‌ای از ابتدا"; Blockly.Msg["LISTS_GET_SUBLIST_START_FROM_END"] = "گرفتن زیرمجموعه‌ای از # از انتها"; Blockly.Msg["LISTS_GET_SUBLIST_START_FROM_START"] = "گرفتن زیرمجموعه‌ای از #"; Blockly.Msg["LISTS_GET_SUBLIST_TAIL"] = ""; // untranslated Blockly.Msg["LISTS_GET_SUBLIST_TOOLTIP"] = "کپی از قسمت مشخص‌شدهٔ لیست درست می‌کند."; Blockly.Msg["LISTS_INDEX_FROM_END_TOOLTIP"] = "%1 آخرین مورد است."; Blockly.Msg["LISTS_INDEX_FROM_START_TOOLTIP"] = "%1 اولین مورد است."; Blockly.Msg["LISTS_INDEX_OF_FIRST"] = "یافتن اولین رخ‌داد مورد"; Blockly.Msg["LISTS_INDEX_OF_HELPURL"] = "https://github.com/google/blockly/wiki/Lists#getting-items-from-a-list"; // untranslated Blockly.Msg["LISTS_INDEX_OF_LAST"] = "یافتن آخرین رخ‌داد مورد"; Blockly.Msg["LISTS_INDEX_OF_TOOLTIP"] = "شاخصی از اولین/آخرین رخ‌داد مورد در فهرست را بر می‌گرداند. %1 بر می‌گرداند اگر آیتم موجود نبود."; Blockly.Msg["LISTS_INLIST"] = "در فهرست"; Blockly.Msg["LISTS_ISEMPTY_HELPURL"] = "https://github.com/google/blockly/wiki/Lists#is-empty"; // untranslated Blockly.Msg["LISTS_ISEMPTY_TITLE"] = "%1 خالی است"; Blockly.Msg["LISTS_ISEMPTY_TOOLTIP"] = "اگر فهرست خالی است مقدار صجیج بر می‌گرداند."; Blockly.Msg["LISTS_LENGTH_HELPURL"] = "https://github.com/google/blockly/wiki/Lists#length-of"; // untranslated Blockly.Msg["LISTS_LENGTH_TITLE"] = "طول %1"; Blockly.Msg["LISTS_LENGTH_TOOLTIP"] = "طول یک فهرست را برمی‌گرداند."; Blockly.Msg["LISTS_REPEAT_HELPURL"] = "https://github.com/google/blockly/wiki/Lists#create-list-with"; // untranslated Blockly.Msg["LISTS_REPEAT_TITLE"] = "فهرستی با %1 تکرارشده به اندازهٔ %2 می‌سازد"; Blockly.Msg["LISTS_REPEAT_TOOLTIP"] = "فهرستی شامل مقادیر داده‌شدهٔ تکرار شده عدد مشخص‌شده می‌سازد."; Blockly.Msg["LISTS_REVERSE_HELPURL"] = "https://github.com/google/blockly/wiki/Lists#reversing-a-list"; // untranslated Blockly.Msg["LISTS_REVERSE_MESSAGE0"] = "معکوس %1"; Blockly.Msg["LISTS_REVERSE_TOOLTIP"] = "یک کپی از لیست را معکوس کنید."; Blockly.Msg["LISTS_SET_INDEX_HELPURL"] = "https://github.com/google/blockly/wiki/Lists#in-list--set"; // untranslated Blockly.Msg["LISTS_SET_INDEX_INPUT_TO"] = "به عنوان"; Blockly.Msg["LISTS_SET_INDEX_INSERT"] = "درج در"; Blockly.Msg["LISTS_SET_INDEX_SET"] = "اعمال"; Blockly.Msg["LISTS_SET_INDEX_TOOLTIP_INSERT_FIRST"] = "موردی به ته فهرست اضافه می‌کند."; Blockly.Msg["LISTS_SET_INDEX_TOOLTIP_INSERT_FROM"] = "موردی در موقعیت مشخص‌شده در یک فهرست اضافه می‌کند."; Blockly.Msg["LISTS_SET_INDEX_TOOLTIP_INSERT_LAST"] = "موردی به ته فهرست الحاق می‌کند."; Blockly.Msg["LISTS_SET_INDEX_TOOLTIP_INSERT_RANDOM"] = "مورد را به صورت تصادفی در یک فهرست می‌افزاید."; Blockly.Msg["LISTS_SET_INDEX_TOOLTIP_SET_FIRST"] = "اولین مورد در یک فهرست را تعیین می‌کند."; Blockly.Msg["LISTS_SET_INDEX_TOOLTIP_SET_FROM"] = "مورد مشخص‌شده در یک فهرست را قرار می‌دهد."; Blockly.Msg["LISTS_SET_INDEX_TOOLTIP_SET_LAST"] = "آخرین مورد در یک فهرست را تعیین می‌کند."; Blockly.Msg["LISTS_SET_INDEX_TOOLTIP_SET_RANDOM"] = "یک مورد تصادفی در یک فهرست را تعیین می‌کند."; Blockly.Msg["LISTS_SORT_HELPURL"] = "https://github.com/google/blockly/wiki/Lists#sorting-a-list"; Blockly.Msg["LISTS_SORT_ORDER_ASCENDING"] = "صعودی"; Blockly.Msg["LISTS_SORT_ORDER_DESCENDING"] = "نزولی"; Blockly.Msg["LISTS_SORT_TITLE"] = "مرتب‌سازی%1 %2 %3"; Blockly.Msg["LISTS_SORT_TOOLTIP"] = "یک کپی از لیست را مرتب کنید."; Blockly.Msg["LISTS_SORT_TYPE_IGNORECASE"] = "حروفی ، رد کردن مورد"; Blockly.Msg["LISTS_SORT_TYPE_NUMERIC"] = "عددی"; Blockly.Msg["LISTS_SORT_TYPE_TEXT"] = "حروفی ، الفبایی"; Blockly.Msg["LISTS_SPLIT_HELPURL"] = "https://github.com/google/blockly/wiki/Lists#splitting-strings-and-joining-lists"; // untranslated Blockly.Msg["LISTS_SPLIT_LIST_FROM_TEXT"] = "ایجاد فهرست از متن"; Blockly.Msg["LISTS_SPLIT_TEXT_FROM_LIST"] = "ایجاد متن از فهرست"; Blockly.Msg["LISTS_SPLIT_TOOLTIP_JOIN"] = "چسباندن یک فهرست از متن‌ها و تشکیل یک متن که با یک جداکننده جدا شده‌اند"; Blockly.Msg["LISTS_SPLIT_TOOLTIP_SPLIT"] = "شکستن متن به فهرستی از متن‌ها، شکستن در محل جداکننده"; Blockly.Msg["LISTS_SPLIT_WITH_DELIMITER"] = "همراه جداساز"; Blockly.Msg["LOGIC_BOOLEAN_FALSE"] = "ناصحیح"; Blockly.Msg["LOGIC_BOOLEAN_HELPURL"] = "https://github.com/google/blockly/wiki/Logic#values"; // untranslated Blockly.Msg["LOGIC_BOOLEAN_TOOLTIP"] = "بازگرداندن یکی از صحیح یا ناصحیح."; Blockly.Msg["LOGIC_BOOLEAN_TRUE"] = "صحیح"; Blockly.Msg["LOGIC_COMPARE_HELPURL"] = "https://fa.wikipedia.org/wiki/%D9%86%D8%A7%D8%A8%D8%B1%D8%A7%D8%A8%D8%B1%DB%8C"; Blockly.Msg["LOGIC_COMPARE_TOOLTIP_EQ"] = "بازگشت صحیح اگر هر دو ورودی با یکدیگر برابر باشد."; Blockly.Msg["LOGIC_COMPARE_TOOLTIP_GT"] = "بازگرداندن صحیح اگر ورودی اول بزرگتر از ورودی دوم باشد."; Blockly.Msg["LOGIC_COMPARE_TOOLTIP_GTE"] = "بازگرداندن صحیح اگر ورودی اول بزرگتر یا مساوی یا ورودی دوم باشد."; Blockly.Msg["LOGIC_COMPARE_TOOLTIP_LT"] = "بازگرداندن صحیح اگر ورودی اول کوچکتر از ورودی دوم باشد."; Blockly.Msg["LOGIC_COMPARE_TOOLTIP_LTE"] = "بازگرداندن صحیح اگر ورودی اول کوچکتر یا مساوی با ورودی دوم باشد."; Blockly.Msg["LOGIC_COMPARE_TOOLTIP_NEQ"] = "برگرداندن صحیح اگر هر دو ورودی با یکدیگر برابر نباشند."; Blockly.Msg["LOGIC_NEGATE_HELPURL"] = "https://github.com/google/blockly/wiki/Logic#not"; // untranslated Blockly.Msg["LOGIC_NEGATE_TITLE"] = "نه %1"; Blockly.Msg["LOGIC_NEGATE_TOOLTIP"] = "صجیج باز می‌گرداند اگر ورودی نا صحیح باشند. ناصحیح بازمی‌گرداند اگر ورودی صحیح باشد."; Blockly.Msg["LOGIC_NULL"] = "تهی"; Blockly.Msg["LOGIC_NULL_HELPURL"] = "https://en.wikipedia.org/wiki/Nullable_type"; // untranslated Blockly.Msg["LOGIC_NULL_TOOLTIP"] = "تهی بازمی‌گرداند."; Blockly.Msg["LOGIC_OPERATION_AND"] = "و"; Blockly.Msg["LOGIC_OPERATION_HELPURL"] = "https://github.com/google/blockly/wiki/Logic#logical-operations"; // untranslated Blockly.Msg["LOGIC_OPERATION_OR"] = "یا"; Blockly.Msg["LOGIC_OPERATION_TOOLTIP_AND"] = "بازگرداندن صحیح اگر هر دو ورودی صحیح باشد."; Blockly.Msg["LOGIC_OPERATION_TOOLTIP_OR"] = "بازگرداندن صحیح اگر یکی از دو ورودی صحیح باشد."; Blockly.Msg["LOGIC_TERNARY_CONDITION"] = "آزمایش"; Blockly.Msg["LOGIC_TERNARY_HELPURL"] = "https://en.wikipedia.org/wiki/%3F:"; // untranslated Blockly.Msg["LOGIC_TERNARY_IF_FALSE"] = "اگر ناصحیح"; Blockly.Msg["LOGIC_TERNARY_IF_TRUE"] = "اگر صحیح"; Blockly.Msg["LOGIC_TERNARY_TOOLTIP"] = "بررسی وضعیت در «آزمایش». اگر وضعیت صحیح باشد، مقدار «اگر صحیح» را بر می‌گرداند در غیر اینصورت مقدار «اگر ناصحیح» را."; Blockly.Msg["MATH_ADDITION_SYMBOL"] = "+"; // untranslated Blockly.Msg["MATH_ARITHMETIC_HELPURL"] = "https://fa.wikipedia.org/wiki/%D8%AD%D8%B3%D8%A7%D8%A8"; Blockly.Msg["MATH_ARITHMETIC_TOOLTIP_ADD"] = "بازگرداندن مقدار جمع دو عدد."; Blockly.Msg["MATH_ARITHMETIC_TOOLTIP_DIVIDE"] = "بازگرداندن باقی‌ماندهٔ دو عدد."; Blockly.Msg["MATH_ARITHMETIC_TOOLTIP_MINUS"] = "بازگرداندن تفاوت دو عدد."; Blockly.Msg["MATH_ARITHMETIC_TOOLTIP_MULTIPLY"] = "بازگرداندن حاصلضرب دو عدد."; Blockly.Msg["MATH_ARITHMETIC_TOOLTIP_POWER"] = "بازگرداندن اولین عددی که از توان عدد دوم حاصل شده باشد."; Blockly.Msg["MATH_ATAN2_HELPURL"] = "https://en.wikipedia.org/wiki/Atan2"; // untranslated Blockly.Msg["MATH_ATAN2_TITLE"] = "atan2 of X:%1 Y:%2"; // untranslated Blockly.Msg["MATH_ATAN2_TOOLTIP"] = "Return the arctangent of point (X, Y) in degrees from -180 to 180."; // untranslated Blockly.Msg["MATH_CHANGE_HELPURL"] = "https://fa.wikipedia.org/wiki/%D8%A7%D8%B5%D8%B7%D9%84%D8%A7%D8%AD_%D8%A8%D8%B1%D9%86%D8%A7%D9%85%D9%87%E2%80%8C%D9%86%D9%88%DB%8C%D8%B3%DB%8C#.D8.A7.D9.81.D8.B2.D8.A7.DB.8C.D8.B4_.D8.B4.D9.85.D8.A7.D8.B1.D9.86.D8.AF.D9.87"; Blockly.Msg["MATH_CHANGE_TITLE"] = "تغییر %1 با %2"; Blockly.Msg["MATH_CHANGE_TOOLTIP"] = "افزودن یک عدد به متغیر '%1'."; Blockly.Msg["MATH_CONSTANT_HELPURL"] = "https://fa.wikipedia.org/wiki/%D8%AB%D8%A7%D8%A8%D8%AA_%D8%B1%DB%8C%D8%A7%D8%B6%DB%8C"; Blockly.Msg["MATH_CONSTANT_TOOLTIP"] = "یکی از مقادیر ثابت جهانی را برمی‌گرداند: π (۳٫۱۴۱…)، e (۲٫۷۱۸...)، φ (۱٫۶۱۸)، sqrt(۲) (۱٫۴۱۴)، sqrt(۱/۲) (۰٫۷۰۷...) و یا ∞ (بی‌نهایت)."; Blockly.Msg["MATH_CONSTRAIN_HELPURL"] = "https://en.wikipedia.org/wiki/Clamping_(graphics)"; // untranslated Blockly.Msg["MATH_CONSTRAIN_TITLE"] = "محدودکردن %1 پایین %2 بالا %3"; Blockly.Msg["MATH_CONSTRAIN_TOOLTIP"] = "محدودکردن یک عدد بین محدودیت‌های مشخص‌شده (بسته)."; Blockly.Msg["MATH_DIVISION_SYMBOL"] = "÷"; // untranslated Blockly.Msg["MATH_IS_DIVISIBLE_BY"] = "تقسیم شده بر"; Blockly.Msg["MATH_IS_EVEN"] = "زوج است"; Blockly.Msg["MATH_IS_NEGATIVE"] = "منفی است"; Blockly.Msg["MATH_IS_ODD"] = "فرد است"; Blockly.Msg["MATH_IS_POSITIVE"] = "مثبت است"; Blockly.Msg["MATH_IS_PRIME"] = "عدد اول است"; Blockly.Msg["MATH_IS_TOOLTIP"] = "بررسی می‌کند که آیا یک عدد زوج، فرد، اول، کامل، مثبت، منفی یا بخش‌پذیر عدد خاصی باشد را بررسی می‌کند. درست یا نادرست باز می‌گرداند."; Blockly.Msg["MATH_IS_WHOLE"] = "کامل است"; Blockly.Msg["MATH_MODULO_HELPURL"] = "https://fa.wikipedia.org/wiki/%D8%B9%D9%85%D9%84%DB%8C%D8%A7%D8%AA_%D9%BE%DB%8C%D9%85%D8%A7%D9%86%D9%87"; Blockly.Msg["MATH_MODULO_TITLE"] = "باقی‌ماندهٔ %1 ÷ %2"; Blockly.Msg["MATH_MODULO_TOOLTIP"] = "باقی‌ماندهٔ تقسیم دو عدد را بر می‌گرداند."; Blockly.Msg["MATH_MULTIPLICATION_SYMBOL"] = "×"; // untranslated Blockly.Msg["MATH_NUMBER_HELPURL"] = "https://fa.wikipedia.org/wiki/%D8%B9%D8%AF%D8%AF"; Blockly.Msg["MATH_NUMBER_TOOLTIP"] = "یک عدد."; Blockly.Msg["MATH_ONLIST_HELPURL"] = ""; // untranslated Blockly.Msg["MATH_ONLIST_OPERATOR_AVERAGE"] = "میانگین فهرست"; Blockly.Msg["MATH_ONLIST_OPERATOR_MAX"] = "بزرگ‌ترین عدد در فهرست"; Blockly.Msg["MATH_ONLIST_OPERATOR_MEDIAN"] = "میانهٔ فهرست"; Blockly.Msg["MATH_ONLIST_OPERATOR_MIN"] = "کوچک‌ترین عدد در فهرست"; Blockly.Msg["MATH_ONLIST_OPERATOR_MODE"] = "مد فهرست"; Blockly.Msg["MATH_ONLIST_OPERATOR_RANDOM"] = "مورد تصادفی از فهرست"; Blockly.Msg["MATH_ONLIST_OPERATOR_STD_DEV"] = "انحراف معیار فهرست"; Blockly.Msg["MATH_ONLIST_OPERATOR_SUM"] = "جمع فهرست"; Blockly.Msg["MATH_ONLIST_TOOLTIP_AVERAGE"] = "میانگین (میانگین ریاضی) مقادیر عددی فهرست را بر می‌گرداند."; Blockly.Msg["MATH_ONLIST_TOOLTIP_MAX"] = "بزرگ‌ترین عدد در فهرست را باز می‌گرداند."; Blockly.Msg["MATH_ONLIST_TOOLTIP_MEDIAN"] = "میانهٔ عدد در فهرست را بر می‌گرداند."; Blockly.Msg["MATH_ONLIST_TOOLTIP_MIN"] = "کوچک‌ترین عدد در فهرست را باز می‌گرداند."; Blockly.Msg["MATH_ONLIST_TOOLTIP_MODE"] = "شایع‌ترین قلم(های) در فهرست را بر می‌گرداند."; Blockly.Msg["MATH_ONLIST_TOOLTIP_RANDOM"] = "موردی تصادفی از فهرست را بر می‌گرداند."; Blockly.Msg["MATH_ONLIST_TOOLTIP_STD_DEV"] = "انحراف معیار فهرست را بر می‌گرداند."; Blockly.Msg["MATH_ONLIST_TOOLTIP_SUM"] = "جمع همهٔ عددهای فهرست را باز می‌گرداند."; Blockly.Msg["MATH_POWER_SYMBOL"] = "^"; // untranslated Blockly.Msg["MATH_RANDOM_FLOAT_HELPURL"] = "https://fa.wikipedia.org/wiki/%D8%AA%D9%88%D9%84%DB%8C%D8%AF_%D8%A7%D8%B9%D8%AF%D8%A7%D8%AF_%D8%AA%D8%B5%D8%A7%D8%AF%D9%81%DB%8C"; Blockly.Msg["MATH_RANDOM_FLOAT_TITLE_RANDOM"] = "کسر تصادفی"; Blockly.Msg["MATH_RANDOM_FLOAT_TOOLTIP"] = "بازگرداندن کسری تصادفی بین ۰٫۰ (بسته) تا ۱٫۰ (باز)."; Blockly.Msg["MATH_RANDOM_INT_HELPURL"] = "https://fa.wikipedia.org/wiki/%D8%AA%D9%88%D9%84%DB%8C%D8%AF_%D8%A7%D8%B9%D8%AF%D8%A7%D8%AF_%D8%AA%D8%B5%D8%A7%D8%AF%D9%81%DB%8C"; Blockly.Msg["MATH_RANDOM_INT_TITLE"] = "عدد صحیح تصادفی بین %1 تا %2"; Blockly.Msg["MATH_RANDOM_INT_TOOLTIP"] = "یک عدد تصادفی بین دو مقدار مشخص‌شده به صورت بسته باز می‌گرداند."; Blockly.Msg["MATH_ROUND_HELPURL"] = "https://fa.wikipedia.org/wiki/%D8%B1%D9%88%DB%8C%D9%87_%28%D8%B9%D9%84%D9%88%D9%85_%D8%B1%D8%A7%DB%8C%D8%A7%D9%86%D9%87%29"; Blockly.Msg["MATH_ROUND_OPERATOR_ROUND"] = "گردکردن"; Blockly.Msg["MATH_ROUND_OPERATOR_ROUNDDOWN"] = "گرد به پایین"; Blockly.Msg["MATH_ROUND_OPERATOR_ROUNDUP"] = "گرد به بالا"; Blockly.Msg["MATH_ROUND_TOOLTIP"] = "گردکردن یک عدد به بالا یا پایین."; Blockly.Msg["MATH_SINGLE_HELPURL"] = "https://fa.wikipedia.org/wiki/%D8%B1%DB%8C%D8%B4%D9%87_%D8%AF%D9%88%D9%85"; Blockly.Msg["MATH_SINGLE_OP_ABSOLUTE"] = "مطلق"; Blockly.Msg["MATH_SINGLE_OP_ROOT"] = "ریشهٔ دوم"; Blockly.Msg["MATH_SINGLE_TOOLTIP_ABS"] = "قدر مطلق یک عدد را بازمی‌گرداند."; Blockly.Msg["MATH_SINGLE_TOOLTIP_EXP"] = "بازگرداندن توان e یک عدد."; Blockly.Msg["MATH_SINGLE_TOOLTIP_LN"] = "لوگاریتم طبیعی یک عدد را باز می‌گرداند."; Blockly.Msg["MATH_SINGLE_TOOLTIP_LOG10"] = "بازگرداندن لگاریتم بر پایهٔ ۱۰ یک عدد."; Blockly.Msg["MATH_SINGLE_TOOLTIP_NEG"] = "منفی‌شدهٔ یک عدد را باز می‌گرداند."; Blockly.Msg["MATH_SINGLE_TOOLTIP_POW10"] = "بازگرداندن توان ۱۰ یک عدد."; Blockly.Msg["MATH_SINGLE_TOOLTIP_ROOT"] = "ریشهٔ دوم یک عدد را باز می‌گرداند."; Blockly.Msg["MATH_SUBTRACTION_SYMBOL"] = "-"; // untranslated Blockly.Msg["MATH_TRIG_ACOS"] = "acos"; // untranslated Blockly.Msg["MATH_TRIG_ASIN"] = "asin"; // untranslated Blockly.Msg["MATH_TRIG_ATAN"] = "atan"; // untranslated Blockly.Msg["MATH_TRIG_COS"] = "cos"; // untranslated Blockly.Msg["MATH_TRIG_HELPURL"] = "https://fa.wikipedia.org/wiki/%D8%AA%D8%A7%D8%A8%D8%B9%E2%80%8C%D9%87%D8%A7%DB%8C_%D9%85%D8%AB%D9%84%D8%AB%D8%A7%D8%AA%DB%8C"; Blockly.Msg["MATH_TRIG_SIN"] = "sin"; // untranslated Blockly.Msg["MATH_TRIG_TAN"] = "tan"; // untranslated Blockly.Msg["MATH_TRIG_TOOLTIP_ACOS"] = "بازگرداندن آرک‌کسینوس درجه (نه رادیان)."; Blockly.Msg["MATH_TRIG_TOOLTIP_ASIN"] = "بازگرداندن آرک‌سینوس درجه (نه رادیان)."; Blockly.Msg["MATH_TRIG_TOOLTIP_ATAN"] = "بازگرداندن آرک‌تانژانت درجه (نه رادیان)."; Blockly.Msg["MATH_TRIG_TOOLTIP_COS"] = "بازگرداندن کسینوس یک زاویه درجه (نه رادیان)."; Blockly.Msg["MATH_TRIG_TOOLTIP_SIN"] = "بازگرداندن سینوس یک زاویه به درجه (نه رادیان)."; Blockly.Msg["MATH_TRIG_TOOLTIP_TAN"] = "بازگرداندن تانژانت یک زاویه به درجه (نه رادیان)."; Blockly.Msg["NEW_COLOUR_VARIABLE"] = "ساخت متغیر رنگ..."; Blockly.Msg["NEW_NUMBER_VARIABLE"] = "ساخت متغیر عددی..."; Blockly.Msg["NEW_STRING_VARIABLE"] = "ساخت متغیر رشته..."; Blockly.Msg["NEW_VARIABLE"] = "ایجاد متغیر..."; Blockly.Msg["NEW_VARIABLE_TITLE"] = "نام متغیر تازه:"; Blockly.Msg["NEW_VARIABLE_TYPE_TITLE"] = "نوع متغیر جدید:"; Blockly.Msg["ORDINAL_NUMBER_SUFFIX"] = ""; // untranslated Blockly.Msg["PROCEDURES_ALLOW_STATEMENTS"] = "اجازه اظهارات"; Blockly.Msg["PROCEDURES_BEFORE_PARAMS"] = "با:"; Blockly.Msg["PROCEDURES_CALLNORETURN_HELPURL"] = "https://fa.wikipedia.org/wiki/%D8%B1%D9%88%DB%8C%D9%87_(%D8%B9%D9%84%D9%88%D9%85_%D8%B1%D8%A7%DB%8C%D8%A7%D9%86%D9%87)"; Blockly.Msg["PROCEDURES_CALLNORETURN_TOOLTIP"] = "اجرای تابع تعریف‌شده توسط کاربر «%1»."; Blockly.Msg["PROCEDURES_CALLRETURN_HELPURL"] = "https://fa.wikipedia.org/wiki/%D8%B1%D9%88%DB%8C%D9%87_%28%D8%B9%D9%84%D9%88%D9%85_%D8%B1%D8%A7%DB%8C%D8%A7%D9%86%D9%87%29"; Blockly.Msg["PROCEDURES_CALLRETURN_TOOLTIP"] = "اجرای تابع تعریف‌شده توسط کاربر «%1» و استفاده از خروجی آن."; Blockly.Msg["PROCEDURES_CALL_BEFORE_PARAMS"] = "با:"; Blockly.Msg["PROCEDURES_CREATE_DO"] = "ساختن «%1»"; Blockly.Msg["PROCEDURES_DEFNORETURN_COMMENT"] = "توصیف این عملکرد..."; Blockly.Msg["PROCEDURES_DEFNORETURN_DO"] = ""; // untranslated Blockly.Msg["PROCEDURES_DEFNORETURN_HELPURL"] = "https://en.wikipedia.org/wiki/Subroutine"; // untranslated Blockly.Msg["PROCEDURES_DEFNORETURN_PROCEDURE"] = "انجام چیزی"; Blockly.Msg["PROCEDURES_DEFNORETURN_TITLE"] = "به"; Blockly.Msg["PROCEDURES_DEFNORETURN_TOOLTIP"] = "تابعی می‌سازد بدون هیچ خروجی."; Blockly.Msg["PROCEDURES_DEFRETURN_HELPURL"] = "https://en.wikipedia.org/wiki/Subroutine"; // untranslated Blockly.Msg["PROCEDURES_DEFRETURN_RETURN"] = "بازگشت"; Blockly.Msg["PROCEDURES_DEFRETURN_TOOLTIP"] = "تابعی با یک خروجی می‌سازد."; Blockly.Msg["PROCEDURES_DEF_DUPLICATE_WARNING"] = "اخطار: این تابعی پارامتر تکراری دارد."; Blockly.Msg["PROCEDURES_HIGHLIGHT_DEF"] = "برجسته‌سازی تعریف تابع"; Blockly.Msg["PROCEDURES_IFRETURN_HELPURL"] = "http://c2.com/cgi/wiki?GuardClause"; // untranslated Blockly.Msg["PROCEDURES_IFRETURN_TOOLTIP"] = "اگر یک مقدار صحیح است، مقدار دوم را برگردان."; Blockly.Msg["PROCEDURES_IFRETURN_WARNING"] = "اخطار: این بلوک احتمالاً فقط داخل یک تابع استفاده می‌شود."; Blockly.Msg["PROCEDURES_MUTATORARG_TITLE"] = "نام ورودی:"; Blockly.Msg["PROCEDURES_MUTATORARG_TOOLTIP"] = "اضافه کردن ورودی به تابع."; Blockly.Msg["PROCEDURES_MUTATORCONTAINER_TITLE"] = "ورودی‌ها"; Blockly.Msg["PROCEDURES_MUTATORCONTAINER_TOOLTIP"] = "افزودن، حذف یا دوباره مرتب‌کردن ورودی این تابع."; Blockly.Msg["REDO"] = "انجام دوباره"; Blockly.Msg["REMOVE_COMMENT"] = "حذف نظر"; Blockly.Msg["RENAME_VARIABLE"] = "تغییر نام متغیر..."; Blockly.Msg["RENAME_VARIABLE_TITLE"] = "تغییر نام همهٔ متغیرهای «%1» به:"; Blockly.Msg["TEXT_APPEND_HELPURL"] = "https://github.com/google/blockly/wiki/Text#text-modification"; // untranslated Blockly.Msg["TEXT_APPEND_TITLE"] = "به %1 الحاق متن %2"; Blockly.Msg["TEXT_APPEND_TOOLTIP"] = "الحاق متنی به متغیر «%1»."; Blockly.Msg["TEXT_CHANGECASE_HELPURL"] = "https://github.com/google/blockly/wiki/Text#adjusting-text-case"; // untranslated Blockly.Msg["TEXT_CHANGECASE_OPERATOR_LOWERCASE"] = "به حروف کوچک"; Blockly.Msg["TEXT_CHANGECASE_OPERATOR_TITLECASE"] = "به حروف بزرگ عنوان"; Blockly.Msg["TEXT_CHANGECASE_OPERATOR_UPPERCASE"] = "به حروف بزرگ"; Blockly.Msg["TEXT_CHANGECASE_TOOLTIP"] = "بازگرداندن کپی متن در حالتی متفاوت."; Blockly.Msg["TEXT_CHARAT_FIRST"] = "گرفتن اولین حرف"; Blockly.Msg["TEXT_CHARAT_FROM_END"] = "گرفتن حرف # از آخر"; Blockly.Msg["TEXT_CHARAT_FROM_START"] = "گرفتن حرف #"; Blockly.Msg["TEXT_CHARAT_HELPURL"] = "https://github.com/google/blockly/wiki/Text#extracting-text"; // untranslated Blockly.Msg["TEXT_CHARAT_LAST"] = "گرفتن آخرین حرف"; Blockly.Msg["TEXT_CHARAT_RANDOM"] = "گرفتن حرف تصادفی"; Blockly.Msg["TEXT_CHARAT_TAIL"] = ""; // untranslated Blockly.Msg["TEXT_CHARAT_TITLE"] = "در متن %1 %2"; Blockly.Msg["TEXT_CHARAT_TOOLTIP"] = "حرفی در موقعیت مشخص‌شده بر می‌گرداند."; Blockly.Msg["TEXT_COUNT_HELPURL"] = "https://github.com/google/blockly/wiki/Text#counting-substrings"; // untranslated Blockly.Msg["TEXT_COUNT_MESSAGE0"] = "تعداد %1 را در %2 بشمار"; Blockly.Msg["TEXT_COUNT_TOOLTIP"] = "تعداد دفعاتی که یک متن درون یک متن دیگر تکرار شده است را برمی‌گرداند"; Blockly.Msg["TEXT_CREATE_JOIN_ITEM_TOOLTIP"] = "افزودن یک مورد به متن."; Blockly.Msg["TEXT_CREATE_JOIN_TITLE_JOIN"] = "عضویت"; Blockly.Msg["TEXT_CREATE_JOIN_TOOLTIP"] = "اضافه کردن، حذف یا مرتب‌سازی بحش‌ها برای تنظیم مجدد این بلوک متنی."; Blockly.Msg["TEXT_GET_SUBSTRING_END_FROM_END"] = "به حرف # از انتها"; Blockly.Msg["TEXT_GET_SUBSTRING_END_FROM_START"] = "به حرف #"; Blockly.Msg["TEXT_GET_SUBSTRING_END_LAST"] = "به آخرین حرف"; Blockly.Msg["TEXT_GET_SUBSTRING_HELPURL"] = "https://github.com/google/blockly/wiki/Text#extracting-a-region-of-text"; // untranslated Blockly.Msg["TEXT_GET_SUBSTRING_INPUT_IN_TEXT"] = "در متن"; Blockly.Msg["TEXT_GET_SUBSTRING_START_FIRST"] = "گرفتن زیرمتن از اولین حرف"; Blockly.Msg["TEXT_GET_SUBSTRING_START_FROM_END"] = "گرفتن زیرمتن از حرف # به انتها"; Blockly.Msg["TEXT_GET_SUBSTRING_START_FROM_START"] = "گرفتن زیرمتن از حرف #"; Blockly.Msg["TEXT_GET_SUBSTRING_TAIL"] = ""; // untranslated Blockly.Msg["TEXT_GET_SUBSTRING_TOOLTIP"] = "قسمت مشخصی‌شده‌ای از متن را بر می‌گرداند."; Blockly.Msg["TEXT_INDEXOF_HELPURL"] = "https://github.com/google/blockly/wiki/Text#finding-text"; // untranslated Blockly.Msg["TEXT_INDEXOF_OPERATOR_FIRST"] = "اولین رخداد متن را بیاب"; Blockly.Msg["TEXT_INDEXOF_OPERATOR_LAST"] = "آخرین رخداد متن را بیاب"; Blockly.Msg["TEXT_INDEXOF_TITLE"] = "در متن %1 %2 %3"; Blockly.Msg["TEXT_INDEXOF_TOOLTIP"] = "شاخصی از اولین آخرین رخ‌داد متن اول در متن دوم بر می‌گرداند. اگر متن یافت نشد %1 باز می‌گرداند."; Blockly.Msg["TEXT_ISEMPTY_HELPURL"] = "https://github.com/google/blockly/wiki/Text#checking-for-empty-text"; // untranslated Blockly.Msg["TEXT_ISEMPTY_TITLE"] = "%1 خالی است"; Blockly.Msg["TEXT_ISEMPTY_TOOLTIP"] = "اضافه کردن صحیح اگر متن فراهم‌شده خالی است."; Blockly.Msg["TEXT_JOIN_HELPURL"] = "https://github.com/google/blockly/wiki/Text#text-creation"; // untranslated Blockly.Msg["TEXT_JOIN_TITLE_CREATEWITH"] = "ایجاد متن با"; Blockly.Msg["TEXT_JOIN_TOOLTIP"] = "یک تکه‌ای از متن را با چسپاندن همهٔ تعداد از موارد ایجاد می‌کند."; Blockly.Msg["TEXT_LENGTH_HELPURL"] = "https://github.com/google/blockly/wiki/Text#text-modification"; // untranslated Blockly.Msg["TEXT_LENGTH_TITLE"] = "طول %1"; Blockly.Msg["TEXT_LENGTH_TOOLTIP"] = "بازگرداندن عددی از حروف (شامل فاصله‌ها) در متن فراهم‌شده."; Blockly.Msg["TEXT_PRINT_HELPURL"] = "https://github.com/google/blockly/wiki/Text#printing-text"; // untranslated Blockly.Msg["TEXT_PRINT_TITLE"] = "چاپ %1"; Blockly.Msg["TEXT_PRINT_TOOLTIP"] = "چاپ متن، عدد یا هر مقدار دیگر مشخص‌شده."; Blockly.Msg["TEXT_PROMPT_HELPURL"] = "https://github.com/google/blockly/wiki/Text#getting-input-from-the-user"; // untranslated Blockly.Msg["TEXT_PROMPT_TOOLTIP_NUMBER"] = "اعلان برای کاربر با یک عدد."; Blockly.Msg["TEXT_PROMPT_TOOLTIP_TEXT"] = "اعلان برای کاربر برای یک متن."; Blockly.Msg["TEXT_PROMPT_TYPE_NUMBER"] = "اعلان برای عدد با پیام"; Blockly.Msg["TEXT_PROMPT_TYPE_TEXT"] = "اعلان برای متن با پیام"; Blockly.Msg["TEXT_REPLACE_HELPURL"] = "https://github.com/google/blockly/wiki/Text#replacing-substrings"; // untranslated Blockly.Msg["TEXT_REPLACE_MESSAGE0"] = "درون %3، متن %1 را با %2 جایگزین کن"; Blockly.Msg["TEXT_REPLACE_TOOLTIP"] = "جایگزین کردن تمام مواردی که از متنی درون متن دیگر وجود دارد"; Blockly.Msg["TEXT_REVERSE_HELPURL"] = "https://github.com/google/blockly/wiki/Text#reversing-text"; // untranslated Blockly.Msg["TEXT_REVERSE_MESSAGE0"] = "معکوس %1"; Blockly.Msg["TEXT_REVERSE_TOOLTIP"] = "چینش کاراکترها درون متن را برعکس می‌کند"; Blockly.Msg["TEXT_TEXT_HELPURL"] = "https://fa.wikipedia.org/wiki/%D8%B1%D8%B4%D8%AA%D9%87_%28%D8%B9%D9%84%D9%88%D9%85_%D8%B1%D8%A7%DB%8C%D8%A7%D9%86%D9%87%29"; Blockly.Msg["TEXT_TEXT_TOOLTIP"] = "یک حرف، کلمه یا خطی از متن."; Blockly.Msg["TEXT_TRIM_HELPURL"] = "https://github.com/google/blockly/wiki/Text#trimming-removing-spaces"; // untranslated Blockly.Msg["TEXT_TRIM_OPERATOR_BOTH"] = "تراشیدن فاصله‌ها از هر دو طرف"; Blockly.Msg["TEXT_TRIM_OPERATOR_LEFT"] = "تراشیدن فاصله‌ها از طرف چپ"; Blockly.Msg["TEXT_TRIM_OPERATOR_RIGHT"] = "تراشیدن فاصله‌ها از طرف چپ"; Blockly.Msg["TEXT_TRIM_TOOLTIP"] = "کپی از متن با فاصله‌های حذف‌شده از یک یا هر دو پایان باز می‌گرداند."; Blockly.Msg["TODAY"] = "امروز"; Blockly.Msg["UNDO"] = "واگردانی"; Blockly.Msg["UNNAMED_KEY"] = "unnamed"; // untranslated Blockly.Msg["VARIABLES_DEFAULT_NAME"] = "مورد"; Blockly.Msg["VARIABLES_GET_CREATE_SET"] = "درست‌کردن «تنظیم %1»"; Blockly.Msg["VARIABLES_GET_HELPURL"] = "https://github.com/google/blockly/wiki/Variables#get"; // untranslated Blockly.Msg["VARIABLES_GET_TOOLTIP"] = "مقدار این متغیر را بر می‌گرداند."; Blockly.Msg["VARIABLES_SET"] = "مجموعه %1 به %2"; Blockly.Msg["VARIABLES_SET_CREATE_GET"] = "درست‌کردن «گرفتن %1»"; Blockly.Msg["VARIABLES_SET_HELPURL"] = "https://github.com/google/blockly/wiki/Variables#set"; // untranslated Blockly.Msg["VARIABLES_SET_TOOLTIP"] = "متغیر برابر با خروجی را مشخص می‌کند."; Blockly.Msg["VARIABLE_ALREADY_EXISTS"] = "متغیری با نام '%1' هم اکنون وجود دارد"; Blockly.Msg["VARIABLE_ALREADY_EXISTS_FOR_ANOTHER_TYPE"] = "در حال حاضر یک متغیر با نام '%1' برای متغیر دیگری از نوع '%2' وجود دارد."; Blockly.Msg["WORKSPACE_ARIA_LABEL"] = "Blockly Workspace"; // untranslated Blockly.Msg["WORKSPACE_COMMENT_DEFAULT_TEXT"] = "یک چیزی بگو..."; Blockly.Msg["CONTROLS_FOREACH_INPUT_DO"] = Blockly.Msg["CONTROLS_REPEAT_INPUT_DO"]; Blockly.Msg["CONTROLS_FOR_INPUT_DO"] = Blockly.Msg["CONTROLS_REPEAT_INPUT_DO"]; Blockly.Msg["CONTROLS_IF_ELSEIF_TITLE_ELSEIF"] = Blockly.Msg["CONTROLS_IF_MSG_ELSEIF"]; Blockly.Msg["CONTROLS_IF_ELSE_TITLE_ELSE"] = Blockly.Msg["CONTROLS_IF_MSG_ELSE"]; Blockly.Msg["CONTROLS_IF_IF_TITLE_IF"] = Blockly.Msg["CONTROLS_IF_MSG_IF"]; Blockly.Msg["CONTROLS_IF_MSG_THEN"] = Blockly.Msg["CONTROLS_REPEAT_INPUT_DO"]; Blockly.Msg["CONTROLS_WHILEUNTIL_INPUT_DO"] = Blockly.Msg["CONTROLS_REPEAT_INPUT_DO"]; Blockly.Msg["LISTS_CREATE_WITH_ITEM_TITLE"] = Blockly.Msg["VARIABLES_DEFAULT_NAME"]; Blockly.Msg["LISTS_GET_INDEX_HELPURL"] = Blockly.Msg["LISTS_INDEX_OF_HELPURL"]; Blockly.Msg["LISTS_GET_INDEX_INPUT_IN_LIST"] = Blockly.Msg["LISTS_INLIST"]; Blockly.Msg["LISTS_GET_SUBLIST_INPUT_IN_LIST"] = Blockly.Msg["LISTS_INLIST"]; Blockly.Msg["LISTS_INDEX_OF_INPUT_IN_LIST"] = Blockly.Msg["LISTS_INLIST"]; Blockly.Msg["LISTS_SET_INDEX_INPUT_IN_LIST"] = Blockly.Msg["LISTS_INLIST"]; Blockly.Msg["MATH_CHANGE_TITLE_ITEM"] = Blockly.Msg["VARIABLES_DEFAULT_NAME"]; Blockly.Msg["PROCEDURES_DEFRETURN_COMMENT"] = Blockly.Msg["PROCEDURES_DEFNORETURN_COMMENT"]; Blockly.Msg["PROCEDURES_DEFRETURN_DO"] = Blockly.Msg["PROCEDURES_DEFNORETURN_DO"]; Blockly.Msg["PROCEDURES_DEFRETURN_PROCEDURE"] = Blockly.Msg["PROCEDURES_DEFNORETURN_PROCEDURE"]; Blockly.Msg["PROCEDURES_DEFRETURN_TITLE"] = Blockly.Msg["PROCEDURES_DEFNORETURN_TITLE"]; Blockly.Msg["TEXT_APPEND_VARIABLE"] = Blockly.Msg["VARIABLES_DEFAULT_NAME"]; Blockly.Msg["TEXT_CREATE_JOIN_ITEM_TITLE_ITEM"] = Blockly.Msg["VARIABLES_DEFAULT_NAME"]; Blockly.Msg["MATH_HUE"] = "230"; Blockly.Msg["LOOPS_HUE"] = "120"; Blockly.Msg["LISTS_HUE"] = "260"; Blockly.Msg["LOGIC_HUE"] = "210"; Blockly.Msg["VARIABLES_HUE"] = "330"; Blockly.Msg["TEXTS_HUE"] = "160"; Blockly.Msg["PROCEDURES_HUE"] = "290"; Blockly.Msg["COLOUR_HUE"] = "20"; Blockly.Msg["VARIABLES_DYNAMIC_HUE"] = "310"; return Blockly.Msg; }));
var transform = require('./presenters/profile').transform, Hapi = require('hapi'), Joi = require('joi'), merge = require('lodash').merge; module.exports = function (options) { return function (request, reply) { var saveProfile = request.server.methods.user.saveProfile, setSession = request.server.methods.user.setSession(request); var opts = { user: transform(request.auth.credentials, options), namespace: 'user-profile-edit' } if (request.method === 'post' || request.method === 'put') { var editableUserProperties = Joi.object().keys({ fullname: Joi.string().allow(''), homepage: Joi.string().allow(''), github: Joi.string().allow(''), twitter: Joi.string().allow(''), freenode: Joi.string().allow('') }); Joi.validate(request.payload, editableUserProperties, function (err, userChanges) { if (err) { opts.error = err; return reply.view('user/profile-edit', opts).code(400); } merge(opts.user, userChanges); opts.user = transform(opts.user, options); saveProfile(opts.user, function (err, data) { if (err) { request.logger.warn(err); request.logger.warn('unable to save profile; user=' + opts.user.name); return reply.view('errors/internal', opts).code(500); } setSession(opts.user, function (err) { if (err) { // TODO this is an error with our cache. Does the user really need to see it? request.logger.warn('unable to set session; user=' + opts.user.name); return reply.view('errors/internal', opts).code(500); } request.timing.page = 'saveProfile'; request.metrics.metric({ name: 'saveProfile' }); return reply.redirect('/profile'); }); }); }); } if (request.method === 'head' || request.method === 'get' || opts.error) { request.timing.page = 'profile-edit'; opts.title = 'Edit Profile'; return reply.view('user/profile-edit', opts); } } } function applyChanges (user, profileChanges) { for (var i in profileChanges) { user[i] = profileChanges[i]; } return user; }
// Copyright 2013 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Closure user agent detection. * @see http://en.wikipedia.org/wiki/User_agent * For more information on browser brand, platform, or device see the other * sub-namespaces in goog.labs.userAgent (browser, platform, and device). * */ goog.provide('goog.labs.userAgent.engine'); goog.require('goog.array'); goog.require('goog.labs.userAgent.util'); goog.require('goog.string'); /** * @return {boolean} Whether the rendering engine is Presto. */ goog.labs.userAgent.engine.isPresto = function() { return goog.labs.userAgent.util.matchUserAgent('Presto'); }; /** * @return {boolean} Whether the rendering engine is Trident. */ goog.labs.userAgent.engine.isTrident = function() { // IE only started including the Trident token in IE8. return goog.labs.userAgent.util.matchUserAgent('Trident') || goog.labs.userAgent.util.matchUserAgent('MSIE'); }; /** * @return {boolean} Whether the rendering engine is WebKit. */ goog.labs.userAgent.engine.isWebKit = function() { return goog.labs.userAgent.util.matchUserAgent('WebKit'); }; /** * @return {boolean} Whether the rendering engine is Gecko. */ goog.labs.userAgent.engine.isGecko = function() { return goog.labs.userAgent.util.matchUserAgent('Gecko') && !goog.labs.userAgent.engine.isWebKit() && !goog.labs.userAgent.engine.isTrident(); }; /** * @return {string} The rendering engine's version or empty string if version * can't be determined. */ goog.labs.userAgent.engine.getVersion = function() { var userAgentString = goog.labs.userAgent.util.getUserAgent(); if (userAgentString) { var tuples = goog.labs.userAgent.util.extractVersionTuples( userAgentString); var engineTuple = tuples[1]; if (engineTuple) { // In Gecko, the version string is either in the browser info or the // Firefox version. See Gecko user agent string reference: // http://goo.gl/mULqa if (engineTuple[0] == 'Gecko') { return goog.labs.userAgent.engine.getVersionForKey_( tuples, 'Firefox'); } return engineTuple[1]; } // IE has only one version identifier, and the Trident version is // specified in the parenthetical. var browserTuple = tuples[0]; var info; if (browserTuple && (info = browserTuple[2])) { var match = /Trident\/([^\s;]+)/.exec(info); if (match) { return match[1]; } } } return ''; }; /** * @param {string|number} version The version to check. * @return {boolean} Whether the rendering engine version is higher or the same * as the given version. */ goog.labs.userAgent.engine.isVersionOrHigher = function(version) { return goog.string.compareVersions(goog.labs.userAgent.engine.getVersion(), version) >= 0; }; /** * @param {!Array.<!Array.<string>>} tuples Version tuples. * @param {string} key The key to look for. * @return {string} The version string of the given key, if present. * Otherwise, the empty string. * @private */ goog.labs.userAgent.engine.getVersionForKey_ = function(tuples, key) { // TODO(nnaze): Move to util if useful elsewhere. var pair = goog.array.find(tuples, function(pair) { return key == pair[0]; }); return pair && pair[1] || ''; };
declare module "flatbuffers" { declare type Offset = number; declare type Table = { bb: ByteBuffer, bb_pos: number }; declare type EncodingValue = 1 | 2; declare var Encoding: { UTF8_BYTES: 1, UTF16_STRING: 2 }; declare class Long { constructor(low: number, high: number): void; static create(low: number, high: number): Long; toFloat64(): number; equals(other: Long): boolean; } declare class Builder { constructor(opt_initial_size: ?number): void; forceDefaults(forceDefaults: boolean): void; dataBuffer(): ByteBuffer; asUint8Array(): Uint8Array; prep(size: number, additional_bytes: number): void; pad(byte_size: number): void; writeInt8(value: number): void; writeInt16(value: number): void; writeInt32(value: number): void; writeInt64(value: Long): void; writeFloat32(value: number): void; writeFloat64(value: number): void; addInt8(value: number): void; addInt16(value: number): void; addInt32(value: number): void; addInt64(value: Long): void; addFloat32(value: number): void; addFloat64(value: number): void; addFieldInt8(voffset: number, value: number, defaultValue: number): void; addFieldInt16(voffset: number, value: number, defaultValue: number): void; addFieldInt32(voffset: number, value: number, defaultValue: number): void; addFieldInt64(voffset: number, value: Long, defaultValue: Long): void; addFieldFloat32(voffset: number, value: number, defaultValue: number): void; addFieldFloat64(voffset: number, value: number, defaultValue: number): void; addFieldOffset(voffset: number, value: Offset, defaultValue: Offset): void; addFieldStruct(voffset: number, value: Offset, defaultValue: Offset): void; nested(obj: Offset): void; notNested(): void; slot(voffset: number): void; offset(): Offset; static growByteBuffer(bb: ByteBuffer): ByteBuffer; addOffset(offset: Offset): void; startObject(numfields: number): void; endObject(): Offset; finish(root_table: Offset, opt_file_identifier: ?string): void; requiredField(table: Offset, field: number): void; startVector(elem_size: number, num_elems: number, alignment: number): void; endVector(): Offset; createString(s: string | Uint8Array): Offset; createLong(low: number, high: number): Long; } declare class ByteBuffer { constructor(bytes: Uint8Array): void; static allocate(byte_size: number): ByteBuffer; bytes(): Uint8Array; position(): number; setPosition(position: number): void; capacity(): number; readInt8(offset: number): number; readUint8(offset: number): number; readInt16(offset: number): number; readUint16(offset: number): number; readInt32(offset: number): number; readUint32(offset: number): number; readInt64(offset: number): Long; readUint64(offset: number): Long; readFloat32(offset: number): number; readFloat64(offset: number): number; writeInt8(offset: number, value: number): void; writeInt16(offset: number, value: number): void; writeInt32(offset: number, value: number): void; writeInt64(offset: number, value: Long): void; writeFloat32(offset: number, value: number): void; writeFloat64(offset: number, value: number): void; createLong(low: number, high: number): Long; } declare var flatbuffers: { Long: Class<Long>, Builder: Class<Builder>, ByteBuffer: Class<ByteBuffer> }; }
/* Script: Collapsable.js Enables a dom element to, when clicked, hide or show (it toggles) another dom element. Kind of an Accordion for one item. License: http://www.clientcide.com/wiki/cnet-libraries#license */ var Collapsable = new Class({ Extends: Fx.Reveal, initialize: function(clicker, section, options) { this.clicker = document.id(clicker); this.section = document.id(section); this.parent(this.section, options); this.addEvents(); }, addEvents: function(){ this.clicker.addEvent('click', this.toggle.bind(this)); } });
var path = require('path'); var init = function (runtime) { if (runtime) { // setup routes runtime.once(runtime.events.INIT_ROUTES, function () { runtime.routes.push({ route: 'test1', text: 'Test 1', navbar: true, handler: path.join(__dirname, '/dist/components/page1') }); runtime.routes.push({ route: 'test2', text: 'Test 2', navbar: true, handler: path.join(__dirname, '/dist/components/page2') }); }); } }; module.exports = init;
const tabsInstance = ( <Tab.Container id="left-tabs-example" defaultActiveKey="first"> <Row className="clearfix"> <Col sm={4}> <Nav bsStyle="pills" stacked> <NavItem eventKey="first"> Tab 1 </NavItem> <NavItem eventKey="second"> Tab 2 </NavItem> </Nav> </Col> <Col sm={8}> <Tab.Content animation> <Tab.Pane eventKey="first"> Tab 1 content </Tab.Pane> <Tab.Pane eventKey="second"> Tab 2 content </Tab.Pane> </Tab.Content> </Col> </Row> </Tab.Container> ); ReactDOM.render(tabsInstance, mountNode);
var events = require('events'), http = require('http'), https = require('https'), util = require('util'); module.exports = ElasticSearchCall; function ElasticSearchCall(params, options, cb) { var self = this self.host = options.host || 'localhost'; self.port = options.port || 80; self.secure = options.secure || false; self.defaultMethod = options.defaultMethod || 'GET'; self.auth = options.auth || false; self.params = params || {}; self.path = [ options.pathPrefix || '', options.path || ''].join(''); self.timeout = options.timeout || false; self.callback = cb || false; self.agent = options.agent; events.EventEmitter.call(this); } util.inherits(ElasticSearchCall, events.EventEmitter); ElasticSearchCall.prototype.exec = function (cb) { var self = this var reqOptions = { path:this.path + this.params.path, method:this.params.method || this.defaultMethod, host:this.host, port:this.port, agent: this.agent } if (typeof cb == 'function') { self.callback = cb; } var client = null; if (this.secure) { client = https; } else { client = http; } var request = client.request(reqOptions); if (self.timeout) { request.setTimeout(self.timeout, function () { self.emit('error', new Error('timed out after ' + self.timeout + 'ms')); }); } request.on('error', function (error) { self.emit("error", error) }) request.on('response', function (response) { var body = ""; response.on('data', function (chunk) { body += chunk; }); response.on('end', function () { if (typeof self.callback == 'function') { self.callback(undefined, body); } else { self.emit("data", body); self.emit("done", 0) } }); response.on('error', function (error) { if (typeof self.callback == 'function') { self.callback(error); } else { self.emit("error", error) } }) }); if (this.auth) { request.setHeader("Authorization", "Basic " + new Buffer(this.auth.username + ":" + this.auth.password).toString('base64')) } if (this.params.data) { if (typeof this.params.data != 'string') { this.params.data = JSON.stringify(this.params.data); } request.setHeader('Content-Type', 'application/json'); request.setHeader('Content-Length', Buffer.byteLength(this.params.data, 'utf8')); request.end(this.params.data); } else { request.end(''); } } /** * Wrap the default data event * @param callback */ ElasticSearchCall.prototype.data = function (callback) { this.on('data', callback); } /** * wrap the default done event * @param callback */ ElasticSearchCall.prototype.done = function (callback) { this.on('done', callback); } /** * wrap the default error event * @param callback */ ElasticSearchCall.prototype.error = function (callback) { this.on('error', callback); }
"use strict"; var webpack = require('webpack'); var path = require('path'); var loaders = require('./webpack.loaders'); var HtmlWebpackPlugin = require('html-webpack-plugin'); var DashboardPlugin = require('webpack-dashboard/plugin'); var ExtractTextPlugin = require('extract-text-webpack-plugin'); const HOST = process.env.HOST || "127.0.0.1"; const PORT = process.env.PORT || "8888"; loaders.push({ test: /\.scss$/, loaders: ['style-loader', 'css-loader?importLoaders=1', 'sass-loader'], exclude: ['node_modules'] }); module.exports = { entry: [ 'react-hot-loader/patch', './src/index.jsx', // your app's entry point ], devtool: process.env.WEBPACK_DEVTOOL || 'eval-source-map', output: { publicPath: '/', path: path.join(__dirname, 'public'), filename: 'bundle.js' }, resolve: { extensions: ['.js', '.jsx'] }, module: { loaders }, devServer: { contentBase: "./public", // do not print bundle build stats noInfo: true, // enable HMR hot: true, // embed the webpack-dev-server runtime into the bundle inline: true, // serve index.html in place of 404 responses to allow HTML5 history historyApiFallback: true, port: PORT, host: HOST }, plugins: [ new webpack.NoEmitOnErrorsPlugin(), new webpack.HotModuleReplacementPlugin(), new ExtractTextPlugin({ filename: 'style.css', allChunks: true }), new DashboardPlugin(), new HtmlWebpackPlugin({ template: './src/template.html', files: { css: ['style.css'], js: [ "bundle.js"], } }), ] };
'use strict'; describe('Items E2E Tests:', function () { describe('Test Items page', function () { it('Should report missing credentials', function () { browser.get('http://localhost:3001/items'); expect(element.all(by.repeater('item in items')).count()).toEqual(0); }); }); });
/* * jQuery dotdotdot 1.6.17 * * Copyright (c) Fred Heusschen * www.frebsite.nl * * Plugin website: * dotdotdot.frebsite.nl * * Dual licensed under the MIT and GPL licenses. * http://en.wikipedia.org/wiki/MIT_License * http://en.wikipedia.org/wiki/GNU_General_Public_License */ (function(d,x){function y(a,b,m,c,g){var l=!1;a.contents().detach().each(function(){var h=d(this);if("undefined"==typeof this||3==this.nodeType&&0==d.trim(this.data).length)return!0;if(h.is("script, .dotdotdot-keep"))a.append(h);else{if(l)return!0;a.append(h);if(g)a[a.is("table, thead, tbody, tfoot, tr, col, colgroup, object, embed, param, ol, ul, dl, blockquote, select, optgroup, option, textarea, script, style")?"after":"append"](g);if(w(m,c)){if(3==this.nodeType){var k=h[0];if(k){var p=z(k),f= -1!==p.indexOf(" ")?" ":"\u3000",f="letter"==c.wrap?"":f,e=p.split(f),q=-1,n=-1,s=0,r=e.length-1;c.fallbackToLetter&&0==s&&0==r&&(f="",e=p.split(f),r=e.length-1);for(;s<=r&&(0!=s||0!=r);){p=Math.floor((s+r)/2);if(p==n)break;n=p;u(k,e.slice(0,n+1).join(f)+c.ellipsis);w(m,c)?(r=n,c.fallbackToLetter&&0==s&&0==r&&(f="",e=e[0].split(f),n=q=-1,s=0,r=e.length-1)):s=q=n}-1==q||1==e.length&&0==e[0].length?(p=h.parent(),h.detach(),f=g&&g.closest(p).length?g.length:0,p.contents().length>f?k=v(p.contents().eq(-1- f),b):(k=v(p,b,!0),f||p.detach()),k&&(p=A(z(k),c),u(k,p),f&&g&&d(k).parent().append(g))):(p=A(e.slice(0,q+1).join(f),c),u(k,p));l=!0}else l=!1}else l=y(h,b,m,c,g);l||(h.detach(),l=!0)}l||g&&g.detach()}});return l}function w(a,b){return a.innerHeight()>b.maxHeight}function A(a,b){for(;-1<d.inArray(a.slice(-1),b.lastCharacter.remove);)a=a.slice(0,-1);0>d.inArray(a.slice(-1),b.lastCharacter.noEllipsis)&&(a+=b.ellipsis);return a}function B(a){return{width:a.innerWidth(),height:a.innerHeight()}}function u(a, b){a.innerText?a.innerText=b:a.nodeValue?a.nodeValue=b:a.textContent&&(a.textContent=b)}function z(a){return a.innerText?a.innerText:a.nodeValue?a.nodeValue:a.textContent?a.textContent:""}function C(a){do a=a.previousSibling;while(a&&1!==a.nodeType&&3!==a.nodeType);return a}function v(a,b,m){var c=a&&a[0];if(c){if(!m){if(3===c.nodeType)return c;if(d.trim(a.text()))return v(a.contents().last(),b)}for(m=C(c);!m;){a=a.parent();if(a.is(b)||!a.length)return!1;m=C(a[0])}if(m)return v(d(m),b)}return!1}function D(a, b){return a?"string"===typeof a?(a=d(a,b),a.length?a:!1):a.jquery?a:!1:!1}if(!d.fn.dotdotdot){d.fn.dotdotdot=function(a){if(0==this.length)return d.fn.dotdotdot.debug('No element found for "'+this.selector+'".'),this;if(1<this.length)return this.each(function(){d(this).dotdotdot(a)});var b=this;b.data("dotdotdot")&&b.trigger("destroy.dot");b.data("dotdotdot-style",b.attr("style")||"");b.css("word-wrap","break-word");"nowrap"===b.css("white-space")&&b.css("white-space","normal");b.bind_events=function(){b.bind("update.dot", function(a,f){a.preventDefault();a.stopPropagation();var e=c,q;if("number"==typeof c.height)q=c.height;else{q=b.innerHeight();for(var n=["paddingTop","paddingBottom"],h=0,l=n.length;h<l;h++){var t=parseInt(b.css(n[h]),10);isNaN(t)&&(t=0);q-=t}}e.maxHeight=q;c.maxHeight+=c.tolerance;if("undefined"!=typeof f){if("string"==typeof f||f instanceof HTMLElement)f=d("<div />").append(f).contents();f instanceof d&&(m=f)}k=b.wrapInner('<div class="dotdotdot" />').children();k.contents().detach().end().append(m.clone(!0)).find("br").replaceWith(" <br /> ").end().css({height:"auto", width:"auto",border:"none",padding:0,margin:0});e=n=!1;g.afterElement&&(n=g.afterElement.clone(!0),n.show(),g.afterElement.detach());if(w(k,c))if("children"==c.wrap){e=k;q=c;h=e.children();l=!1;e.empty();for(var t=0,v=h.length;t<v;t++){var u=h.eq(t);e.append(u);n&&e.append(n);if(w(e,q)){u.remove();l=!0;break}else n&&n.detach()}e=l}else e=y(k,b,k,c,n);k.replaceWith(k.contents());k=null;d.isFunction(c.callback)&&c.callback.call(b[0],e,m);return g.isTruncated=e}).bind("isTruncated.dot",function(a,c){a.preventDefault(); a.stopPropagation();"function"==typeof c&&c.call(b[0],g.isTruncated);return g.isTruncated}).bind("originalContent.dot",function(a,c){a.preventDefault();a.stopPropagation();"function"==typeof c&&c.call(b[0],m);return m}).bind("destroy.dot",function(a){a.preventDefault();a.stopPropagation();b.unwatch().unbind_events().contents().detach().end().append(m).attr("style",b.data("dotdotdot-style")||"").data("dotdotdot",!1)});return b};b.unbind_events=function(){b.unbind(".dot");return b};b.watch=function(){b.unwatch(); if("window"==c.watch){var a=d(window),f=a.width(),e=a.height();a.bind("resize.dot"+g.dotId,function(){f==a.width()&&e==a.height()&&c.windowResizeFix||(f=a.width(),e=a.height(),h&&clearInterval(h),h=setTimeout(function(){b.trigger("update.dot")},100))})}else l=B(b),h=setInterval(function(){if(b.is(":visible")){var a=B(b);if(l.width!=a.width||l.height!=a.height)b.trigger("update.dot"),l=a}},500);return b};b.unwatch=function(){d(window).unbind("resize.dot"+g.dotId);h&&clearInterval(h);return b};var m= b.contents(),c=d.extend(!0,{},d.fn.dotdotdot.defaults,a),g={},l={},h=null,k=null;c.lastCharacter.remove instanceof Array||(c.lastCharacter.remove=d.fn.dotdotdot.defaultArrays.lastCharacter.remove);c.lastCharacter.noEllipsis instanceof Array||(c.lastCharacter.noEllipsis=d.fn.dotdotdot.defaultArrays.lastCharacter.noEllipsis);g.afterElement=D(c.after,b);g.isTruncated=!1;g.dotId=E++;b.data("dotdotdot",!0).bind_events().trigger("update.dot");c.watch&&b.watch();return b};d.fn.dotdotdot.defaults={ellipsis:"... ", wrap:"word",fallbackToLetter:!0,lastCharacter:{},tolerance:0,callback:null,after:null,height:null,watch:!1,windowResizeFix:!0};d.fn.dotdotdot.defaultArrays={lastCharacter:{remove:" \u3000,;.!?".split(""),noEllipsis:[]}};d.fn.dotdotdot.debug=function(a){};var E=1,F=d.fn.html;d.fn.html=function(a){return a!=x&&!d.isFunction(a)&&this.data("dotdotdot")?this.trigger("update.dot",[a]):F.apply(this,arguments)};var G=d.fn.text;d.fn.text=function(a,b){return a!=x&&!d.isFunction(a)&&this.data("dotdotdot")&& !0!==b?(a=d("<div />").text(a).html(),this.trigger("update.dot",[a])):G.apply(this,null!=b?[a]:arguments)}}})($grv);
(function(e) { var t = document.body.clientWidth; e(document).ready(function() { e("nav").before('<a class="toggleMenu active" href="">Menu<span class="touch-btn">&#9660;</span></a>'); e("nav ul li a").each(function() { if (e(this).next().length > 0) { e(this).addClass("parent"); e(this).append('<span class="touch-btn">&#9660;</span>') } }); e(".toggleMenu").click(function(t) { t.preventDefault(); e(this).toggleClass("active"); e("nav ul").toggleClass("active") }); n() }); e(window).bind("resize orientationchange", function() { t = document.body.clientWidth; n() }); var n = function() { if (t < 768) { e(".toggleMenu").css("display", "block"); if (!e(".toggleMenu").hasClass("active")) { e("nav ul:first-child").addClass("active") } else { e("nav ul:first-child").removeClass("active") } e("nav ul li").unbind("mouseenter mouseleave"); e(".touch-btn").unbind("click").bind("click", function(t) { t.preventDefault(); e(this).closest("li").toggleClass("active") }) } else if (t >= 768) { e(".toggleMenu").css("display", "none") } } })(jQuery)
/** * Magento * * NOTICE OF LICENSE * * This source file is subject to the Academic Free License (AFL 3.0) * that is bundled with this package in the file LICENSE_AFL.txt. * It is also available through the world-wide-web at this URL: * http://opensource.org/licenses/afl-3.0.php * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to license@magento.com so we can send you a copy immediately. * * DISCLAIMER * * Do not edit or add to this file if you wish to upgrade Magento to newer * versions in the future. If you wish to customize Magento for your * needs please refer to http://www.magento.com for more information. * * @category Mage * @package Mage_Adminhtml * @copyright Copyright (c) 2006-2016 X.commerce, Inc. and affiliates (http://www.magento.com) * @license http://opensource.org/licenses/afl-3.0.php Academic Free License (AFL 3.0) */ var VarienRulesForm = new Class.create(); VarienRulesForm.prototype = { initialize : function(parent, newChildUrl){ this.parent = $(parent); this.newChildUrl = newChildUrl; this.shownElement = null; this.updateElement = null; this.chooserSelectedItems = $H({}); this.readOnly = false; var elems = this.parent.getElementsByClassName('rule-param'); for (var i=0; i<elems.length; i++) { this.initParam(elems[i]); } }, setReadonly: function (readonly){ this.readOnly = readonly; var elems = this.parent.getElementsByClassName('rule-param-remove'); for (var i=0; i<elems.length; i++) { var element = elems[i]; if (this.readOnly) { element.hide(); } else { element.show(); } } var elems = this.parent.getElementsByClassName('rule-param-new-child'); for (var i=0; i<elems.length; i++) { var element = elems[i]; if (this.readOnly) { element.hide(); } else { element.show(); } } var elems = this.parent.getElementsByClassName('rule-param'); for (var i=0; i<elems.length; i++) { var container = elems[i]; var label = Element.down(container, '.label'); if (label) { if (this.readOnly) { label.addClassName('label-disabled'); } else { label.removeClassName('label-disabled'); } } } }, initParam: function (container) { container.rulesObject = this; var label = Element.down(container, '.label'); if (label) { Event.observe(label, 'click', this.showParamInputField.bind(this, container)); } var elem = Element.down(container, '.element'); if (elem) { var trig = elem.down('.rule-chooser-trigger'); if (trig) { Event.observe(trig, 'click', this.toggleChooser.bind(this, container)); } var apply = elem.down('.rule-param-apply'); if (apply) { Event.observe(apply, 'click', this.hideParamInputField.bind(this, container)); } else { elem = elem.down('.element-value-changer'); elem.container = container; if (!elem.multiple) { Event.observe(elem, 'change', this.hideParamInputField.bind(this, container)); } Event.observe(elem, 'blur', this.hideParamInputField.bind(this, container)); } } var remove = Element.down(container, '.rule-param-remove'); if (remove) { Event.observe(remove, 'click', this.removeRuleEntry.bind(this, container)); } }, showChooserElement: function (chooser) { this.chooserSelectedItems = $H({}); if (chooser.hasClassName('no-split')) { this.chooserSelectedItems.set(this.updateElement.value, 1); } else { var values = this.updateElement.value.split(','), s = ''; for (i=0; i<values.length; i++) { s = values[i].strip(); if (s!='') { this.chooserSelectedItems.set(s,1); } } } new Ajax.Request(chooser.getAttribute('url'), { evalScripts: true, parameters: {'form_key': FORM_KEY, 'selected[]':this.chooserSelectedItems.keys() }, onSuccess: function(transport) { if (this._processSuccess(transport)) { $(chooser).update(transport.responseText); this.showChooserLoaded(chooser, transport); } }.bind(this), onFailure: this._processFailure.bind(this) }); }, showChooserLoaded: function(chooser, transport) { chooser.style.display = 'block'; }, showChooser: function (container, event) { var chooser = container.up('li'); if (!chooser) { return; } chooser = chooser.down('.rule-chooser'); if (!chooser) { return; } this.showChooserElement(chooser); }, hideChooser: function (container, event) { var chooser = container.up('li'); if (!chooser) { return; } chooser = chooser.down('.rule-chooser'); if (!chooser) { return; } chooser.style.display = 'none'; }, toggleChooser: function (container, event) { if (this.readOnly) { return false; } var chooser = container.up('li').down('.rule-chooser'); if (!chooser) { return; } if (chooser.style.display=='block') { chooser.style.display = 'none'; this.cleanChooser(container, event); } else { this.showChooserElement(chooser); } }, cleanChooser: function (container, event) { var chooser = container.up('li').down('.rule-chooser'); if (!chooser) { return; } chooser.innerHTML = ''; }, showParamInputField: function (container, event) { if (this.readOnly) { return false; } if (this.shownElement) { this.hideParamInputField(this.shownElement, event); } Element.addClassName(container, 'rule-param-edit'); var elemContainer = Element.down(container, '.element'); var elem = Element.down(elemContainer, 'input.input-text'); if (elem) { elem.focus(); if (elem && elem.id && elem.id.match(/__value$/)) { this.updateElement = elem; //this.showChooser(container, event); } } var elem = Element.down(elemContainer, '.element-value-changer'); if (elem) { elem.focus(); // trying to emulate enter to open dropdown // if (document.createEventObject) { // var event = document.createEventObject(); // event.altKey = true; // event.keyCode = 40; // elem.fireEvent("onkeydown", evt); // } else { // var event = document.createEvent("Events"); // event.altKey = true; // event.keyCode = 40; // elem.dispatchEvent(event); // } } this.shownElement = container; }, hideParamInputField: function (container, event) { Element.removeClassName(container, 'rule-param-edit'); var label = Element.down(container, '.label'), elem; if (!container.hasClassName('rule-param-new-child')) { elem = Element.down(container, '.element-value-changer'); if (elem && elem.options) { var selectedOptions = []; for (i=0; i<elem.options.length; i++) { if (elem.options[i].selected) { selectedOptions.push(elem.options[i].text); } } var str = selectedOptions.join(', '); label.innerHTML = str!='' ? str : '...'; // if (elem && elem.selectedIndex>=0) { // var str = elem.options[elem.selectedIndex].text; // label.innerHTML = str!='' ? str : '...'; // } } elem = Element.down(container, 'input.input-text'); if (elem) { var str = elem.value.replace(/(^\s+|\s+$)/g, ''); elem.value = str; if (str=='') { str = '...'; } else if (str.length>30) { str = str.substr(0, 30)+'...'; } label.innerHTML = str.escapeHTML(); } } else { elem = Element.down(container, '.element-value-changer'); if (elem.value) { this.addRuleNewChild(elem); } elem.value = ''; } if (elem && elem.id && elem.id.match(/__value$/)) { this.hideChooser(container, event); this.updateElement = null; } this.shownElement = null; }, addRuleNewChild: function (elem) { var parent_id = elem.id.replace(/^.*__(.*)__.*$/, '$1'); var children_ul = $(elem.id.replace(/__/g, ':').replace(/[^:]*$/, 'children').replace(/:/g, '__')); var max_id = 0, i; var children_inputs = Selector.findChildElements(children_ul, $A(['input.hidden'])); if (children_inputs.length) { children_inputs.each(function(el){ if (el.id.match(/__type$/)) { i = 1 * el.id.replace(/^.*__.*?([0-9]+)__.*$/, '$1'); max_id = i > max_id ? i : max_id; } }); } var new_id = parent_id + '--' + (max_id + 1); var new_type = elem.value; var new_elem = document.createElement('LI'); new_elem.className = 'rule-param-wait'; new_elem.innerHTML = Translator.translate('Please wait, loading...'); children_ul.insertBefore(new_elem, $(elem).up('li')); new Ajax.Request(this.newChildUrl, { evalScripts: true, parameters: {form_key: FORM_KEY, type:new_type.replace('/','-'), id:new_id }, onComplete: this.onAddNewChildComplete.bind(this, new_elem), onSuccess: function(transport) { if(this._processSuccess(transport)) { $(new_elem).update(transport.responseText); } }.bind(this), onFailure: this._processFailure.bind(this) }); }, _processSuccess : function(transport) { if (transport.responseText.isJSON()) { var response = transport.responseText.evalJSON() if (response.error) { alert(response.message); } if(response.ajaxExpired && response.ajaxRedirect) { setLocation(response.ajaxRedirect); } return false; } return true; }, _processFailure : function(transport) { location.href = BASE_URL; }, onAddNewChildComplete: function (new_elem) { if (this.readOnly) { return false; } $(new_elem).removeClassName('rule-param-wait'); var elems = new_elem.getElementsByClassName('rule-param'); for (var i=0; i<elems.length; i++) { this.initParam(elems[i]); } }, removeRuleEntry: function (container, event) { var li = Element.up(container, 'li'); li.parentNode.removeChild(li); }, chooserGridInit: function (grid) { //grid.reloadParams = {'selected[]':this.chooserSelectedItems.keys()}; }, chooserGridRowInit: function (grid, row) { if (!grid.reloadParams) { grid.reloadParams = {'selected[]':this.chooserSelectedItems.keys()}; } }, chooserGridRowClick: function (grid, event) { var trElement = Event.findElement(event, 'tr'); var isInput = Event.element(event).tagName == 'INPUT'; if (trElement) { var checkbox = Element.select(trElement, 'input'); if (checkbox[0]) { var checked = isInput ? checkbox[0].checked : !checkbox[0].checked; grid.setCheckboxChecked(checkbox[0], checked); } } }, chooserGridCheckboxCheck: function (grid, element, checked) { if (checked) { if (!element.up('th')) { this.chooserSelectedItems.set(element.value,1); } } else { this.chooserSelectedItems.unset(element.value); } grid.reloadParams = {'selected[]':this.chooserSelectedItems.keys()}; this.updateElement.value = this.chooserSelectedItems.keys().join(', '); } }
(function() { 'use strict'; angular.module('app.common').service('commonModal', commonModal); commonModal.$inject = ['$modal']; function commonModal($modal) { var modalDefaults = { backdrop: true, keyboard: true, modalFade: true, templateUrl: 'app/modules/common/modal/modal.html' }; var modalOptions = { closeButtonText: 'Close', actionButtonText: 'OK', headerText: 'Proceed?', bodyText: 'Perform this action?' }; this.show = function(customModalDefaults, customModalOptions) { var defaults = {}; var options = {}; angular.extend(defaults, modalDefaults, customModalDefaults); angular.extend(options, modalOptions, customModalOptions); if (!defaults.controller) { defaults.controller = defaultModalController(defaults, options); } return $modal.open(defaults).result; }; } function defaultModalController(defaults, options) { function controller($scope, $modalInstance) { $scope.modalOptions = options; $scope.modalOptions.ok = function(result) { $modalInstance.close(result); }; $scope.modalOptions.close = $scope.modalOptions.close || function(result) { $modalInstance.dismiss('cancel'); }; }; controller.$inject = ['$scope', '$modalInstance']; return controller; } })();
import Component from 'react-pure-render/component'; import React, {PropTypes} from 'react'; export default function fetch(...actions) { return Wrapped => class Fetch extends Component { static contextTypes = { store: PropTypes.object // Redux store. }; // Passed via react-router or can be passed manually in React Native. static propTypes = { location: PropTypes.object, params: PropTypes.object }; // For server side fetching. Check frontend/render.js static fetchActions = actions; // For client side fetching. componentDidMount() { const {store: {dispatch}} = this.context; const {location, params} = this.props; actions.forEach(action => dispatch(action({location, params}))); } render() { return <Wrapped {...this.props} />; } }; }
/* * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. * Changes may cause incorrect behavior and will be lost if the code is * regenerated. */ 'use strict'; var models = require('./index'); var util = require('util'); /** * @class * Initializes a new instance of the VirtualMachineExtensionImage class. * @constructor * Describes a Virtual Machine Extension Image. * @member {string} operatingSystem the operating system this extension * supports. * * @member {string} computeRole the type of role (IaaS or PaaS) this extension * supports. * * @member {string} handlerSchema the schema defined by publisher, where * extension consumers should provide settings in a matching schema. * * @member {boolean} [vmScaleSetEnabled] whether the extension can be used on * xRP VMScaleSets.By default existing extensions are usable on scalesets, * but there might be cases where a publisher wants to explicitly indicate * the extension is only enabled for CRP VMs but not VMSS. * * @member {boolean} [supportsMultipleExtensions] whether the handler can * support multiple extensions. * */ function VirtualMachineExtensionImage() { VirtualMachineExtensionImage['super_'].call(this); } util.inherits(VirtualMachineExtensionImage, models['Resource']); /** * Defines the metadata of VirtualMachineExtensionImage * * @returns {object} metadata of VirtualMachineExtensionImage * */ VirtualMachineExtensionImage.prototype.mapper = function () { return { required: false, serializedName: 'VirtualMachineExtensionImage', type: { name: 'Composite', className: 'VirtualMachineExtensionImage', modelProperties: { id: { required: false, readOnly: true, serializedName: 'id', type: { name: 'String' } }, name: { required: false, readOnly: true, serializedName: 'name', type: { name: 'String' } }, type: { required: false, readOnly: true, serializedName: 'type', type: { name: 'String' } }, location: { required: true, serializedName: 'location', type: { name: 'String' } }, tags: { required: false, serializedName: 'tags', type: { name: 'Dictionary', value: { required: false, serializedName: 'StringElementType', type: { name: 'String' } } } }, operatingSystem: { required: true, serializedName: 'properties.operatingSystem', type: { name: 'String' } }, computeRole: { required: true, serializedName: 'properties.computeRole', type: { name: 'String' } }, handlerSchema: { required: true, serializedName: 'properties.handlerSchema', type: { name: 'String' } }, vmScaleSetEnabled: { required: false, serializedName: 'properties.vmScaleSetEnabled', type: { name: 'Boolean' } }, supportsMultipleExtensions: { required: false, serializedName: 'properties.supportsMultipleExtensions', type: { name: 'Boolean' } } } } }; }; module.exports = VirtualMachineExtensionImage;
"use strict"; define(['src/NodeWatcher', 'src/debug', 'jquery.qunit'], function (CSLEDIT_NodeWatcher, debug) { module("CSLEDIT_NodeWatcher", { setup : function () { debug.log("typeof NodeWatcher = " + typeof(CSLEDIT_NodeWatcher)); CSLEDIT_NodeWatcher.FakeData = function () { this.nodes = { "style": {name: "style", cslId: 0}, "style/info": {name: "info", cslId: 1} }; }; CSLEDIT_NodeWatcher.FakeData.prototype.getNodesFromPath = function (nodePath) { var result = []; if (nodePath in this.nodes) { result.push(this.nodes[nodePath]); } return result; }; debug.log("created FakeData"); } }); test("create & amend node", function () { var nodeView, currentNode, viewUpdated = false, description, fakeData = new CSLEDIT_NodeWatcher.FakeData(); description = "Create NodeWatcher"; nodeView = new CSLEDIT_NodeWatcher("style/info", fakeData, function (nodeData) { currentNode = nodeData; viewUpdated = true; }); equal(currentNode.name, "info", description); equal(currentNode.cslId, 1, description); description = "Amend node"; nodeView.amendNode(1, {name: "newName"}); equal(currentNode.name, "newName", description); viewUpdated = false; nodeView.amendNode(0, {name: "test"}); equal(viewUpdated, false, description); }); test("add/delete nodes", function () { var nodeView, currentNode, viewUpdated = false, description, fakeData = new CSLEDIT_NodeWatcher.FakeData(); description = "Create NodeWatcher"; nodeView = new CSLEDIT_NodeWatcher("style/info", fakeData, // fake update function function (nodeData) { currentNode = nodeData; viewUpdated = true; }); equal(currentNode.name, "info", description); equal(currentNode.cslId, 1, description); description = "Add node before"; nodeView.addNode(0, 0, { name: "new-node-before", cslId: 1, children : [ {name: "new-node-before-within", cslId: 2} ] }, 2); equal(currentNode.cslId, 3, description); description = "Add node within"; viewUpdated = false; nodeView.addNode(3, 0, {name: "new-node-within", cslId: 4}, 1); equal(viewUpdated, false, description); description = "Add node after"; viewUpdated = false; nodeView.addNode(0, 2, {name: "new-node-after", cslId: 5}, 1); equal(viewUpdated, false, description); // use deleteNode to undo the above addNode commands description = "Delete node after"; viewUpdated = false; nodeView.deleteNode(4, 1); equal(viewUpdated, false, description); description = "Delete node within"; viewUpdated = false; nodeView.deleteNode(4, 1); equal(viewUpdated, false, description); description = "Delete node before"; nodeView.deleteNode(1, 2); equal(currentNode.cslId, 1, description); }); test("Delete and recreate node", function () { var nodeView, currentNode, viewUpdated = false, description, fakeData = new CSLEDIT_NodeWatcher.FakeData(); description = "Create NodeWatcher"; nodeView = new CSLEDIT_NodeWatcher("style/info", fakeData, // fake update function function (nodeData) { currentNode = nodeData; viewUpdated = true; }); equal(currentNode.name, "info", description); equal(currentNode.cslId, 1, description); description = "Delete node"; delete fakeData.nodes["style/info"]; nodeView.deleteNode(1, 1); equal(currentNode, null); description = "Recreate node"; fakeData.nodes["style/info"] = {name: "info", cslId: 1}; nodeView.addNode(0, 0, {name: "info", cslId: 1}); equal(currentNode.name, "info"); equal(currentNode.cslId, 1); }); test("Create and delete node", function () { var nodeView, currentNode, viewUpdated = false, description, fakeData = new CSLEDIT_NodeWatcher.FakeData(); description = "Create NodeWatcher for non-existant style/citation node"; nodeView = new CSLEDIT_NodeWatcher("style/citation", fakeData, // fake update function function (nodeData) { currentNode = nodeData; viewUpdated = true; }); equal(currentNode, null, description); description = "Recreate node"; fakeData.nodes["style/citation"] = {name: "citation", cslId: 2}; nodeView.addNode(0, 1, {name: "citation", cslId: 2}); equal(currentNode.name, "citation"); equal(currentNode.cslId, 2); }); });
/*! jQuery UI - v1.10.3 - 2013-07-29 * http://jqueryui.com * Includes: jquery.ui.core.js, jquery.ui.widget.js, jquery.ui.mouse.js, jquery.ui.position.js, jquery.ui.draggable.js, jquery.ui.droppable.js, jquery.ui.resizable.js, jquery.ui.selectable.js, jquery.ui.sortable.js, jquery.ui.accordion.js, jquery.ui.autocomplete.js, jquery.ui.button.js, jquery.ui.datepicker.js, jquery.ui.dialog.js, jquery.ui.menu.js, jquery.ui.progressbar.js, jquery.ui.slider.js, jquery.ui.spinner.js, jquery.ui.tabs.js, jquery.ui.tooltip.js, jquery.ui.effect.js, jquery.ui.effect-blind.js, jquery.ui.effect-bounce.js, jquery.ui.effect-clip.js, jquery.ui.effect-drop.js, jquery.ui.effect-explode.js, jquery.ui.effect-fade.js, jquery.ui.effect-fold.js, jquery.ui.effect-highlight.js, jquery.ui.effect-pulsate.js, jquery.ui.effect-scale.js, jquery.ui.effect-shake.js, jquery.ui.effect-slide.js, jquery.ui.effect-transfer.js * Copyright 2013 jQuery Foundation and other contributors Licensed MIT */ (function( $, undefined ) { var uuid = 0, runiqueId = /^ui-id-\d+$/; // $.ui might exist from components with no dependencies, e.g., $.ui.position $.ui = $.ui || {}; $.extend( $.ui, { version: "1.10.3", keyCode: { BACKSPACE: 8, COMMA: 188, DELETE: 46, DOWN: 40, END: 35, ENTER: 13, ESCAPE: 27, HOME: 36, LEFT: 37, NUMPAD_ADD: 107, NUMPAD_DECIMAL: 110, NUMPAD_DIVIDE: 111, NUMPAD_ENTER: 108, NUMPAD_MULTIPLY: 106, NUMPAD_SUBTRACT: 109, PAGE_DOWN: 34, PAGE_UP: 33, PERIOD: 190, RIGHT: 39, SPACE: 32, TAB: 9, UP: 38 } }); // plugins $.fn.extend({ focus: (function( orig ) { return function( delay, fn ) { return typeof delay === "number" ? this.each(function() { var elem = this; setTimeout(function() { $( elem ).focus(); if ( fn ) { fn.call( elem ); } }, delay ); }) : orig.apply( this, arguments ); }; })( $.fn.focus ), scrollParent: function() { var scrollParent; if (($.ui.ie && (/(static|relative)/).test(this.css("position"))) || (/absolute/).test(this.css("position"))) { scrollParent = this.parents().filter(function() { return (/(relative|absolute|fixed)/).test($.css(this,"position")) && (/(auto|scroll)/).test($.css(this,"overflow")+$.css(this,"overflow-y")+$.css(this,"overflow-x")); }).eq(0); } else { scrollParent = this.parents().filter(function() { return (/(auto|scroll)/).test($.css(this,"overflow")+$.css(this,"overflow-y")+$.css(this,"overflow-x")); }).eq(0); } return (/fixed/).test(this.css("position")) || !scrollParent.length ? $(document) : scrollParent; }, zIndex: function( zIndex ) { if ( zIndex !== undefined ) { return this.css( "zIndex", zIndex ); } if ( this.length ) { var elem = $( this[ 0 ] ), position, value; while ( elem.length && elem[ 0 ] !== document ) { // Ignore z-index if position is set to a value where z-index is ignored by the browser // This makes behavior of this function consistent across browsers // WebKit always returns auto if the element is positioned position = elem.css( "position" ); if ( position === "absolute" || position === "relative" || position === "fixed" ) { // IE returns 0 when zIndex is not specified // other browsers return a string // we ignore the case of nested elements with an explicit value of 0 // <div style="z-index: -10;"><div style="z-index: 0;"></div></div> value = parseInt( elem.css( "zIndex" ), 10 ); if ( !isNaN( value ) && value !== 0 ) { return value; } } elem = elem.parent(); } } return 0; }, uniqueId: function() { return this.each(function() { if ( !this.id ) { this.id = "ui-id-" + (++uuid); } }); }, removeUniqueId: function() { return this.each(function() { if ( runiqueId.test( this.id ) ) { $( this ).removeAttr( "id" ); } }); } }); // selectors function focusable( element, isTabIndexNotNaN ) { var map, mapName, img, nodeName = element.nodeName.toLowerCase(); if ( "area" === nodeName ) { map = element.parentNode; mapName = map.name; if ( !element.href || !mapName || map.nodeName.toLowerCase() !== "map" ) { return false; } img = $( "img[usemap=#" + mapName + "]" )[0]; return !!img && visible( img ); } return ( /input|select|textarea|button|object/.test( nodeName ) ? !element.disabled : "a" === nodeName ? element.href || isTabIndexNotNaN : isTabIndexNotNaN) && // the element and all of its ancestors must be visible visible( element ); } function visible( element ) { return $.expr.filters.visible( element ) && !$( element ).parents().addBack().filter(function() { return $.css( this, "visibility" ) === "hidden"; }).length; } $.extend( $.expr[ ":" ], { data: $.expr.createPseudo ? $.expr.createPseudo(function( dataName ) { return function( elem ) { return !!$.data( elem, dataName ); }; }) : // support: jQuery <1.8 function( elem, i, match ) { return !!$.data( elem, match[ 3 ] ); }, focusable: function( element ) { return focusable( element, !isNaN( $.attr( element, "tabindex" ) ) ); }, tabbable: function( element ) { var tabIndex = $.attr( element, "tabindex" ), isTabIndexNaN = isNaN( tabIndex ); return ( isTabIndexNaN || tabIndex >= 0 ) && focusable( element, !isTabIndexNaN ); } }); // support: jQuery <1.8 if ( !$( "<a>" ).outerWidth( 1 ).jquery ) { $.each( [ "Width", "Height" ], function( i, name ) { var side = name === "Width" ? [ "Left", "Right" ] : [ "Top", "Bottom" ], type = name.toLowerCase(), orig = { innerWidth: $.fn.innerWidth, innerHeight: $.fn.innerHeight, outerWidth: $.fn.outerWidth, outerHeight: $.fn.outerHeight }; function reduce( elem, size, border, margin ) { $.each( side, function() { size -= parseFloat( $.css( elem, "padding" + this ) ) || 0; if ( border ) { size -= parseFloat( $.css( elem, "border" + this + "Width" ) ) || 0; } if ( margin ) { size -= parseFloat( $.css( elem, "margin" + this ) ) || 0; } }); return size; } $.fn[ "inner" + name ] = function( size ) { if ( size === undefined ) { return orig[ "inner" + name ].call( this ); } return this.each(function() { $( this ).css( type, reduce( this, size ) + "px" ); }); }; $.fn[ "outer" + name] = function( size, margin ) { if ( typeof size !== "number" ) { return orig[ "outer" + name ].call( this, size ); } return this.each(function() { $( this).css( type, reduce( this, size, true, margin ) + "px" ); }); }; }); } // support: jQuery <1.8 if ( !$.fn.addBack ) { $.fn.addBack = function( selector ) { return this.add( selector == null ? this.prevObject : this.prevObject.filter( selector ) ); }; } // support: jQuery 1.6.1, 1.6.2 (http://bugs.jquery.com/ticket/9413) if ( $( "<a>" ).data( "a-b", "a" ).removeData( "a-b" ).data( "a-b" ) ) { $.fn.removeData = (function( removeData ) { return function( key ) { if ( arguments.length ) { return removeData.call( this, $.camelCase( key ) ); } else { return removeData.call( this ); } }; })( $.fn.removeData ); } // deprecated $.ui.ie = !!/msie [\w.]+/.exec( navigator.userAgent.toLowerCase() ); $.support.selectstart = "onselectstart" in document.createElement( "div" ); $.fn.extend({ disableSelection: function() { return this.bind( ( $.support.selectstart ? "selectstart" : "mousedown" ) + ".ui-disableSelection", function( event ) { event.preventDefault(); }); }, enableSelection: function() { return this.unbind( ".ui-disableSelection" ); } }); $.extend( $.ui, { // $.ui.plugin is deprecated. Use $.widget() extensions instead. plugin: { add: function( module, option, set ) { var i, proto = $.ui[ module ].prototype; for ( i in set ) { proto.plugins[ i ] = proto.plugins[ i ] || []; proto.plugins[ i ].push( [ option, set[ i ] ] ); } }, call: function( instance, name, args ) { var i, set = instance.plugins[ name ]; if ( !set || !instance.element[ 0 ].parentNode || instance.element[ 0 ].parentNode.nodeType === 11 ) { return; } for ( i = 0; i < set.length; i++ ) { if ( instance.options[ set[ i ][ 0 ] ] ) { set[ i ][ 1 ].apply( instance.element, args ); } } } }, // only used by resizable hasScroll: function( el, a ) { //If overflow is hidden, the element might have extra content, but the user wants to hide it if ( $( el ).css( "overflow" ) === "hidden") { return false; } var scroll = ( a && a === "left" ) ? "scrollLeft" : "scrollTop", has = false; if ( el[ scroll ] > 0 ) { return true; } // TODO: determine which cases actually cause this to happen // if the element doesn't have the scroll set, see if it's possible to // set the scroll el[ scroll ] = 1; has = ( el[ scroll ] > 0 ); el[ scroll ] = 0; return has; } }); })( jQuery ); (function( $, undefined ) { var uuid = 0, slice = Array.prototype.slice, _cleanData = $.cleanData; $.cleanData = function( elems ) { for ( var i = 0, elem; (elem = elems[i]) != null; i++ ) { try { $( elem ).triggerHandler( "remove" ); // http://bugs.jquery.com/ticket/8235 } catch( e ) {} } _cleanData( elems ); }; $.widget = function( name, base, prototype ) { var fullName, existingConstructor, constructor, basePrototype, // proxiedPrototype allows the provided prototype to remain unmodified // so that it can be used as a mixin for multiple widgets (#8876) proxiedPrototype = {}, namespace = name.split( "." )[ 0 ]; name = name.split( "." )[ 1 ]; fullName = namespace + "-" + name; if ( !prototype ) { prototype = base; base = $.Widget; } // create selector for plugin $.expr[ ":" ][ fullName.toLowerCase() ] = function( elem ) { return !!$.data( elem, fullName ); }; $[ namespace ] = $[ namespace ] || {}; existingConstructor = $[ namespace ][ name ]; constructor = $[ namespace ][ name ] = function( options, element ) { // allow instantiation without "new" keyword if ( !this._createWidget ) { return new constructor( options, element ); } // allow instantiation without initializing for simple inheritance // must use "new" keyword (the code above always passes args) if ( arguments.length ) { this._createWidget( options, element ); } }; // extend with the existing constructor to carry over any static properties $.extend( constructor, existingConstructor, { version: prototype.version, // copy the object used to create the prototype in case we need to // redefine the widget later _proto: $.extend( {}, prototype ), // track widgets that inherit from this widget in case this widget is // redefined after a widget inherits from it _childConstructors: [] }); basePrototype = new base(); // we need to make the options hash a property directly on the new instance // otherwise we'll modify the options hash on the prototype that we're // inheriting from basePrototype.options = $.widget.extend( {}, basePrototype.options ); $.each( prototype, function( prop, value ) { if ( !$.isFunction( value ) ) { proxiedPrototype[ prop ] = value; return; } proxiedPrototype[ prop ] = (function() { var _super = function() { return base.prototype[ prop ].apply( this, arguments ); }, _superApply = function( args ) { return base.prototype[ prop ].apply( this, args ); }; return function() { var __super = this._super, __superApply = this._superApply, returnValue; this._super = _super; this._superApply = _superApply; returnValue = value.apply( this, arguments ); this._super = __super; this._superApply = __superApply; return returnValue; }; })(); }); constructor.prototype = $.widget.extend( basePrototype, { // TODO: remove support for widgetEventPrefix // always use the name + a colon as the prefix, e.g., draggable:start // don't prefix for widgets that aren't DOM-based widgetEventPrefix: existingConstructor ? basePrototype.widgetEventPrefix : name }, proxiedPrototype, { constructor: constructor, namespace: namespace, widgetName: name, widgetFullName: fullName }); // If this widget is being redefined then we need to find all widgets that // are inheriting from it and redefine all of them so that they inherit from // the new version of this widget. We're essentially trying to replace one // level in the prototype chain. if ( existingConstructor ) { $.each( existingConstructor._childConstructors, function( i, child ) { var childPrototype = child.prototype; // redefine the child widget using the same prototype that was // originally used, but inherit from the new version of the base $.widget( childPrototype.namespace + "." + childPrototype.widgetName, constructor, child._proto ); }); // remove the list of existing child constructors from the old constructor // so the old child constructors can be garbage collected delete existingConstructor._childConstructors; } else { base._childConstructors.push( constructor ); } $.widget.bridge( name, constructor ); }; $.widget.extend = function( target ) { var input = slice.call( arguments, 1 ), inputIndex = 0, inputLength = input.length, key, value; for ( ; inputIndex < inputLength; inputIndex++ ) { for ( key in input[ inputIndex ] ) { value = input[ inputIndex ][ key ]; if ( input[ inputIndex ].hasOwnProperty( key ) && value !== undefined ) { // Clone objects if ( $.isPlainObject( value ) ) { target[ key ] = $.isPlainObject( target[ key ] ) ? $.widget.extend( {}, target[ key ], value ) : // Don't extend strings, arrays, etc. with objects $.widget.extend( {}, value ); // Copy everything else by reference } else { target[ key ] = value; } } } } return target; }; $.widget.bridge = function( name, object ) { var fullName = object.prototype.widgetFullName || name; $.fn[ name ] = function( options ) { var isMethodCall = typeof options === "string", args = slice.call( arguments, 1 ), returnValue = this; // allow multiple hashes to be passed on init options = !isMethodCall && args.length ? $.widget.extend.apply( null, [ options ].concat(args) ) : options; if ( isMethodCall ) { this.each(function() { var methodValue, instance = $.data( this, fullName ); if ( !instance ) { return $.error( "cannot call methods on " + name + " prior to initialization; " + "attempted to call method '" + options + "'" ); } if ( !$.isFunction( instance[options] ) || options.charAt( 0 ) === "_" ) { return $.error( "no such method '" + options + "' for " + name + " widget instance" ); } methodValue = instance[ options ].apply( instance, args ); if ( methodValue !== instance && methodValue !== undefined ) { returnValue = methodValue && methodValue.jquery ? returnValue.pushStack( methodValue.get() ) : methodValue; return false; } }); } else { this.each(function() { var instance = $.data( this, fullName ); if ( instance ) { instance.option( options || {} )._init(); } else { $.data( this, fullName, new object( options, this ) ); } }); } return returnValue; }; }; $.Widget = function( /* options, element */ ) {}; $.Widget._childConstructors = []; $.Widget.prototype = { widgetName: "widget", widgetEventPrefix: "", defaultElement: "<div>", options: { disabled: false, // callbacks create: null }, _createWidget: function( options, element ) { element = $( element || this.defaultElement || this )[ 0 ]; this.element = $( element ); this.uuid = uuid++; this.eventNamespace = "." + this.widgetName + this.uuid; this.options = $.widget.extend( {}, this.options, this._getCreateOptions(), options ); this.bindings = $(); this.hoverable = $(); this.focusable = $(); if ( element !== this ) { $.data( element, this.widgetFullName, this ); this._on( true, this.element, { remove: function( event ) { if ( event.target === element ) { this.destroy(); } } }); this.document = $( element.style ? // element within the document element.ownerDocument : // element is window or document element.document || element ); this.window = $( this.document[0].defaultView || this.document[0].parentWindow ); } this._create(); this._trigger( "create", null, this._getCreateEventData() ); this._init(); }, _getCreateOptions: $.noop, _getCreateEventData: $.noop, _create: $.noop, _init: $.noop, destroy: function() { this._destroy(); // we can probably remove the unbind calls in 2.0 // all event bindings should go through this._on() this.element .unbind( this.eventNamespace ) // 1.9 BC for #7810 // TODO remove dual storage .removeData( this.widgetName ) .removeData( this.widgetFullName ) // support: jquery <1.6.3 // http://bugs.jquery.com/ticket/9413 .removeData( $.camelCase( this.widgetFullName ) ); this.widget() .unbind( this.eventNamespace ) .removeAttr( "aria-disabled" ) .removeClass( this.widgetFullName + "-disabled " + "ui-state-disabled" ); // clean up events and states this.bindings.unbind( this.eventNamespace ); this.hoverable.removeClass( "ui-state-hover" ); this.focusable.removeClass( "ui-state-focus" ); }, _destroy: $.noop, widget: function() { return this.element; }, option: function( key, value ) { var options = key, parts, curOption, i; if ( arguments.length === 0 ) { // don't return a reference to the internal hash return $.widget.extend( {}, this.options ); } if ( typeof key === "string" ) { // handle nested keys, e.g., "foo.bar" => { foo: { bar: ___ } } options = {}; parts = key.split( "." ); key = parts.shift(); if ( parts.length ) { curOption = options[ key ] = $.widget.extend( {}, this.options[ key ] ); for ( i = 0; i < parts.length - 1; i++ ) { curOption[ parts[ i ] ] = curOption[ parts[ i ] ] || {}; curOption = curOption[ parts[ i ] ]; } key = parts.pop(); if ( value === undefined ) { return curOption[ key ] === undefined ? null : curOption[ key ]; } curOption[ key ] = value; } else { if ( value === undefined ) { return this.options[ key ] === undefined ? null : this.options[ key ]; } options[ key ] = value; } } this._setOptions( options ); return this; }, _setOptions: function( options ) { var key; for ( key in options ) { this._setOption( key, options[ key ] ); } return this; }, _setOption: function( key, value ) { this.options[ key ] = value; if ( key === "disabled" ) { this.widget() .toggleClass( this.widgetFullName + "-disabled ui-state-disabled", !!value ) .attr( "aria-disabled", value ); this.hoverable.removeClass( "ui-state-hover" ); this.focusable.removeClass( "ui-state-focus" ); } return this; }, enable: function() { return this._setOption( "disabled", false ); }, disable: function() { return this._setOption( "disabled", true ); }, _on: function( suppressDisabledCheck, element, handlers ) { var delegateElement, instance = this; // no suppressDisabledCheck flag, shuffle arguments if ( typeof suppressDisabledCheck !== "boolean" ) { handlers = element; element = suppressDisabledCheck; suppressDisabledCheck = false; } // no element argument, shuffle and use this.element if ( !handlers ) { handlers = element; element = this.element; delegateElement = this.widget(); } else { // accept selectors, DOM elements element = delegateElement = $( element ); this.bindings = this.bindings.add( element ); } $.each( handlers, function( event, handler ) { function handlerProxy() { // allow widgets to customize the disabled handling // - disabled as an array instead of boolean // - disabled class as method for disabling individual parts if ( !suppressDisabledCheck && ( instance.options.disabled === true || $( this ).hasClass( "ui-state-disabled" ) ) ) { return; } return ( typeof handler === "string" ? instance[ handler ] : handler ) .apply( instance, arguments ); } // copy the guid so direct unbinding works if ( typeof handler !== "string" ) { handlerProxy.guid = handler.guid = handler.guid || handlerProxy.guid || $.guid++; } var match = event.match( /^(\w+)\s*(.*)$/ ), eventName = match[1] + instance.eventNamespace, selector = match[2]; if ( selector ) { delegateElement.delegate( selector, eventName, handlerProxy ); } else { element.bind( eventName, handlerProxy ); } }); }, _off: function( element, eventName ) { eventName = (eventName || "").split( " " ).join( this.eventNamespace + " " ) + this.eventNamespace; element.unbind( eventName ).undelegate( eventName ); }, _delay: function( handler, delay ) { function handlerProxy() { return ( typeof handler === "string" ? instance[ handler ] : handler ) .apply( instance, arguments ); } var instance = this; return setTimeout( handlerProxy, delay || 0 ); }, _hoverable: function( element ) { this.hoverable = this.hoverable.add( element ); this._on( element, { mouseenter: function( event ) { $( event.currentTarget ).addClass( "ui-state-hover" ); }, mouseleave: function( event ) { $( event.currentTarget ).removeClass( "ui-state-hover" ); } }); }, _focusable: function( element ) { this.focusable = this.focusable.add( element ); this._on( element, { focusin: function( event ) { $( event.currentTarget ).addClass( "ui-state-focus" ); }, focusout: function( event ) { $( event.currentTarget ).removeClass( "ui-state-focus" ); } }); }, _trigger: function( type, event, data ) { var prop, orig, callback = this.options[ type ]; data = data || {}; event = $.Event( event ); event.type = ( type === this.widgetEventPrefix ? type : this.widgetEventPrefix + type ).toLowerCase(); // the original event may come from any element // so we need to reset the target on the new event event.target = this.element[ 0 ]; // copy original event properties over to the new event orig = event.originalEvent; if ( orig ) { for ( prop in orig ) { if ( !( prop in event ) ) { event[ prop ] = orig[ prop ]; } } } this.element.trigger( event, data ); return !( $.isFunction( callback ) && callback.apply( this.element[0], [ event ].concat( data ) ) === false || event.isDefaultPrevented() ); } }; $.each( { show: "fadeIn", hide: "fadeOut" }, function( method, defaultEffect ) { $.Widget.prototype[ "_" + method ] = function( element, options, callback ) { if ( typeof options === "string" ) { options = { effect: options }; } var hasOptions, effectName = !options ? method : options === true || typeof options === "number" ? defaultEffect : options.effect || defaultEffect; options = options || {}; if ( typeof options === "number" ) { options = { duration: options }; } hasOptions = !$.isEmptyObject( options ); options.complete = callback; if ( options.delay ) { element.delay( options.delay ); } if ( hasOptions && $.effects && $.effects.effect[ effectName ] ) { element[ method ]( options ); } else if ( effectName !== method && element[ effectName ] ) { element[ effectName ]( options.duration, options.easing, callback ); } else { element.queue(function( next ) { $( this )[ method ](); if ( callback ) { callback.call( element[ 0 ] ); } next(); }); } }; }); })( jQuery ); (function( $, undefined ) { var mouseHandled = false; $( document ).mouseup( function() { mouseHandled = false; }); $.widget("ui.mouse", { version: "1.10.3", options: { cancel: "input,textarea,button,select,option", distance: 1, delay: 0 }, _mouseInit: function() { var that = this; this.element .bind("mousedown."+this.widgetName, function(event) { return that._mouseDown(event); }) .bind("click."+this.widgetName, function(event) { if (true === $.data(event.target, that.widgetName + ".preventClickEvent")) { $.removeData(event.target, that.widgetName + ".preventClickEvent"); event.stopImmediatePropagation(); return false; } }); this.started = false; }, // TODO: make sure destroying one instance of mouse doesn't mess with // other instances of mouse _mouseDestroy: function() { this.element.unbind("."+this.widgetName); if ( this._mouseMoveDelegate ) { $(document) .unbind("mousemove."+this.widgetName, this._mouseMoveDelegate) .unbind("mouseup."+this.widgetName, this._mouseUpDelegate); } }, _mouseDown: function(event) { // don't let more than one widget handle mouseStart if( mouseHandled ) { return; } // we may have missed mouseup (out of window) (this._mouseStarted && this._mouseUp(event)); this._mouseDownEvent = event; var that = this, btnIsLeft = (event.which === 1), // event.target.nodeName works around a bug in IE 8 with // disabled inputs (#7620) elIsCancel = (typeof this.options.cancel === "string" && event.target.nodeName ? $(event.target).closest(this.options.cancel).length : false); if (!btnIsLeft || elIsCancel || !this._mouseCapture(event)) { return true; } this.mouseDelayMet = !this.options.delay; if (!this.mouseDelayMet) { this._mouseDelayTimer = setTimeout(function() { that.mouseDelayMet = true; }, this.options.delay); } if (this._mouseDistanceMet(event) && this._mouseDelayMet(event)) { this._mouseStarted = (this._mouseStart(event) !== false); if (!this._mouseStarted) { event.preventDefault(); return true; } } // Click event may never have fired (Gecko & Opera) if (true === $.data(event.target, this.widgetName + ".preventClickEvent")) { $.removeData(event.target, this.widgetName + ".preventClickEvent"); } // these delegates are required to keep context this._mouseMoveDelegate = function(event) { return that._mouseMove(event); }; this._mouseUpDelegate = function(event) { return that._mouseUp(event); }; $(document) .bind("mousemove."+this.widgetName, this._mouseMoveDelegate) .bind("mouseup."+this.widgetName, this._mouseUpDelegate); event.preventDefault(); mouseHandled = true; return true; }, _mouseMove: function(event) { // IE mouseup check - mouseup happened when mouse was out of window if ($.ui.ie && ( !document.documentMode || document.documentMode < 9 ) && !event.button) { return this._mouseUp(event); } if (this._mouseStarted) { this._mouseDrag(event); return event.preventDefault(); } if (this._mouseDistanceMet(event) && this._mouseDelayMet(event)) { this._mouseStarted = (this._mouseStart(this._mouseDownEvent, event) !== false); (this._mouseStarted ? this._mouseDrag(event) : this._mouseUp(event)); } return !this._mouseStarted; }, _mouseUp: function(event) { $(document) .unbind("mousemove."+this.widgetName, this._mouseMoveDelegate) .unbind("mouseup."+this.widgetName, this._mouseUpDelegate); if (this._mouseStarted) { this._mouseStarted = false; if (event.target === this._mouseDownEvent.target) { $.data(event.target, this.widgetName + ".preventClickEvent", true); } this._mouseStop(event); } return false; }, _mouseDistanceMet: function(event) { return (Math.max( Math.abs(this._mouseDownEvent.pageX - event.pageX), Math.abs(this._mouseDownEvent.pageY - event.pageY) ) >= this.options.distance ); }, _mouseDelayMet: function(/* event */) { return this.mouseDelayMet; }, // These are placeholder methods, to be overriden by extending plugin _mouseStart: function(/* event */) {}, _mouseDrag: function(/* event */) {}, _mouseStop: function(/* event */) {}, _mouseCapture: function(/* event */) { return true; } }); })(jQuery); (function( $, undefined ) { $.ui = $.ui || {}; var cachedScrollbarWidth, max = Math.max, abs = Math.abs, round = Math.round, rhorizontal = /left|center|right/, rvertical = /top|center|bottom/, roffset = /[\+\-]\d+(\.[\d]+)?%?/, rposition = /^\w+/, rpercent = /%$/, _position = $.fn.position; function getOffsets( offsets, width, height ) { return [ parseFloat( offsets[ 0 ] ) * ( rpercent.test( offsets[ 0 ] ) ? width / 100 : 1 ), parseFloat( offsets[ 1 ] ) * ( rpercent.test( offsets[ 1 ] ) ? height / 100 : 1 ) ]; } function parseCss( element, property ) { return parseInt( $.css( element, property ), 10 ) || 0; } function getDimensions( elem ) { var raw = elem[0]; if ( raw.nodeType === 9 ) { return { width: elem.width(), height: elem.height(), offset: { top: 0, left: 0 } }; } if ( $.isWindow( raw ) ) { return { width: elem.width(), height: elem.height(), offset: { top: elem.scrollTop(), left: elem.scrollLeft() } }; } if ( raw.preventDefault ) { return { width: 0, height: 0, offset: { top: raw.pageY, left: raw.pageX } }; } return { width: elem.outerWidth(), height: elem.outerHeight(), offset: elem.offset() }; } $.position = { scrollbarWidth: function() { if ( cachedScrollbarWidth !== undefined ) { return cachedScrollbarWidth; } var w1, w2, div = $( "<div style='display:block;width:50px;height:50px;overflow:hidden;'><div style='height:100px;width:auto;'></div></div>" ), innerDiv = div.children()[0]; $( "body" ).append( div ); w1 = innerDiv.offsetWidth; div.css( "overflow", "scroll" ); w2 = innerDiv.offsetWidth; if ( w1 === w2 ) { w2 = div[0].clientWidth; } div.remove(); return (cachedScrollbarWidth = w1 - w2); }, getScrollInfo: function( within ) { var overflowX = within.isWindow ? "" : within.element.css( "overflow-x" ), overflowY = within.isWindow ? "" : within.element.css( "overflow-y" ), hasOverflowX = overflowX === "scroll" || ( overflowX === "auto" && within.width < within.element[0].scrollWidth ), hasOverflowY = overflowY === "scroll" || ( overflowY === "auto" && within.height < within.element[0].scrollHeight ); return { width: hasOverflowY ? $.position.scrollbarWidth() : 0, height: hasOverflowX ? $.position.scrollbarWidth() : 0 }; }, getWithinInfo: function( element ) { var withinElement = $( element || window ), isWindow = $.isWindow( withinElement[0] ); return { element: withinElement, isWindow: isWindow, offset: withinElement.offset() || { left: 0, top: 0 }, scrollLeft: withinElement.scrollLeft(), scrollTop: withinElement.scrollTop(), width: isWindow ? withinElement.width() : withinElement.outerWidth(), height: isWindow ? withinElement.height() : withinElement.outerHeight() }; } }; $.fn.position = function( options ) { if ( !options || !options.of ) { return _position.apply( this, arguments ); } // make a copy, we don't want to modify arguments options = $.extend( {}, options ); var atOffset, targetWidth, targetHeight, targetOffset, basePosition, dimensions, target = $( options.of ), within = $.position.getWithinInfo( options.within ), scrollInfo = $.position.getScrollInfo( within ), collision = ( options.collision || "flip" ).split( " " ), offsets = {}; dimensions = getDimensions( target ); if ( target[0].preventDefault ) { // force left top to allow flipping options.at = "left top"; } targetWidth = dimensions.width; targetHeight = dimensions.height; targetOffset = dimensions.offset; // clone to reuse original targetOffset later basePosition = $.extend( {}, targetOffset ); // force my and at to have valid horizontal and vertical positions // if a value is missing or invalid, it will be converted to center $.each( [ "my", "at" ], function() { var pos = ( options[ this ] || "" ).split( " " ), horizontalOffset, verticalOffset; if ( pos.length === 1) { pos = rhorizontal.test( pos[ 0 ] ) ? pos.concat( [ "center" ] ) : rvertical.test( pos[ 0 ] ) ? [ "center" ].concat( pos ) : [ "center", "center" ]; } pos[ 0 ] = rhorizontal.test( pos[ 0 ] ) ? pos[ 0 ] : "center"; pos[ 1 ] = rvertical.test( pos[ 1 ] ) ? pos[ 1 ] : "center"; // calculate offsets horizontalOffset = roffset.exec( pos[ 0 ] ); verticalOffset = roffset.exec( pos[ 1 ] ); offsets[ this ] = [ horizontalOffset ? horizontalOffset[ 0 ] : 0, verticalOffset ? verticalOffset[ 0 ] : 0 ]; // reduce to just the positions without the offsets options[ this ] = [ rposition.exec( pos[ 0 ] )[ 0 ], rposition.exec( pos[ 1 ] )[ 0 ] ]; }); // normalize collision option if ( collision.length === 1 ) { collision[ 1 ] = collision[ 0 ]; } if ( options.at[ 0 ] === "right" ) { basePosition.left += targetWidth; } else if ( options.at[ 0 ] === "center" ) { basePosition.left += targetWidth / 2; } if ( options.at[ 1 ] === "bottom" ) { basePosition.top += targetHeight; } else if ( options.at[ 1 ] === "center" ) { basePosition.top += targetHeight / 2; } atOffset = getOffsets( offsets.at, targetWidth, targetHeight ); basePosition.left += atOffset[ 0 ]; basePosition.top += atOffset[ 1 ]; return this.each(function() { var collisionPosition, using, elem = $( this ), elemWidth = elem.outerWidth(), elemHeight = elem.outerHeight(), marginLeft = parseCss( this, "marginLeft" ), marginTop = parseCss( this, "marginTop" ), collisionWidth = elemWidth + marginLeft + parseCss( this, "marginRight" ) + scrollInfo.width, collisionHeight = elemHeight + marginTop + parseCss( this, "marginBottom" ) + scrollInfo.height, position = $.extend( {}, basePosition ), myOffset = getOffsets( offsets.my, elem.outerWidth(), elem.outerHeight() ); if ( options.my[ 0 ] === "right" ) { position.left -= elemWidth; } else if ( options.my[ 0 ] === "center" ) { position.left -= elemWidth / 2; } if ( options.my[ 1 ] === "bottom" ) { position.top -= elemHeight; } else if ( options.my[ 1 ] === "center" ) { position.top -= elemHeight / 2; } position.left += myOffset[ 0 ]; position.top += myOffset[ 1 ]; // if the browser doesn't support fractions, then round for consistent results if ( !$.support.offsetFractions ) { position.left = round( position.left ); position.top = round( position.top ); } collisionPosition = { marginLeft: marginLeft, marginTop: marginTop }; $.each( [ "left", "top" ], function( i, dir ) { if ( $.ui.position[ collision[ i ] ] ) { $.ui.position[ collision[ i ] ][ dir ]( position, { targetWidth: targetWidth, targetHeight: targetHeight, elemWidth: elemWidth, elemHeight: elemHeight, collisionPosition: collisionPosition, collisionWidth: collisionWidth, collisionHeight: collisionHeight, offset: [ atOffset[ 0 ] + myOffset[ 0 ], atOffset [ 1 ] + myOffset[ 1 ] ], my: options.my, at: options.at, within: within, elem : elem }); } }); if ( options.using ) { // adds feedback as second argument to using callback, if present using = function( props ) { var left = targetOffset.left - position.left, right = left + targetWidth - elemWidth, top = targetOffset.top - position.top, bottom = top + targetHeight - elemHeight, feedback = { target: { element: target, left: targetOffset.left, top: targetOffset.top, width: targetWidth, height: targetHeight }, element: { element: elem, left: position.left, top: position.top, width: elemWidth, height: elemHeight }, horizontal: right < 0 ? "left" : left > 0 ? "right" : "center", vertical: bottom < 0 ? "top" : top > 0 ? "bottom" : "middle" }; if ( targetWidth < elemWidth && abs( left + right ) < targetWidth ) { feedback.horizontal = "center"; } if ( targetHeight < elemHeight && abs( top + bottom ) < targetHeight ) { feedback.vertical = "middle"; } if ( max( abs( left ), abs( right ) ) > max( abs( top ), abs( bottom ) ) ) { feedback.important = "horizontal"; } else { feedback.important = "vertical"; } options.using.call( this, props, feedback ); }; } elem.offset( $.extend( position, { using: using } ) ); }); }; $.ui.position = { fit: { left: function( position, data ) { var within = data.within, withinOffset = within.isWindow ? within.scrollLeft : within.offset.left, outerWidth = within.width, collisionPosLeft = position.left - data.collisionPosition.marginLeft, overLeft = withinOffset - collisionPosLeft, overRight = collisionPosLeft + data.collisionWidth - outerWidth - withinOffset, newOverRight; // element is wider than within if ( data.collisionWidth > outerWidth ) { // element is initially over the left side of within if ( overLeft > 0 && overRight <= 0 ) { newOverRight = position.left + overLeft + data.collisionWidth - outerWidth - withinOffset; position.left += overLeft - newOverRight; // element is initially over right side of within } else if ( overRight > 0 && overLeft <= 0 ) { position.left = withinOffset; // element is initially over both left and right sides of within } else { if ( overLeft > overRight ) { position.left = withinOffset + outerWidth - data.collisionWidth; } else { position.left = withinOffset; } } // too far left -> align with left edge } else if ( overLeft > 0 ) { position.left += overLeft; // too far right -> align with right edge } else if ( overRight > 0 ) { position.left -= overRight; // adjust based on position and margin } else { position.left = max( position.left - collisionPosLeft, position.left ); } }, top: function( position, data ) { var within = data.within, withinOffset = within.isWindow ? within.scrollTop : within.offset.top, outerHeight = data.within.height, collisionPosTop = position.top - data.collisionPosition.marginTop, overTop = withinOffset - collisionPosTop, overBottom = collisionPosTop + data.collisionHeight - outerHeight - withinOffset, newOverBottom; // element is taller than within if ( data.collisionHeight > outerHeight ) { // element is initially over the top of within if ( overTop > 0 && overBottom <= 0 ) { newOverBottom = position.top + overTop + data.collisionHeight - outerHeight - withinOffset; position.top += overTop - newOverBottom; // element is initially over bottom of within } else if ( overBottom > 0 && overTop <= 0 ) { position.top = withinOffset; // element is initially over both top and bottom of within } else { if ( overTop > overBottom ) { position.top = withinOffset + outerHeight - data.collisionHeight; } else { position.top = withinOffset; } } // too far up -> align with top } else if ( overTop > 0 ) { position.top += overTop; // too far down -> align with bottom edge } else if ( overBottom > 0 ) { position.top -= overBottom; // adjust based on position and margin } else { position.top = max( position.top - collisionPosTop, position.top ); } } }, flip: { left: function( position, data ) { var within = data.within, withinOffset = within.offset.left + within.scrollLeft, outerWidth = within.width, offsetLeft = within.isWindow ? within.scrollLeft : within.offset.left, collisionPosLeft = position.left - data.collisionPosition.marginLeft, overLeft = collisionPosLeft - offsetLeft, overRight = collisionPosLeft + data.collisionWidth - outerWidth - offsetLeft, myOffset = data.my[ 0 ] === "left" ? -data.elemWidth : data.my[ 0 ] === "right" ? data.elemWidth : 0, atOffset = data.at[ 0 ] === "left" ? data.targetWidth : data.at[ 0 ] === "right" ? -data.targetWidth : 0, offset = -2 * data.offset[ 0 ], newOverRight, newOverLeft; if ( overLeft < 0 ) { newOverRight = position.left + myOffset + atOffset + offset + data.collisionWidth - outerWidth - withinOffset; if ( newOverRight < 0 || newOverRight < abs( overLeft ) ) { position.left += myOffset + atOffset + offset; } } else if ( overRight > 0 ) { newOverLeft = position.left - data.collisionPosition.marginLeft + myOffset + atOffset + offset - offsetLeft; if ( newOverLeft > 0 || abs( newOverLeft ) < overRight ) { position.left += myOffset + atOffset + offset; } } }, top: function( position, data ) { var within = data.within, withinOffset = within.offset.top + within.scrollTop, outerHeight = within.height, offsetTop = within.isWindow ? within.scrollTop : within.offset.top, collisionPosTop = position.top - data.collisionPosition.marginTop, overTop = collisionPosTop - offsetTop, overBottom = collisionPosTop + data.collisionHeight - outerHeight - offsetTop, top = data.my[ 1 ] === "top", myOffset = top ? -data.elemHeight : data.my[ 1 ] === "bottom" ? data.elemHeight : 0, atOffset = data.at[ 1 ] === "top" ? data.targetHeight : data.at[ 1 ] === "bottom" ? -data.targetHeight : 0, offset = -2 * data.offset[ 1 ], newOverTop, newOverBottom; if ( overTop < 0 ) { newOverBottom = position.top + myOffset + atOffset + offset + data.collisionHeight - outerHeight - withinOffset; if ( ( position.top + myOffset + atOffset + offset) > overTop && ( newOverBottom < 0 || newOverBottom < abs( overTop ) ) ) { position.top += myOffset + atOffset + offset; } } else if ( overBottom > 0 ) { newOverTop = position.top - data.collisionPosition.marginTop + myOffset + atOffset + offset - offsetTop; if ( ( position.top + myOffset + atOffset + offset) > overBottom && ( newOverTop > 0 || abs( newOverTop ) < overBottom ) ) { position.top += myOffset + atOffset + offset; } } } }, flipfit: { left: function() { $.ui.position.flip.left.apply( this, arguments ); $.ui.position.fit.left.apply( this, arguments ); }, top: function() { $.ui.position.flip.top.apply( this, arguments ); $.ui.position.fit.top.apply( this, arguments ); } } }; // fraction support test (function () { var testElement, testElementParent, testElementStyle, offsetLeft, i, body = document.getElementsByTagName( "body" )[ 0 ], div = document.createElement( "div" ); //Create a "fake body" for testing based on method used in jQuery.support testElement = document.createElement( body ? "div" : "body" ); testElementStyle = { visibility: "hidden", width: 0, height: 0, border: 0, margin: 0, background: "none" }; if ( body ) { $.extend( testElementStyle, { position: "absolute", left: "-1000px", top: "-1000px" }); } for ( i in testElementStyle ) { testElement.style[ i ] = testElementStyle[ i ]; } testElement.appendChild( div ); testElementParent = body || document.documentElement; testElementParent.insertBefore( testElement, testElementParent.firstChild ); div.style.cssText = "position: absolute; left: 10.7432222px;"; offsetLeft = $( div ).offset().left; $.support.offsetFractions = offsetLeft > 10 && offsetLeft < 11; testElement.innerHTML = ""; testElementParent.removeChild( testElement ); })(); }( jQuery ) ); (function( $, undefined ) { $.widget("ui.draggable", $.ui.mouse, { version: "1.10.3", widgetEventPrefix: "drag", options: { addClasses: true, appendTo: "parent", axis: false, connectToSortable: false, containment: false, cursor: "auto", cursorAt: false, grid: false, handle: false, helper: "original", iframeFix: false, opacity: false, refreshPositions: false, revert: false, revertDuration: 500, scope: "default", scroll: true, scrollSensitivity: 20, scrollSpeed: 20, snap: false, snapMode: "both", snapTolerance: 20, stack: false, zIndex: false, // callbacks drag: null, start: null, stop: null }, _create: function() { if (this.options.helper === "original" && !(/^(?:r|a|f)/).test(this.element.css("position"))) { this.element[0].style.position = "relative"; } if (this.options.addClasses){ this.element.addClass("ui-draggable"); } if (this.options.disabled){ this.element.addClass("ui-draggable-disabled"); } this._mouseInit(); }, _destroy: function() { this.element.removeClass( "ui-draggable ui-draggable-dragging ui-draggable-disabled" ); this._mouseDestroy(); }, _mouseCapture: function(event) { var o = this.options; // among others, prevent a drag on a resizable-handle if (this.helper || o.disabled || $(event.target).closest(".ui-resizable-handle").length > 0) { return false; } //Quit if we're not on a valid handle this.handle = this._getHandle(event); if (!this.handle) { return false; } $(o.iframeFix === true ? "iframe" : o.iframeFix).each(function() { $("<div class='ui-draggable-iframeFix' style='background: #fff;'></div>") .css({ width: this.offsetWidth+"px", height: this.offsetHeight+"px", position: "absolute", opacity: "0.001", zIndex: 1000 }) .css($(this).offset()) .appendTo("body"); }); return true; }, _mouseStart: function(event) { var o = this.options; //Create and append the visible helper this.helper = this._createHelper(event); this.helper.addClass("ui-draggable-dragging"); //Cache the helper size this._cacheHelperProportions(); //If ddmanager is used for droppables, set the global draggable if($.ui.ddmanager) { $.ui.ddmanager.current = this; } /* * - Position generation - * This block generates everything position related - it's the core of draggables. */ //Cache the margins of the original element this._cacheMargins(); //Store the helper's css position this.cssPosition = this.helper.css( "position" ); this.scrollParent = this.helper.scrollParent(); this.offsetParent = this.helper.offsetParent(); this.offsetParentCssPosition = this.offsetParent.css( "position" ); //The element's absolute position on the page minus margins this.offset = this.positionAbs = this.element.offset(); this.offset = { top: this.offset.top - this.margins.top, left: this.offset.left - this.margins.left }; //Reset scroll cache this.offset.scroll = false; $.extend(this.offset, { click: { //Where the click happened, relative to the element left: event.pageX - this.offset.left, top: event.pageY - this.offset.top }, parent: this._getParentOffset(), relative: this._getRelativeOffset() //This is a relative to absolute position minus the actual position calculation - only used for relative positioned helper }); //Generate the original position this.originalPosition = this.position = this._generatePosition(event); this.originalPageX = event.pageX; this.originalPageY = event.pageY; //Adjust the mouse offset relative to the helper if "cursorAt" is supplied (o.cursorAt && this._adjustOffsetFromHelper(o.cursorAt)); //Set a containment if given in the options this._setContainment(); //Trigger event + callbacks if(this._trigger("start", event) === false) { this._clear(); return false; } //Recache the helper size this._cacheHelperProportions(); //Prepare the droppable offsets if ($.ui.ddmanager && !o.dropBehaviour) { $.ui.ddmanager.prepareOffsets(this, event); } this._mouseDrag(event, true); //Execute the drag once - this causes the helper not to be visible before getting its correct position //If the ddmanager is used for droppables, inform the manager that dragging has started (see #5003) if ( $.ui.ddmanager ) { $.ui.ddmanager.dragStart(this, event); } return true; }, _mouseDrag: function(event, noPropagation) { // reset any necessary cached properties (see #5009) if ( this.offsetParentCssPosition === "fixed" ) { this.offset.parent = this._getParentOffset(); } //Compute the helpers position this.position = this._generatePosition(event); this.positionAbs = this._convertPositionTo("absolute"); //Call plugins and callbacks and use the resulting position if something is returned if (!noPropagation) { var ui = this._uiHash(); if(this._trigger("drag", event, ui) === false) { this._mouseUp({}); return false; } this.position = ui.position; } if(!this.options.axis || this.options.axis !== "y") { this.helper[0].style.left = this.position.left+"px"; } if(!this.options.axis || this.options.axis !== "x") { this.helper[0].style.top = this.position.top+"px"; } if($.ui.ddmanager) { $.ui.ddmanager.drag(this, event); } return false; }, _mouseStop: function(event) { //If we are using droppables, inform the manager about the drop var that = this, dropped = false; if ($.ui.ddmanager && !this.options.dropBehaviour) { dropped = $.ui.ddmanager.drop(this, event); } //if a drop comes from outside (a sortable) if(this.dropped) { dropped = this.dropped; this.dropped = false; } //if the original element is no longer in the DOM don't bother to continue (see #8269) if ( this.options.helper === "original" && !$.contains( this.element[ 0 ].ownerDocument, this.element[ 0 ] ) ) { return false; } if((this.options.revert === "invalid" && !dropped) || (this.options.revert === "valid" && dropped) || this.options.revert === true || ($.isFunction(this.options.revert) && this.options.revert.call(this.element, dropped))) { $(this.helper).animate(this.originalPosition, parseInt(this.options.revertDuration, 10), function() { if(that._trigger("stop", event) !== false) { that._clear(); } }); } else { if(this._trigger("stop", event) !== false) { this._clear(); } } return false; }, _mouseUp: function(event) { //Remove frame helpers $("div.ui-draggable-iframeFix").each(function() { this.parentNode.removeChild(this); }); //If the ddmanager is used for droppables, inform the manager that dragging has stopped (see #5003) if( $.ui.ddmanager ) { $.ui.ddmanager.dragStop(this, event); } return $.ui.mouse.prototype._mouseUp.call(this, event); }, cancel: function() { if(this.helper.is(".ui-draggable-dragging")) { this._mouseUp({}); } else { this._clear(); } return this; }, _getHandle: function(event) { return this.options.handle ? !!$( event.target ).closest( this.element.find( this.options.handle ) ).length : true; }, _createHelper: function(event) { var o = this.options, helper = $.isFunction(o.helper) ? $(o.helper.apply(this.element[0], [event])) : (o.helper === "clone" ? this.element.clone().removeAttr("id") : this.element); if(!helper.parents("body").length) { helper.appendTo((o.appendTo === "parent" ? this.element[0].parentNode : o.appendTo)); } if(helper[0] !== this.element[0] && !(/(fixed|absolute)/).test(helper.css("position"))) { helper.css("position", "absolute"); } return helper; }, _adjustOffsetFromHelper: function(obj) { if (typeof obj === "string") { obj = obj.split(" "); } if ($.isArray(obj)) { obj = {left: +obj[0], top: +obj[1] || 0}; } if ("left" in obj) { this.offset.click.left = obj.left + this.margins.left; } if ("right" in obj) { this.offset.click.left = this.helperProportions.width - obj.right + this.margins.left; } if ("top" in obj) { this.offset.click.top = obj.top + this.margins.top; } if ("bottom" in obj) { this.offset.click.top = this.helperProportions.height - obj.bottom + this.margins.top; } }, _getParentOffset: function() { //Get the offsetParent and cache its position var po = this.offsetParent.offset(); // This is a special case where we need to modify a offset calculated on start, since the following happened: // 1. The position of the helper is absolute, so it's position is calculated based on the next positioned parent // 2. The actual offset parent is a child of the scroll parent, and the scroll parent isn't the document, which means that // the scroll is included in the initial calculation of the offset of the parent, and never recalculated upon drag if(this.cssPosition === "absolute" && this.scrollParent[0] !== document && $.contains(this.scrollParent[0], this.offsetParent[0])) { po.left += this.scrollParent.scrollLeft(); po.top += this.scrollParent.scrollTop(); } //This needs to be actually done for all browsers, since pageX/pageY includes this information //Ugly IE fix if((this.offsetParent[0] === document.body) || (this.offsetParent[0].tagName && this.offsetParent[0].tagName.toLowerCase() === "html" && $.ui.ie)) { po = { top: 0, left: 0 }; } return { top: po.top + (parseInt(this.offsetParent.css("borderTopWidth"),10) || 0), left: po.left + (parseInt(this.offsetParent.css("borderLeftWidth"),10) || 0) }; }, _getRelativeOffset: function() { if(this.cssPosition === "relative") { var p = this.element.position(); return { top: p.top - (parseInt(this.helper.css("top"),10) || 0) + this.scrollParent.scrollTop(), left: p.left - (parseInt(this.helper.css("left"),10) || 0) + this.scrollParent.scrollLeft() }; } else { return { top: 0, left: 0 }; } }, _cacheMargins: function() { this.margins = { left: (parseInt(this.element.css("marginLeft"),10) || 0), top: (parseInt(this.element.css("marginTop"),10) || 0), right: (parseInt(this.element.css("marginRight"),10) || 0), bottom: (parseInt(this.element.css("marginBottom"),10) || 0) }; }, _cacheHelperProportions: function() { this.helperProportions = { width: this.helper.outerWidth(), height: this.helper.outerHeight() }; }, _setContainment: function() { var over, c, ce, o = this.options; if ( !o.containment ) { this.containment = null; return; } if ( o.containment === "window" ) { this.containment = [ $( window ).scrollLeft() - this.offset.relative.left - this.offset.parent.left, $( window ).scrollTop() - this.offset.relative.top - this.offset.parent.top, $( window ).scrollLeft() + $( window ).width() - this.helperProportions.width - this.margins.left, $( window ).scrollTop() + ( $( window ).height() || document.body.parentNode.scrollHeight ) - this.helperProportions.height - this.margins.top ]; return; } if ( o.containment === "document") { this.containment = [ 0, 0, $( document ).width() - this.helperProportions.width - this.margins.left, ( $( document ).height() || document.body.parentNode.scrollHeight ) - this.helperProportions.height - this.margins.top ]; return; } if ( o.containment.constructor === Array ) { this.containment = o.containment; return; } if ( o.containment === "parent" ) { o.containment = this.helper[ 0 ].parentNode; } c = $( o.containment ); ce = c[ 0 ]; if( !ce ) { return; } over = c.css( "overflow" ) !== "hidden"; this.containment = [ ( parseInt( c.css( "borderLeftWidth" ), 10 ) || 0 ) + ( parseInt( c.css( "paddingLeft" ), 10 ) || 0 ), ( parseInt( c.css( "borderTopWidth" ), 10 ) || 0 ) + ( parseInt( c.css( "paddingTop" ), 10 ) || 0 ) , ( over ? Math.max( ce.scrollWidth, ce.offsetWidth ) : ce.offsetWidth ) - ( parseInt( c.css( "borderRightWidth" ), 10 ) || 0 ) - ( parseInt( c.css( "paddingRight" ), 10 ) || 0 ) - this.helperProportions.width - this.margins.left - this.margins.right, ( over ? Math.max( ce.scrollHeight, ce.offsetHeight ) : ce.offsetHeight ) - ( parseInt( c.css( "borderBottomWidth" ), 10 ) || 0 ) - ( parseInt( c.css( "paddingBottom" ), 10 ) || 0 ) - this.helperProportions.height - this.margins.top - this.margins.bottom ]; this.relative_container = c; }, _convertPositionTo: function(d, pos) { if(!pos) { pos = this.position; } var mod = d === "absolute" ? 1 : -1, scroll = this.cssPosition === "absolute" && !( this.scrollParent[ 0 ] !== document && $.contains( this.scrollParent[ 0 ], this.offsetParent[ 0 ] ) ) ? this.offsetParent : this.scrollParent; //Cache the scroll if (!this.offset.scroll) { this.offset.scroll = {top : scroll.scrollTop(), left : scroll.scrollLeft()}; } return { top: ( pos.top + // The absolute mouse position this.offset.relative.top * mod + // Only for relative positioned nodes: Relative offset from element to offset parent this.offset.parent.top * mod - // The offsetParent's offset without borders (offset + border) ( ( this.cssPosition === "fixed" ? -this.scrollParent.scrollTop() : this.offset.scroll.top ) * mod ) ), left: ( pos.left + // The absolute mouse position this.offset.relative.left * mod + // Only for relative positioned nodes: Relative offset from element to offset parent this.offset.parent.left * mod - // The offsetParent's offset without borders (offset + border) ( ( this.cssPosition === "fixed" ? -this.scrollParent.scrollLeft() : this.offset.scroll.left ) * mod ) ) }; }, _generatePosition: function(event) { var containment, co, top, left, o = this.options, scroll = this.cssPosition === "absolute" && !( this.scrollParent[ 0 ] !== document && $.contains( this.scrollParent[ 0 ], this.offsetParent[ 0 ] ) ) ? this.offsetParent : this.scrollParent, pageX = event.pageX, pageY = event.pageY; //Cache the scroll if (!this.offset.scroll) { this.offset.scroll = {top : scroll.scrollTop(), left : scroll.scrollLeft()}; } /* * - Position constraining - * Constrain the position to a mix of grid, containment. */ // If we are not dragging yet, we won't check for options if ( this.originalPosition ) { if ( this.containment ) { if ( this.relative_container ){ co = this.relative_container.offset(); containment = [ this.containment[ 0 ] + co.left, this.containment[ 1 ] + co.top, this.containment[ 2 ] + co.left, this.containment[ 3 ] + co.top ]; } else { containment = this.containment; } if(event.pageX - this.offset.click.left < containment[0]) { pageX = containment[0] + this.offset.click.left; } if(event.pageY - this.offset.click.top < containment[1]) { pageY = containment[1] + this.offset.click.top; } if(event.pageX - this.offset.click.left > containment[2]) { pageX = containment[2] + this.offset.click.left; } if(event.pageY - this.offset.click.top > containment[3]) { pageY = containment[3] + this.offset.click.top; } } if(o.grid) { //Check for grid elements set to 0 to prevent divide by 0 error causing invalid argument errors in IE (see ticket #6950) top = o.grid[1] ? this.originalPageY + Math.round((pageY - this.originalPageY) / o.grid[1]) * o.grid[1] : this.originalPageY; pageY = containment ? ((top - this.offset.click.top >= containment[1] || top - this.offset.click.top > containment[3]) ? top : ((top - this.offset.click.top >= containment[1]) ? top - o.grid[1] : top + o.grid[1])) : top; left = o.grid[0] ? this.originalPageX + Math.round((pageX - this.originalPageX) / o.grid[0]) * o.grid[0] : this.originalPageX; pageX = containment ? ((left - this.offset.click.left >= containment[0] || left - this.offset.click.left > containment[2]) ? left : ((left - this.offset.click.left >= containment[0]) ? left - o.grid[0] : left + o.grid[0])) : left; } } return { top: ( pageY - // The absolute mouse position this.offset.click.top - // Click offset (relative to the element) this.offset.relative.top - // Only for relative positioned nodes: Relative offset from element to offset parent this.offset.parent.top + // The offsetParent's offset without borders (offset + border) ( this.cssPosition === "fixed" ? -this.scrollParent.scrollTop() : this.offset.scroll.top ) ), left: ( pageX - // The absolute mouse position this.offset.click.left - // Click offset (relative to the element) this.offset.relative.left - // Only for relative positioned nodes: Relative offset from element to offset parent this.offset.parent.left + // The offsetParent's offset without borders (offset + border) ( this.cssPosition === "fixed" ? -this.scrollParent.scrollLeft() : this.offset.scroll.left ) ) }; }, _clear: function() { this.helper.removeClass("ui-draggable-dragging"); if(this.helper[0] !== this.element[0] && !this.cancelHelperRemoval) { this.helper.remove(); } this.helper = null; this.cancelHelperRemoval = false; }, // From now on bulk stuff - mainly helpers _trigger: function(type, event, ui) { ui = ui || this._uiHash(); $.ui.plugin.call(this, type, [event, ui]); //The absolute position has to be recalculated after plugins if(type === "drag") { this.positionAbs = this._convertPositionTo("absolute"); } return $.Widget.prototype._trigger.call(this, type, event, ui); }, plugins: {}, _uiHash: function() { return { helper: this.helper, position: this.position, originalPosition: this.originalPosition, offset: this.positionAbs }; } }); $.ui.plugin.add("draggable", "connectToSortable", { start: function(event, ui) { var inst = $(this).data("ui-draggable"), o = inst.options, uiSortable = $.extend({}, ui, { item: inst.element }); inst.sortables = []; $(o.connectToSortable).each(function() { var sortable = $.data(this, "ui-sortable"); if (sortable && !sortable.options.disabled) { inst.sortables.push({ instance: sortable, shouldRevert: sortable.options.revert }); sortable.refreshPositions(); // Call the sortable's refreshPositions at drag start to refresh the containerCache since the sortable container cache is used in drag and needs to be up to date (this will ensure it's initialised as well as being kept in step with any changes that might have happened on the page). sortable._trigger("activate", event, uiSortable); } }); }, stop: function(event, ui) { //If we are still over the sortable, we fake the stop event of the sortable, but also remove helper var inst = $(this).data("ui-draggable"), uiSortable = $.extend({}, ui, { item: inst.element }); $.each(inst.sortables, function() { if(this.instance.isOver) { this.instance.isOver = 0; inst.cancelHelperRemoval = true; //Don't remove the helper in the draggable instance this.instance.cancelHelperRemoval = false; //Remove it in the sortable instance (so sortable plugins like revert still work) //The sortable revert is supported, and we have to set a temporary dropped variable on the draggable to support revert: "valid/invalid" if(this.shouldRevert) { this.instance.options.revert = this.shouldRevert; } //Trigger the stop of the sortable this.instance._mouseStop(event); this.instance.options.helper = this.instance.options._helper; //If the helper has been the original item, restore properties in the sortable if(inst.options.helper === "original") { this.instance.currentItem.css({ top: "auto", left: "auto" }); } } else { this.instance.cancelHelperRemoval = false; //Remove the helper in the sortable instance this.instance._trigger("deactivate", event, uiSortable); } }); }, drag: function(event, ui) { var inst = $(this).data("ui-draggable"), that = this; $.each(inst.sortables, function() { var innermostIntersecting = false, thisSortable = this; //Copy over some variables to allow calling the sortable's native _intersectsWith this.instance.positionAbs = inst.positionAbs; this.instance.helperProportions = inst.helperProportions; this.instance.offset.click = inst.offset.click; if(this.instance._intersectsWith(this.instance.containerCache)) { innermostIntersecting = true; $.each(inst.sortables, function () { this.instance.positionAbs = inst.positionAbs; this.instance.helperProportions = inst.helperProportions; this.instance.offset.click = inst.offset.click; if (this !== thisSortable && this.instance._intersectsWith(this.instance.containerCache) && $.contains(thisSortable.instance.element[0], this.instance.element[0]) ) { innermostIntersecting = false; } return innermostIntersecting; }); } if(innermostIntersecting) { //If it intersects, we use a little isOver variable and set it once, so our move-in stuff gets fired only once if(!this.instance.isOver) { this.instance.isOver = 1; //Now we fake the start of dragging for the sortable instance, //by cloning the list group item, appending it to the sortable and using it as inst.currentItem //We can then fire the start event of the sortable with our passed browser event, and our own helper (so it doesn't create a new one) this.instance.currentItem = $(that).clone().removeAttr("id").appendTo(this.instance.element).data("ui-sortable-item", true); this.instance.options._helper = this.instance.options.helper; //Store helper option to later restore it this.instance.options.helper = function() { return ui.helper[0]; }; event.target = this.instance.currentItem[0]; this.instance._mouseCapture(event, true); this.instance._mouseStart(event, true, true); //Because the browser event is way off the new appended portlet, we modify a couple of variables to reflect the changes this.instance.offset.click.top = inst.offset.click.top; this.instance.offset.click.left = inst.offset.click.left; this.instance.offset.parent.left -= inst.offset.parent.left - this.instance.offset.parent.left; this.instance.offset.parent.top -= inst.offset.parent.top - this.instance.offset.parent.top; inst._trigger("toSortable", event); inst.dropped = this.instance.element; //draggable revert needs that //hack so receive/update callbacks work (mostly) inst.currentItem = inst.element; this.instance.fromOutside = inst; } //Provided we did all the previous steps, we can fire the drag event of the sortable on every draggable drag, when it intersects with the sortable if(this.instance.currentItem) { this.instance._mouseDrag(event); } } else { //If it doesn't intersect with the sortable, and it intersected before, //we fake the drag stop of the sortable, but make sure it doesn't remove the helper by using cancelHelperRemoval if(this.instance.isOver) { this.instance.isOver = 0; this.instance.cancelHelperRemoval = true; //Prevent reverting on this forced stop this.instance.options.revert = false; // The out event needs to be triggered independently this.instance._trigger("out", event, this.instance._uiHash(this.instance)); this.instance._mouseStop(event, true); this.instance.options.helper = this.instance.options._helper; //Now we remove our currentItem, the list group clone again, and the placeholder, and animate the helper back to it's original size this.instance.currentItem.remove(); if(this.instance.placeholder) { this.instance.placeholder.remove(); } inst._trigger("fromSortable", event); inst.dropped = false; //draggable revert needs that } } }); } }); $.ui.plugin.add("draggable", "cursor", { start: function() { var t = $("body"), o = $(this).data("ui-draggable").options; if (t.css("cursor")) { o._cursor = t.css("cursor"); } t.css("cursor", o.cursor); }, stop: function() { var o = $(this).data("ui-draggable").options; if (o._cursor) { $("body").css("cursor", o._cursor); } } }); $.ui.plugin.add("draggable", "opacity", { start: function(event, ui) { var t = $(ui.helper), o = $(this).data("ui-draggable").options; if(t.css("opacity")) { o._opacity = t.css("opacity"); } t.css("opacity", o.opacity); }, stop: function(event, ui) { var o = $(this).data("ui-draggable").options; if(o._opacity) { $(ui.helper).css("opacity", o._opacity); } } }); $.ui.plugin.add("draggable", "scroll", { start: function() { var i = $(this).data("ui-draggable"); if(i.scrollParent[0] !== document && i.scrollParent[0].tagName !== "HTML") { i.overflowOffset = i.scrollParent.offset(); } }, drag: function( event ) { var i = $(this).data("ui-draggable"), o = i.options, scrolled = false; if(i.scrollParent[0] !== document && i.scrollParent[0].tagName !== "HTML") { if(!o.axis || o.axis !== "x") { if((i.overflowOffset.top + i.scrollParent[0].offsetHeight) - event.pageY < o.scrollSensitivity) { i.scrollParent[0].scrollTop = scrolled = i.scrollParent[0].scrollTop + o.scrollSpeed; } else if(event.pageY - i.overflowOffset.top < o.scrollSensitivity) { i.scrollParent[0].scrollTop = scrolled = i.scrollParent[0].scrollTop - o.scrollSpeed; } } if(!o.axis || o.axis !== "y") { if((i.overflowOffset.left + i.scrollParent[0].offsetWidth) - event.pageX < o.scrollSensitivity) { i.scrollParent[0].scrollLeft = scrolled = i.scrollParent[0].scrollLeft + o.scrollSpeed; } else if(event.pageX - i.overflowOffset.left < o.scrollSensitivity) { i.scrollParent[0].scrollLeft = scrolled = i.scrollParent[0].scrollLeft - o.scrollSpeed; } } } else { if(!o.axis || o.axis !== "x") { if(event.pageY - $(document).scrollTop() < o.scrollSensitivity) { scrolled = $(document).scrollTop($(document).scrollTop() - o.scrollSpeed); } else if($(window).height() - (event.pageY - $(document).scrollTop()) < o.scrollSensitivity) { scrolled = $(document).scrollTop($(document).scrollTop() + o.scrollSpeed); } } if(!o.axis || o.axis !== "y") { if(event.pageX - $(document).scrollLeft() < o.scrollSensitivity) { scrolled = $(document).scrollLeft($(document).scrollLeft() - o.scrollSpeed); } else if($(window).width() - (event.pageX - $(document).scrollLeft()) < o.scrollSensitivity) { scrolled = $(document).scrollLeft($(document).scrollLeft() + o.scrollSpeed); } } } if(scrolled !== false && $.ui.ddmanager && !o.dropBehaviour) { $.ui.ddmanager.prepareOffsets(i, event); } } }); $.ui.plugin.add("draggable", "snap", { start: function() { var i = $(this).data("ui-draggable"), o = i.options; i.snapElements = []; $(o.snap.constructor !== String ? ( o.snap.items || ":data(ui-draggable)" ) : o.snap).each(function() { var $t = $(this), $o = $t.offset(); if(this !== i.element[0]) { i.snapElements.push({ item: this, width: $t.outerWidth(), height: $t.outerHeight(), top: $o.top, left: $o.left }); } }); }, drag: function(event, ui) { var ts, bs, ls, rs, l, r, t, b, i, first, inst = $(this).data("ui-draggable"), o = inst.options, d = o.snapTolerance, x1 = ui.offset.left, x2 = x1 + inst.helperProportions.width, y1 = ui.offset.top, y2 = y1 + inst.helperProportions.height; for (i = inst.snapElements.length - 1; i >= 0; i--){ l = inst.snapElements[i].left; r = l + inst.snapElements[i].width; t = inst.snapElements[i].top; b = t + inst.snapElements[i].height; if ( x2 < l - d || x1 > r + d || y2 < t - d || y1 > b + d || !$.contains( inst.snapElements[ i ].item.ownerDocument, inst.snapElements[ i ].item ) ) { if(inst.snapElements[i].snapping) { (inst.options.snap.release && inst.options.snap.release.call(inst.element, event, $.extend(inst._uiHash(), { snapItem: inst.snapElements[i].item }))); } inst.snapElements[i].snapping = false; continue; } if(o.snapMode !== "inner") { ts = Math.abs(t - y2) <= d; bs = Math.abs(b - y1) <= d; ls = Math.abs(l - x2) <= d; rs = Math.abs(r - x1) <= d; if(ts) { ui.position.top = inst._convertPositionTo("relative", { top: t - inst.helperProportions.height, left: 0 }).top - inst.margins.top; } if(bs) { ui.position.top = inst._convertPositionTo("relative", { top: b, left: 0 }).top - inst.margins.top; } if(ls) { ui.position.left = inst._convertPositionTo("relative", { top: 0, left: l - inst.helperProportions.width }).left - inst.margins.left; } if(rs) { ui.position.left = inst._convertPositionTo("relative", { top: 0, left: r }).left - inst.margins.left; } } first = (ts || bs || ls || rs); if(o.snapMode !== "outer") { ts = Math.abs(t - y1) <= d; bs = Math.abs(b - y2) <= d; ls = Math.abs(l - x1) <= d; rs = Math.abs(r - x2) <= d; if(ts) { ui.position.top = inst._convertPositionTo("relative", { top: t, left: 0 }).top - inst.margins.top; } if(bs) { ui.position.top = inst._convertPositionTo("relative", { top: b - inst.helperProportions.height, left: 0 }).top - inst.margins.top; } if(ls) { ui.position.left = inst._convertPositionTo("relative", { top: 0, left: l }).left - inst.margins.left; } if(rs) { ui.position.left = inst._convertPositionTo("relative", { top: 0, left: r - inst.helperProportions.width }).left - inst.margins.left; } } if(!inst.snapElements[i].snapping && (ts || bs || ls || rs || first)) { (inst.options.snap.snap && inst.options.snap.snap.call(inst.element, event, $.extend(inst._uiHash(), { snapItem: inst.snapElements[i].item }))); } inst.snapElements[i].snapping = (ts || bs || ls || rs || first); } } }); $.ui.plugin.add("draggable", "stack", { start: function() { var min, o = this.data("ui-draggable").options, group = $.makeArray($(o.stack)).sort(function(a,b) { return (parseInt($(a).css("zIndex"),10) || 0) - (parseInt($(b).css("zIndex"),10) || 0); }); if (!group.length) { return; } min = parseInt($(group[0]).css("zIndex"), 10) || 0; $(group).each(function(i) { $(this).css("zIndex", min + i); }); this.css("zIndex", (min + group.length)); } }); $.ui.plugin.add("draggable", "zIndex", { start: function(event, ui) { var t = $(ui.helper), o = $(this).data("ui-draggable").options; if(t.css("zIndex")) { o._zIndex = t.css("zIndex"); } t.css("zIndex", o.zIndex); }, stop: function(event, ui) { var o = $(this).data("ui-draggable").options; if(o._zIndex) { $(ui.helper).css("zIndex", o._zIndex); } } }); })(jQuery); (function( $, undefined ) { function isOverAxis( x, reference, size ) { return ( x > reference ) && ( x < ( reference + size ) ); } $.widget("ui.droppable", { version: "1.10.3", widgetEventPrefix: "drop", options: { accept: "*", activeClass: false, addClasses: true, greedy: false, hoverClass: false, scope: "default", tolerance: "intersect", // callbacks activate: null, deactivate: null, drop: null, out: null, over: null }, _create: function() { var o = this.options, accept = o.accept; this.isover = false; this.isout = true; this.accept = $.isFunction(accept) ? accept : function(d) { return d.is(accept); }; //Store the droppable's proportions this.proportions = { width: this.element[0].offsetWidth, height: this.element[0].offsetHeight }; // Add the reference and positions to the manager $.ui.ddmanager.droppables[o.scope] = $.ui.ddmanager.droppables[o.scope] || []; $.ui.ddmanager.droppables[o.scope].push(this); (o.addClasses && this.element.addClass("ui-droppable")); }, _destroy: function() { var i = 0, drop = $.ui.ddmanager.droppables[this.options.scope]; for ( ; i < drop.length; i++ ) { if ( drop[i] === this ) { drop.splice(i, 1); } } this.element.removeClass("ui-droppable ui-droppable-disabled"); }, _setOption: function(key, value) { if(key === "accept") { this.accept = $.isFunction(value) ? value : function(d) { return d.is(value); }; } $.Widget.prototype._setOption.apply(this, arguments); }, _activate: function(event) { var draggable = $.ui.ddmanager.current; if(this.options.activeClass) { this.element.addClass(this.options.activeClass); } if(draggable){ this._trigger("activate", event, this.ui(draggable)); } }, _deactivate: function(event) { var draggable = $.ui.ddmanager.current; if(this.options.activeClass) { this.element.removeClass(this.options.activeClass); } if(draggable){ this._trigger("deactivate", event, this.ui(draggable)); } }, _over: function(event) { var draggable = $.ui.ddmanager.current; // Bail if draggable and droppable are same element if (!draggable || (draggable.currentItem || draggable.element)[0] === this.element[0]) { return; } if (this.accept.call(this.element[0],(draggable.currentItem || draggable.element))) { if(this.options.hoverClass) { this.element.addClass(this.options.hoverClass); } this._trigger("over", event, this.ui(draggable)); } }, _out: function(event) { var draggable = $.ui.ddmanager.current; // Bail if draggable and droppable are same element if (!draggable || (draggable.currentItem || draggable.element)[0] === this.element[0]) { return; } if (this.accept.call(this.element[0],(draggable.currentItem || draggable.element))) { if(this.options.hoverClass) { this.element.removeClass(this.options.hoverClass); } this._trigger("out", event, this.ui(draggable)); } }, _drop: function(event,custom) { var draggable = custom || $.ui.ddmanager.current, childrenIntersection = false; // Bail if draggable and droppable are same element if (!draggable || (draggable.currentItem || draggable.element)[0] === this.element[0]) { return false; } this.element.find(":data(ui-droppable)").not(".ui-draggable-dragging").each(function() { var inst = $.data(this, "ui-droppable"); if( inst.options.greedy && !inst.options.disabled && inst.options.scope === draggable.options.scope && inst.accept.call(inst.element[0], (draggable.currentItem || draggable.element)) && $.ui.intersect(draggable, $.extend(inst, { offset: inst.element.offset() }), inst.options.tolerance) ) { childrenIntersection = true; return false; } }); if(childrenIntersection) { return false; } if(this.accept.call(this.element[0],(draggable.currentItem || draggable.element))) { if(this.options.activeClass) { this.element.removeClass(this.options.activeClass); } if(this.options.hoverClass) { this.element.removeClass(this.options.hoverClass); } this._trigger("drop", event, this.ui(draggable)); return this.element; } return false; }, ui: function(c) { return { draggable: (c.currentItem || c.element), helper: c.helper, position: c.position, offset: c.positionAbs }; } }); $.ui.intersect = function(draggable, droppable, toleranceMode) { if (!droppable.offset) { return false; } var draggableLeft, draggableTop, x1 = (draggable.positionAbs || draggable.position.absolute).left, x2 = x1 + draggable.helperProportions.width, y1 = (draggable.positionAbs || draggable.position.absolute).top, y2 = y1 + draggable.helperProportions.height, l = droppable.offset.left, r = l + droppable.proportions.width, t = droppable.offset.top, b = t + droppable.proportions.height; switch (toleranceMode) { case "fit": return (l <= x1 && x2 <= r && t <= y1 && y2 <= b); case "intersect": return (l < x1 + (draggable.helperProportions.width / 2) && // Right Half x2 - (draggable.helperProportions.width / 2) < r && // Left Half t < y1 + (draggable.helperProportions.height / 2) && // Bottom Half y2 - (draggable.helperProportions.height / 2) < b ); // Top Half case "pointer": draggableLeft = ((draggable.positionAbs || draggable.position.absolute).left + (draggable.clickOffset || draggable.offset.click).left); draggableTop = ((draggable.positionAbs || draggable.position.absolute).top + (draggable.clickOffset || draggable.offset.click).top); return isOverAxis( draggableTop, t, droppable.proportions.height ) && isOverAxis( draggableLeft, l, droppable.proportions.width ); case "touch": return ( (y1 >= t && y1 <= b) || // Top edge touching (y2 >= t && y2 <= b) || // Bottom edge touching (y1 < t && y2 > b) // Surrounded vertically ) && ( (x1 >= l && x1 <= r) || // Left edge touching (x2 >= l && x2 <= r) || // Right edge touching (x1 < l && x2 > r) // Surrounded horizontally ); default: return false; } }; /* This manager tracks offsets of draggables and droppables */ $.ui.ddmanager = { current: null, droppables: { "default": [] }, prepareOffsets: function(t, event) { var i, j, m = $.ui.ddmanager.droppables[t.options.scope] || [], type = event ? event.type : null, // workaround for #2317 list = (t.currentItem || t.element).find(":data(ui-droppable)").addBack(); droppablesLoop: for (i = 0; i < m.length; i++) { //No disabled and non-accepted if(m[i].options.disabled || (t && !m[i].accept.call(m[i].element[0],(t.currentItem || t.element)))) { continue; } // Filter out elements in the current dragged item for (j=0; j < list.length; j++) { if(list[j] === m[i].element[0]) { m[i].proportions.height = 0; continue droppablesLoop; } } m[i].visible = m[i].element.css("display") !== "none"; if(!m[i].visible) { continue; } //Activate the droppable if used directly from draggables if(type === "mousedown") { m[i]._activate.call(m[i], event); } m[i].offset = m[i].element.offset(); m[i].proportions = { width: m[i].element[0].offsetWidth, height: m[i].element[0].offsetHeight }; } }, drop: function(draggable, event) { var dropped = false; // Create a copy of the droppables in case the list changes during the drop (#9116) $.each(($.ui.ddmanager.droppables[draggable.options.scope] || []).slice(), function() { if(!this.options) { return; } if (!this.options.disabled && this.visible && $.ui.intersect(draggable, this, this.options.tolerance)) { dropped = this._drop.call(this, event) || dropped; } if (!this.options.disabled && this.visible && this.accept.call(this.element[0],(draggable.currentItem || draggable.element))) { this.isout = true; this.isover = false; this._deactivate.call(this, event); } }); return dropped; }, dragStart: function( draggable, event ) { //Listen for scrolling so that if the dragging causes scrolling the position of the droppables can be recalculated (see #5003) draggable.element.parentsUntil( "body" ).bind( "scroll.droppable", function() { if( !draggable.options.refreshPositions ) { $.ui.ddmanager.prepareOffsets( draggable, event ); } }); }, drag: function(draggable, event) { //If you have a highly dynamic page, you might try this option. It renders positions every time you move the mouse. if(draggable.options.refreshPositions) { $.ui.ddmanager.prepareOffsets(draggable, event); } //Run through all droppables and check their positions based on specific tolerance options $.each($.ui.ddmanager.droppables[draggable.options.scope] || [], function() { if(this.options.disabled || this.greedyChild || !this.visible) { return; } var parentInstance, scope, parent, intersects = $.ui.intersect(draggable, this, this.options.tolerance), c = !intersects && this.isover ? "isout" : (intersects && !this.isover ? "isover" : null); if(!c) { return; } if (this.options.greedy) { // find droppable parents with same scope scope = this.options.scope; parent = this.element.parents(":data(ui-droppable)").filter(function () { return $.data(this, "ui-droppable").options.scope === scope; }); if (parent.length) { parentInstance = $.data(parent[0], "ui-droppable"); parentInstance.greedyChild = (c === "isover"); } } // we just moved into a greedy child if (parentInstance && c === "isover") { parentInstance.isover = false; parentInstance.isout = true; parentInstance._out.call(parentInstance, event); } this[c] = true; this[c === "isout" ? "isover" : "isout"] = false; this[c === "isover" ? "_over" : "_out"].call(this, event); // we just moved out of a greedy child if (parentInstance && c === "isout") { parentInstance.isout = false; parentInstance.isover = true; parentInstance._over.call(parentInstance, event); } }); }, dragStop: function( draggable, event ) { draggable.element.parentsUntil( "body" ).unbind( "scroll.droppable" ); //Call prepareOffsets one final time since IE does not fire return scroll events when overflow was caused by drag (see #5003) if( !draggable.options.refreshPositions ) { $.ui.ddmanager.prepareOffsets( draggable, event ); } } }; })(jQuery); (function( $, undefined ) { function num(v) { return parseInt(v, 10) || 0; } function isNumber(value) { return !isNaN(parseInt(value, 10)); } $.widget("ui.resizable", $.ui.mouse, { version: "1.10.3", widgetEventPrefix: "resize", options: { alsoResize: false, animate: false, animateDuration: "slow", animateEasing: "swing", aspectRatio: false, autoHide: false, containment: false, ghost: false, grid: false, handles: "e,s,se", helper: false, maxHeight: null, maxWidth: null, minHeight: 10, minWidth: 10, // See #7960 zIndex: 90, // callbacks resize: null, start: null, stop: null }, _create: function() { var n, i, handle, axis, hname, that = this, o = this.options; this.element.addClass("ui-resizable"); $.extend(this, { _aspectRatio: !!(o.aspectRatio), aspectRatio: o.aspectRatio, originalElement: this.element, _proportionallyResizeElements: [], _helper: o.helper || o.ghost || o.animate ? o.helper || "ui-resizable-helper" : null }); //Wrap the element if it cannot hold child nodes if(this.element[0].nodeName.match(/canvas|textarea|input|select|button|img/i)) { //Create a wrapper element and set the wrapper to the new current internal element this.element.wrap( $("<div class='ui-wrapper' style='overflow: hidden;'></div>").css({ position: this.element.css("position"), width: this.element.outerWidth(), height: this.element.outerHeight(), top: this.element.css("top"), left: this.element.css("left") }) ); //Overwrite the original this.element this.element = this.element.parent().data( "ui-resizable", this.element.data("ui-resizable") ); this.elementIsWrapper = true; //Move margins to the wrapper this.element.css({ marginLeft: this.originalElement.css("marginLeft"), marginTop: this.originalElement.css("marginTop"), marginRight: this.originalElement.css("marginRight"), marginBottom: this.originalElement.css("marginBottom") }); this.originalElement.css({ marginLeft: 0, marginTop: 0, marginRight: 0, marginBottom: 0}); //Prevent Safari textarea resize this.originalResizeStyle = this.originalElement.css("resize"); this.originalElement.css("resize", "none"); //Push the actual element to our proportionallyResize internal array this._proportionallyResizeElements.push(this.originalElement.css({ position: "static", zoom: 1, display: "block" })); // avoid IE jump (hard set the margin) this.originalElement.css({ margin: this.originalElement.css("margin") }); // fix handlers offset this._proportionallyResize(); } this.handles = o.handles || (!$(".ui-resizable-handle", this.element).length ? "e,s,se" : { n: ".ui-resizable-n", e: ".ui-resizable-e", s: ".ui-resizable-s", w: ".ui-resizable-w", se: ".ui-resizable-se", sw: ".ui-resizable-sw", ne: ".ui-resizable-ne", nw: ".ui-resizable-nw" }); if(this.handles.constructor === String) { if ( this.handles === "all") { this.handles = "n,e,s,w,se,sw,ne,nw"; } n = this.handles.split(","); this.handles = {}; for(i = 0; i < n.length; i++) { handle = $.trim(n[i]); hname = "ui-resizable-"+handle; axis = $("<div class='ui-resizable-handle " + hname + "'></div>"); // Apply zIndex to all handles - see #7960 axis.css({ zIndex: o.zIndex }); //TODO : What's going on here? if ("se" === handle) { axis.addClass("ui-icon ui-icon-gripsmall-diagonal-se"); } //Insert into internal handles object and append to element this.handles[handle] = ".ui-resizable-"+handle; this.element.append(axis); } } this._renderAxis = function(target) { var i, axis, padPos, padWrapper; target = target || this.element; for(i in this.handles) { if(this.handles[i].constructor === String) { this.handles[i] = $(this.handles[i], this.element).show(); } //Apply pad to wrapper element, needed to fix axis position (textarea, inputs, scrolls) if (this.elementIsWrapper && this.originalElement[0].nodeName.match(/textarea|input|select|button/i)) { axis = $(this.handles[i], this.element); //Checking the correct pad and border padWrapper = /sw|ne|nw|se|n|s/.test(i) ? axis.outerHeight() : axis.outerWidth(); //The padding type i have to apply... padPos = [ "padding", /ne|nw|n/.test(i) ? "Top" : /se|sw|s/.test(i) ? "Bottom" : /^e$/.test(i) ? "Right" : "Left" ].join(""); target.css(padPos, padWrapper); this._proportionallyResize(); } //TODO: What's that good for? There's not anything to be executed left if(!$(this.handles[i]).length) { continue; } } }; //TODO: make renderAxis a prototype function this._renderAxis(this.element); this._handles = $(".ui-resizable-handle", this.element) .disableSelection(); //Matching axis name this._handles.mouseover(function() { if (!that.resizing) { if (this.className) { axis = this.className.match(/ui-resizable-(se|sw|ne|nw|n|e|s|w)/i); } //Axis, default = se that.axis = axis && axis[1] ? axis[1] : "se"; } }); //If we want to auto hide the elements if (o.autoHide) { this._handles.hide(); $(this.element) .addClass("ui-resizable-autohide") .mouseenter(function() { if (o.disabled) { return; } $(this).removeClass("ui-resizable-autohide"); that._handles.show(); }) .mouseleave(function(){ if (o.disabled) { return; } if (!that.resizing) { $(this).addClass("ui-resizable-autohide"); that._handles.hide(); } }); } //Initialize the mouse interaction this._mouseInit(); }, _destroy: function() { this._mouseDestroy(); var wrapper, _destroy = function(exp) { $(exp).removeClass("ui-resizable ui-resizable-disabled ui-resizable-resizing") .removeData("resizable").removeData("ui-resizable").unbind(".resizable").find(".ui-resizable-handle").remove(); }; //TODO: Unwrap at same DOM position if (this.elementIsWrapper) { _destroy(this.element); wrapper = this.element; this.originalElement.css({ position: wrapper.css("position"), width: wrapper.outerWidth(), height: wrapper.outerHeight(), top: wrapper.css("top"), left: wrapper.css("left") }).insertAfter( wrapper ); wrapper.remove(); } this.originalElement.css("resize", this.originalResizeStyle); _destroy(this.originalElement); return this; }, _mouseCapture: function(event) { var i, handle, capture = false; for (i in this.handles) { handle = $(this.handles[i])[0]; if (handle === event.target || $.contains(handle, event.target)) { capture = true; } } return !this.options.disabled && capture; }, _mouseStart: function(event) { var curleft, curtop, cursor, o = this.options, iniPos = this.element.position(), el = this.element; this.resizing = true; // bugfix for http://dev.jquery.com/ticket/1749 if ( (/absolute/).test( el.css("position") ) ) { el.css({ position: "absolute", top: el.css("top"), left: el.css("left") }); } else if (el.is(".ui-draggable")) { el.css({ position: "absolute", top: iniPos.top, left: iniPos.left }); } this._renderProxy(); curleft = num(this.helper.css("left")); curtop = num(this.helper.css("top")); if (o.containment) { curleft += $(o.containment).scrollLeft() || 0; curtop += $(o.containment).scrollTop() || 0; } //Store needed variables this.offset = this.helper.offset(); this.position = { left: curleft, top: curtop }; this.size = this._helper ? { width: el.outerWidth(), height: el.outerHeight() } : { width: el.width(), height: el.height() }; this.originalSize = this._helper ? { width: el.outerWidth(), height: el.outerHeight() } : { width: el.width(), height: el.height() }; this.originalPosition = { left: curleft, top: curtop }; this.sizeDiff = { width: el.outerWidth() - el.width(), height: el.outerHeight() - el.height() }; this.originalMousePosition = { left: event.pageX, top: event.pageY }; //Aspect Ratio this.aspectRatio = (typeof o.aspectRatio === "number") ? o.aspectRatio : ((this.originalSize.width / this.originalSize.height) || 1); cursor = $(".ui-resizable-" + this.axis).css("cursor"); $("body").css("cursor", cursor === "auto" ? this.axis + "-resize" : cursor); el.addClass("ui-resizable-resizing"); this._propagate("start", event); return true; }, _mouseDrag: function(event) { //Increase performance, avoid regex var data, el = this.helper, props = {}, smp = this.originalMousePosition, a = this.axis, prevTop = this.position.top, prevLeft = this.position.left, prevWidth = this.size.width, prevHeight = this.size.height, dx = (event.pageX-smp.left)||0, dy = (event.pageY-smp.top)||0, trigger = this._change[a]; if (!trigger) { return false; } // Calculate the attrs that will be change data = trigger.apply(this, [event, dx, dy]); // Put this in the mouseDrag handler since the user can start pressing shift while resizing this._updateVirtualBoundaries(event.shiftKey); if (this._aspectRatio || event.shiftKey) { data = this._updateRatio(data, event); } data = this._respectSize(data, event); this._updateCache(data); // plugins callbacks need to be called first this._propagate("resize", event); if (this.position.top !== prevTop) { props.top = this.position.top + "px"; } if (this.position.left !== prevLeft) { props.left = this.position.left + "px"; } if (this.size.width !== prevWidth) { props.width = this.size.width + "px"; } if (this.size.height !== prevHeight) { props.height = this.size.height + "px"; } el.css(props); if (!this._helper && this._proportionallyResizeElements.length) { this._proportionallyResize(); } // Call the user callback if the element was resized if ( ! $.isEmptyObject(props) ) { this._trigger("resize", event, this.ui()); } return false; }, _mouseStop: function(event) { this.resizing = false; var pr, ista, soffseth, soffsetw, s, left, top, o = this.options, that = this; if(this._helper) { pr = this._proportionallyResizeElements; ista = pr.length && (/textarea/i).test(pr[0].nodeName); soffseth = ista && $.ui.hasScroll(pr[0], "left") /* TODO - jump height */ ? 0 : that.sizeDiff.height; soffsetw = ista ? 0 : that.sizeDiff.width; s = { width: (that.helper.width() - soffsetw), height: (that.helper.height() - soffseth) }; left = (parseInt(that.element.css("left"), 10) + (that.position.left - that.originalPosition.left)) || null; top = (parseInt(that.element.css("top"), 10) + (that.position.top - that.originalPosition.top)) || null; if (!o.animate) { this.element.css($.extend(s, { top: top, left: left })); } that.helper.height(that.size.height); that.helper.width(that.size.width); if (this._helper && !o.animate) { this._proportionallyResize(); } } $("body").css("cursor", "auto"); this.element.removeClass("ui-resizable-resizing"); this._propagate("stop", event); if (this._helper) { this.helper.remove(); } return false; }, _updateVirtualBoundaries: function(forceAspectRatio) { var pMinWidth, pMaxWidth, pMinHeight, pMaxHeight, b, o = this.options; b = { minWidth: isNumber(o.minWidth) ? o.minWidth : 0, maxWidth: isNumber(o.maxWidth) ? o.maxWidth : Infinity, minHeight: isNumber(o.minHeight) ? o.minHeight : 0, maxHeight: isNumber(o.maxHeight) ? o.maxHeight : Infinity }; if(this._aspectRatio || forceAspectRatio) { // We want to create an enclosing box whose aspect ration is the requested one // First, compute the "projected" size for each dimension based on the aspect ratio and other dimension pMinWidth = b.minHeight * this.aspectRatio; pMinHeight = b.minWidth / this.aspectRatio; pMaxWidth = b.maxHeight * this.aspectRatio; pMaxHeight = b.maxWidth / this.aspectRatio; if(pMinWidth > b.minWidth) { b.minWidth = pMinWidth; } if(pMinHeight > b.minHeight) { b.minHeight = pMinHeight; } if(pMaxWidth < b.maxWidth) { b.maxWidth = pMaxWidth; } if(pMaxHeight < b.maxHeight) { b.maxHeight = pMaxHeight; } } this._vBoundaries = b; }, _updateCache: function(data) { this.offset = this.helper.offset(); if (isNumber(data.left)) { this.position.left = data.left; } if (isNumber(data.top)) { this.position.top = data.top; } if (isNumber(data.height)) { this.size.height = data.height; } if (isNumber(data.width)) { this.size.width = data.width; } }, _updateRatio: function( data ) { var cpos = this.position, csize = this.size, a = this.axis; if (isNumber(data.height)) { data.width = (data.height * this.aspectRatio); } else if (isNumber(data.width)) { data.height = (data.width / this.aspectRatio); } if (a === "sw") { data.left = cpos.left + (csize.width - data.width); data.top = null; } if (a === "nw") { data.top = cpos.top + (csize.height - data.height); data.left = cpos.left + (csize.width - data.width); } return data; }, _respectSize: function( data ) { var o = this._vBoundaries, a = this.axis, ismaxw = isNumber(data.width) && o.maxWidth && (o.maxWidth < data.width), ismaxh = isNumber(data.height) && o.maxHeight && (o.maxHeight < data.height), isminw = isNumber(data.width) && o.minWidth && (o.minWidth > data.width), isminh = isNumber(data.height) && o.minHeight && (o.minHeight > data.height), dw = this.originalPosition.left + this.originalSize.width, dh = this.position.top + this.size.height, cw = /sw|nw|w/.test(a), ch = /nw|ne|n/.test(a); if (isminw) { data.width = o.minWidth; } if (isminh) { data.height = o.minHeight; } if (ismaxw) { data.width = o.maxWidth; } if (ismaxh) { data.height = o.maxHeight; } if (isminw && cw) { data.left = dw - o.minWidth; } if (ismaxw && cw) { data.left = dw - o.maxWidth; } if (isminh && ch) { data.top = dh - o.minHeight; } if (ismaxh && ch) { data.top = dh - o.maxHeight; } // fixing jump error on top/left - bug #2330 if (!data.width && !data.height && !data.left && data.top) { data.top = null; } else if (!data.width && !data.height && !data.top && data.left) { data.left = null; } return data; }, _proportionallyResize: function() { if (!this._proportionallyResizeElements.length) { return; } var i, j, borders, paddings, prel, element = this.helper || this.element; for ( i=0; i < this._proportionallyResizeElements.length; i++) { prel = this._proportionallyResizeElements[i]; if (!this.borderDif) { this.borderDif = []; borders = [prel.css("borderTopWidth"), prel.css("borderRightWidth"), prel.css("borderBottomWidth"), prel.css("borderLeftWidth")]; paddings = [prel.css("paddingTop"), prel.css("paddingRight"), prel.css("paddingBottom"), prel.css("paddingLeft")]; for ( j = 0; j < borders.length; j++ ) { this.borderDif[ j ] = ( parseInt( borders[ j ], 10 ) || 0 ) + ( parseInt( paddings[ j ], 10 ) || 0 ); } } prel.css({ height: (element.height() - this.borderDif[0] - this.borderDif[2]) || 0, width: (element.width() - this.borderDif[1] - this.borderDif[3]) || 0 }); } }, _renderProxy: function() { var el = this.element, o = this.options; this.elementOffset = el.offset(); if(this._helper) { this.helper = this.helper || $("<div style='overflow:hidden;'></div>"); this.helper.addClass(this._helper).css({ width: this.element.outerWidth() - 1, height: this.element.outerHeight() - 1, position: "absolute", left: this.elementOffset.left +"px", top: this.elementOffset.top +"px", zIndex: ++o.zIndex //TODO: Don't modify option }); this.helper .appendTo("body") .disableSelection(); } else { this.helper = this.element; } }, _change: { e: function(event, dx) { return { width: this.originalSize.width + dx }; }, w: function(event, dx) { var cs = this.originalSize, sp = this.originalPosition; return { left: sp.left + dx, width: cs.width - dx }; }, n: function(event, dx, dy) { var cs = this.originalSize, sp = this.originalPosition; return { top: sp.top + dy, height: cs.height - dy }; }, s: function(event, dx, dy) { return { height: this.originalSize.height + dy }; }, se: function(event, dx, dy) { return $.extend(this._change.s.apply(this, arguments), this._change.e.apply(this, [event, dx, dy])); }, sw: function(event, dx, dy) { return $.extend(this._change.s.apply(this, arguments), this._change.w.apply(this, [event, dx, dy])); }, ne: function(event, dx, dy) { return $.extend(this._change.n.apply(this, arguments), this._change.e.apply(this, [event, dx, dy])); }, nw: function(event, dx, dy) { return $.extend(this._change.n.apply(this, arguments), this._change.w.apply(this, [event, dx, dy])); } }, _propagate: function(n, event) { $.ui.plugin.call(this, n, [event, this.ui()]); (n !== "resize" && this._trigger(n, event, this.ui())); }, plugins: {}, ui: function() { return { originalElement: this.originalElement, element: this.element, helper: this.helper, position: this.position, size: this.size, originalSize: this.originalSize, originalPosition: this.originalPosition }; } }); /* * Resizable Extensions */ $.ui.plugin.add("resizable", "animate", { stop: function( event ) { var that = $(this).data("ui-resizable"), o = that.options, pr = that._proportionallyResizeElements, ista = pr.length && (/textarea/i).test(pr[0].nodeName), soffseth = ista && $.ui.hasScroll(pr[0], "left") /* TODO - jump height */ ? 0 : that.sizeDiff.height, soffsetw = ista ? 0 : that.sizeDiff.width, style = { width: (that.size.width - soffsetw), height: (that.size.height - soffseth) }, left = (parseInt(that.element.css("left"), 10) + (that.position.left - that.originalPosition.left)) || null, top = (parseInt(that.element.css("top"), 10) + (that.position.top - that.originalPosition.top)) || null; that.element.animate( $.extend(style, top && left ? { top: top, left: left } : {}), { duration: o.animateDuration, easing: o.animateEasing, step: function() { var data = { width: parseInt(that.element.css("width"), 10), height: parseInt(that.element.css("height"), 10), top: parseInt(that.element.css("top"), 10), left: parseInt(that.element.css("left"), 10) }; if (pr && pr.length) { $(pr[0]).css({ width: data.width, height: data.height }); } // propagating resize, and updating values for each animation step that._updateCache(data); that._propagate("resize", event); } } ); } }); $.ui.plugin.add("resizable", "containment", { start: function() { var element, p, co, ch, cw, width, height, that = $(this).data("ui-resizable"), o = that.options, el = that.element, oc = o.containment, ce = (oc instanceof $) ? oc.get(0) : (/parent/.test(oc)) ? el.parent().get(0) : oc; if (!ce) { return; } that.containerElement = $(ce); if (/document/.test(oc) || oc === document) { that.containerOffset = { left: 0, top: 0 }; that.containerPosition = { left: 0, top: 0 }; that.parentData = { element: $(document), left: 0, top: 0, width: $(document).width(), height: $(document).height() || document.body.parentNode.scrollHeight }; } // i'm a node, so compute top, left, right, bottom else { element = $(ce); p = []; $([ "Top", "Right", "Left", "Bottom" ]).each(function(i, name) { p[i] = num(element.css("padding" + name)); }); that.containerOffset = element.offset(); that.containerPosition = element.position(); that.containerSize = { height: (element.innerHeight() - p[3]), width: (element.innerWidth() - p[1]) }; co = that.containerOffset; ch = that.containerSize.height; cw = that.containerSize.width; width = ($.ui.hasScroll(ce, "left") ? ce.scrollWidth : cw ); height = ($.ui.hasScroll(ce) ? ce.scrollHeight : ch); that.parentData = { element: ce, left: co.left, top: co.top, width: width, height: height }; } }, resize: function( event ) { var woset, hoset, isParent, isOffsetRelative, that = $(this).data("ui-resizable"), o = that.options, co = that.containerOffset, cp = that.position, pRatio = that._aspectRatio || event.shiftKey, cop = { top:0, left:0 }, ce = that.containerElement; if (ce[0] !== document && (/static/).test(ce.css("position"))) { cop = co; } if (cp.left < (that._helper ? co.left : 0)) { that.size.width = that.size.width + (that._helper ? (that.position.left - co.left) : (that.position.left - cop.left)); if (pRatio) { that.size.height = that.size.width / that.aspectRatio; } that.position.left = o.helper ? co.left : 0; } if (cp.top < (that._helper ? co.top : 0)) { that.size.height = that.size.height + (that._helper ? (that.position.top - co.top) : that.position.top); if (pRatio) { that.size.width = that.size.height * that.aspectRatio; } that.position.top = that._helper ? co.top : 0; } that.offset.left = that.parentData.left+that.position.left; that.offset.top = that.parentData.top+that.position.top; woset = Math.abs( (that._helper ? that.offset.left - cop.left : (that.offset.left - cop.left)) + that.sizeDiff.width ); hoset = Math.abs( (that._helper ? that.offset.top - cop.top : (that.offset.top - co.top)) + that.sizeDiff.height ); isParent = that.containerElement.get(0) === that.element.parent().get(0); isOffsetRelative = /relative|absolute/.test(that.containerElement.css("position")); if(isParent && isOffsetRelative) { woset -= that.parentData.left; } if (woset + that.size.width >= that.parentData.width) { that.size.width = that.parentData.width - woset; if (pRatio) { that.size.height = that.size.width / that.aspectRatio; } } if (hoset + that.size.height >= that.parentData.height) { that.size.height = that.parentData.height - hoset; if (pRatio) { that.size.width = that.size.height * that.aspectRatio; } } }, stop: function(){ var that = $(this).data("ui-resizable"), o = that.options, co = that.containerOffset, cop = that.containerPosition, ce = that.containerElement, helper = $(that.helper), ho = helper.offset(), w = helper.outerWidth() - that.sizeDiff.width, h = helper.outerHeight() - that.sizeDiff.height; if (that._helper && !o.animate && (/relative/).test(ce.css("position"))) { $(this).css({ left: ho.left - cop.left - co.left, width: w, height: h }); } if (that._helper && !o.animate && (/static/).test(ce.css("position"))) { $(this).css({ left: ho.left - cop.left - co.left, width: w, height: h }); } } }); $.ui.plugin.add("resizable", "alsoResize", { start: function () { var that = $(this).data("ui-resizable"), o = that.options, _store = function (exp) { $(exp).each(function() { var el = $(this); el.data("ui-resizable-alsoresize", { width: parseInt(el.width(), 10), height: parseInt(el.height(), 10), left: parseInt(el.css("left"), 10), top: parseInt(el.css("top"), 10) }); }); }; if (typeof(o.alsoResize) === "object" && !o.alsoResize.parentNode) { if (o.alsoResize.length) { o.alsoResize = o.alsoResize[0]; _store(o.alsoResize); } else { $.each(o.alsoResize, function (exp) { _store(exp); }); } }else{ _store(o.alsoResize); } }, resize: function (event, ui) { var that = $(this).data("ui-resizable"), o = that.options, os = that.originalSize, op = that.originalPosition, delta = { height: (that.size.height - os.height) || 0, width: (that.size.width - os.width) || 0, top: (that.position.top - op.top) || 0, left: (that.position.left - op.left) || 0 }, _alsoResize = function (exp, c) { $(exp).each(function() { var el = $(this), start = $(this).data("ui-resizable-alsoresize"), style = {}, css = c && c.length ? c : el.parents(ui.originalElement[0]).length ? ["width", "height"] : ["width", "height", "top", "left"]; $.each(css, function (i, prop) { var sum = (start[prop]||0) + (delta[prop]||0); if (sum && sum >= 0) { style[prop] = sum || null; } }); el.css(style); }); }; if (typeof(o.alsoResize) === "object" && !o.alsoResize.nodeType) { $.each(o.alsoResize, function (exp, c) { _alsoResize(exp, c); }); }else{ _alsoResize(o.alsoResize); } }, stop: function () { $(this).removeData("resizable-alsoresize"); } }); $.ui.plugin.add("resizable", "ghost", { start: function() { var that = $(this).data("ui-resizable"), o = that.options, cs = that.size; that.ghost = that.originalElement.clone(); that.ghost .css({ opacity: 0.25, display: "block", position: "relative", height: cs.height, width: cs.width, margin: 0, left: 0, top: 0 }) .addClass("ui-resizable-ghost") .addClass(typeof o.ghost === "string" ? o.ghost : ""); that.ghost.appendTo(that.helper); }, resize: function(){ var that = $(this).data("ui-resizable"); if (that.ghost) { that.ghost.css({ position: "relative", height: that.size.height, width: that.size.width }); } }, stop: function() { var that = $(this).data("ui-resizable"); if (that.ghost && that.helper) { that.helper.get(0).removeChild(that.ghost.get(0)); } } }); $.ui.plugin.add("resizable", "grid", { resize: function() { var that = $(this).data("ui-resizable"), o = that.options, cs = that.size, os = that.originalSize, op = that.originalPosition, a = that.axis, grid = typeof o.grid === "number" ? [o.grid, o.grid] : o.grid, gridX = (grid[0]||1), gridY = (grid[1]||1), ox = Math.round((cs.width - os.width) / gridX) * gridX, oy = Math.round((cs.height - os.height) / gridY) * gridY, newWidth = os.width + ox, newHeight = os.height + oy, isMaxWidth = o.maxWidth && (o.maxWidth < newWidth), isMaxHeight = o.maxHeight && (o.maxHeight < newHeight), isMinWidth = o.minWidth && (o.minWidth > newWidth), isMinHeight = o.minHeight && (o.minHeight > newHeight); o.grid = grid; if (isMinWidth) { newWidth = newWidth + gridX; } if (isMinHeight) { newHeight = newHeight + gridY; } if (isMaxWidth) { newWidth = newWidth - gridX; } if (isMaxHeight) { newHeight = newHeight - gridY; } if (/^(se|s|e)$/.test(a)) { that.size.width = newWidth; that.size.height = newHeight; } else if (/^(ne)$/.test(a)) { that.size.width = newWidth; that.size.height = newHeight; that.position.top = op.top - oy; } else if (/^(sw)$/.test(a)) { that.size.width = newWidth; that.size.height = newHeight; that.position.left = op.left - ox; } else { that.size.width = newWidth; that.size.height = newHeight; that.position.top = op.top - oy; that.position.left = op.left - ox; } } }); })(jQuery); (function( $, undefined ) { $.widget("ui.selectable", $.ui.mouse, { version: "1.10.3", options: { appendTo: "body", autoRefresh: true, distance: 0, filter: "*", tolerance: "touch", // callbacks selected: null, selecting: null, start: null, stop: null, unselected: null, unselecting: null }, _create: function() { var selectees, that = this; this.element.addClass("ui-selectable"); this.dragged = false; // cache selectee children based on filter this.refresh = function() { selectees = $(that.options.filter, that.element[0]); selectees.addClass("ui-selectee"); selectees.each(function() { var $this = $(this), pos = $this.offset(); $.data(this, "selectable-item", { element: this, $element: $this, left: pos.left, top: pos.top, right: pos.left + $this.outerWidth(), bottom: pos.top + $this.outerHeight(), startselected: false, selected: $this.hasClass("ui-selected"), selecting: $this.hasClass("ui-selecting"), unselecting: $this.hasClass("ui-unselecting") }); }); }; this.refresh(); this.selectees = selectees.addClass("ui-selectee"); this._mouseInit(); this.helper = $("<div class='ui-selectable-helper'></div>"); }, _destroy: function() { this.selectees .removeClass("ui-selectee") .removeData("selectable-item"); this.element .removeClass("ui-selectable ui-selectable-disabled"); this._mouseDestroy(); }, _mouseStart: function(event) { var that = this, options = this.options; this.opos = [event.pageX, event.pageY]; if (this.options.disabled) { return; } this.selectees = $(options.filter, this.element[0]); this._trigger("start", event); $(options.appendTo).append(this.helper); // position helper (lasso) this.helper.css({ "left": event.pageX, "top": event.pageY, "width": 0, "height": 0 }); if (options.autoRefresh) { this.refresh(); } this.selectees.filter(".ui-selected").each(function() { var selectee = $.data(this, "selectable-item"); selectee.startselected = true; if (!event.metaKey && !event.ctrlKey) { selectee.$element.removeClass("ui-selected"); selectee.selected = false; selectee.$element.addClass("ui-unselecting"); selectee.unselecting = true; // selectable UNSELECTING callback that._trigger("unselecting", event, { unselecting: selectee.element }); } }); $(event.target).parents().addBack().each(function() { var doSelect, selectee = $.data(this, "selectable-item"); if (selectee) { doSelect = (!event.metaKey && !event.ctrlKey) || !selectee.$element.hasClass("ui-selected"); selectee.$element .removeClass(doSelect ? "ui-unselecting" : "ui-selected") .addClass(doSelect ? "ui-selecting" : "ui-unselecting"); selectee.unselecting = !doSelect; selectee.selecting = doSelect; selectee.selected = doSelect; // selectable (UN)SELECTING callback if (doSelect) { that._trigger("selecting", event, { selecting: selectee.element }); } else { that._trigger("unselecting", event, { unselecting: selectee.element }); } return false; } }); }, _mouseDrag: function(event) { this.dragged = true; if (this.options.disabled) { return; } var tmp, that = this, options = this.options, x1 = this.opos[0], y1 = this.opos[1], x2 = event.pageX, y2 = event.pageY; if (x1 > x2) { tmp = x2; x2 = x1; x1 = tmp; } if (y1 > y2) { tmp = y2; y2 = y1; y1 = tmp; } this.helper.css({left: x1, top: y1, width: x2-x1, height: y2-y1}); this.selectees.each(function() { var selectee = $.data(this, "selectable-item"), hit = false; //prevent helper from being selected if appendTo: selectable if (!selectee || selectee.element === that.element[0]) { return; } if (options.tolerance === "touch") { hit = ( !(selectee.left > x2 || selectee.right < x1 || selectee.top > y2 || selectee.bottom < y1) ); } else if (options.tolerance === "fit") { hit = (selectee.left > x1 && selectee.right < x2 && selectee.top > y1 && selectee.bottom < y2); } if (hit) { // SELECT if (selectee.selected) { selectee.$element.removeClass("ui-selected"); selectee.selected = false; } if (selectee.unselecting) { selectee.$element.removeClass("ui-unselecting"); selectee.unselecting = false; } if (!selectee.selecting) { selectee.$element.addClass("ui-selecting"); selectee.selecting = true; // selectable SELECTING callback that._trigger("selecting", event, { selecting: selectee.element }); } } else { // UNSELECT if (selectee.selecting) { if ((event.metaKey || event.ctrlKey) && selectee.startselected) { selectee.$element.removeClass("ui-selecting"); selectee.selecting = false; selectee.$element.addClass("ui-selected"); selectee.selected = true; } else { selectee.$element.removeClass("ui-selecting"); selectee.selecting = false; if (selectee.startselected) { selectee.$element.addClass("ui-unselecting"); selectee.unselecting = true; } // selectable UNSELECTING callback that._trigger("unselecting", event, { unselecting: selectee.element }); } } if (selectee.selected) { if (!event.metaKey && !event.ctrlKey && !selectee.startselected) { selectee.$element.removeClass("ui-selected"); selectee.selected = false; selectee.$element.addClass("ui-unselecting"); selectee.unselecting = true; // selectable UNSELECTING callback that._trigger("unselecting", event, { unselecting: selectee.element }); } } } }); return false; }, _mouseStop: function(event) { var that = this; this.dragged = false; $(".ui-unselecting", this.element[0]).each(function() { var selectee = $.data(this, "selectable-item"); selectee.$element.removeClass("ui-unselecting"); selectee.unselecting = false; selectee.startselected = false; that._trigger("unselected", event, { unselected: selectee.element }); }); $(".ui-selecting", this.element[0]).each(function() { var selectee = $.data(this, "selectable-item"); selectee.$element.removeClass("ui-selecting").addClass("ui-selected"); selectee.selecting = false; selectee.selected = true; selectee.startselected = true; that._trigger("selected", event, { selected: selectee.element }); }); this._trigger("stop", event); this.helper.remove(); return false; } }); })(jQuery); (function( $, undefined ) { /*jshint loopfunc: true */ function isOverAxis( x, reference, size ) { return ( x > reference ) && ( x < ( reference + size ) ); } function isFloating(item) { return (/left|right/).test(item.css("float")) || (/inline|table-cell/).test(item.css("display")); } $.widget("ui.sortable", $.ui.mouse, { version: "1.10.3", widgetEventPrefix: "sort", ready: false, options: { appendTo: "parent", axis: false, connectWith: false, containment: false, cursor: "auto", cursorAt: false, dropOnEmpty: true, forcePlaceholderSize: false, forceHelperSize: false, grid: false, handle: false, helper: "original", items: "> *", opacity: false, placeholder: false, revert: false, scroll: true, scrollSensitivity: 20, scrollSpeed: 20, scope: "default", tolerance: "intersect", zIndex: 1000, // callbacks activate: null, beforeStop: null, change: null, deactivate: null, out: null, over: null, receive: null, remove: null, sort: null, start: null, stop: null, update: null }, _create: function() { var o = this.options; this.containerCache = {}; this.element.addClass("ui-sortable"); //Get the items this.refresh(); //Let's determine if the items are being displayed horizontally this.floating = this.items.length ? o.axis === "x" || isFloating(this.items[0].item) : false; //Let's determine the parent's offset this.offset = this.element.offset(); //Initialize mouse events for interaction this._mouseInit(); //We're ready to go this.ready = true; }, _destroy: function() { this.element .removeClass("ui-sortable ui-sortable-disabled"); this._mouseDestroy(); for ( var i = this.items.length - 1; i >= 0; i-- ) { this.items[i].item.removeData(this.widgetName + "-item"); } return this; }, _setOption: function(key, value){ if ( key === "disabled" ) { this.options[ key ] = value; this.widget().toggleClass( "ui-sortable-disabled", !!value ); } else { // Don't call widget base _setOption for disable as it adds ui-state-disabled class $.Widget.prototype._setOption.apply(this, arguments); } }, _mouseCapture: function(event, overrideHandle) { var currentItem = null, validHandle = false, that = this; if (this.reverting) { return false; } if(this.options.disabled || this.options.type === "static") { return false; } //We have to refresh the items data once first this._refreshItems(event); //Find out if the clicked node (or one of its parents) is a actual item in this.items $(event.target).parents().each(function() { if($.data(this, that.widgetName + "-item") === that) { currentItem = $(this); return false; } }); if($.data(event.target, that.widgetName + "-item") === that) { currentItem = $(event.target); } if(!currentItem) { return false; } if(this.options.handle && !overrideHandle) { $(this.options.handle, currentItem).find("*").addBack().each(function() { if(this === event.target) { validHandle = true; } }); if(!validHandle) { return false; } } this.currentItem = currentItem; this._removeCurrentsFromItems(); return true; }, _mouseStart: function(event, overrideHandle, noActivation) { var i, body, o = this.options; this.currentContainer = this; //We only need to call refreshPositions, because the refreshItems call has been moved to mouseCapture this.refreshPositions(); //Create and append the visible helper this.helper = this._createHelper(event); //Cache the helper size this._cacheHelperProportions(); /* * - Position generation - * This block generates everything position related - it's the core of draggables. */ //Cache the margins of the original element this._cacheMargins(); //Get the next scrolling parent this.scrollParent = this.helper.scrollParent(); //The element's absolute position on the page minus margins this.offset = this.currentItem.offset(); this.offset = { top: this.offset.top - this.margins.top, left: this.offset.left - this.margins.left }; $.extend(this.offset, { click: { //Where the click happened, relative to the element left: event.pageX - this.offset.left, top: event.pageY - this.offset.top }, parent: this._getParentOffset(), relative: this._getRelativeOffset() //This is a relative to absolute position minus the actual position calculation - only used for relative positioned helper }); // Only after we got the offset, we can change the helper's position to absolute // TODO: Still need to figure out a way to make relative sorting possible this.helper.css("position", "absolute"); this.cssPosition = this.helper.css("position"); //Generate the original position this.originalPosition = this._generatePosition(event); this.originalPageX = event.pageX; this.originalPageY = event.pageY; //Adjust the mouse offset relative to the helper if "cursorAt" is supplied (o.cursorAt && this._adjustOffsetFromHelper(o.cursorAt)); //Cache the former DOM position this.domPosition = { prev: this.currentItem.prev()[0], parent: this.currentItem.parent()[0] }; //If the helper is not the original, hide the original so it's not playing any role during the drag, won't cause anything bad this way if(this.helper[0] !== this.currentItem[0]) { this.currentItem.hide(); } //Create the placeholder this._createPlaceholder(); //Set a containment if given in the options if(o.containment) { this._setContainment(); } if( o.cursor && o.cursor !== "auto" ) { // cursor option body = this.document.find( "body" ); // support: IE this.storedCursor = body.css( "cursor" ); body.css( "cursor", o.cursor ); this.storedStylesheet = $( "<style>*{ cursor: "+o.cursor+" !important; }</style>" ).appendTo( body ); } if(o.opacity) { // opacity option if (this.helper.css("opacity")) { this._storedOpacity = this.helper.css("opacity"); } this.helper.css("opacity", o.opacity); } if(o.zIndex) { // zIndex option if (this.helper.css("zIndex")) { this._storedZIndex = this.helper.css("zIndex"); } this.helper.css("zIndex", o.zIndex); } //Prepare scrolling if(this.scrollParent[0] !== document && this.scrollParent[0].tagName !== "HTML") { this.overflowOffset = this.scrollParent.offset(); } //Call callbacks this._trigger("start", event, this._uiHash()); //Recache the helper size if(!this._preserveHelperProportions) { this._cacheHelperProportions(); } //Post "activate" events to possible containers if( !noActivation ) { for ( i = this.containers.length - 1; i >= 0; i-- ) { this.containers[ i ]._trigger( "activate", event, this._uiHash( this ) ); } } //Prepare possible droppables if($.ui.ddmanager) { $.ui.ddmanager.current = this; } if ($.ui.ddmanager && !o.dropBehaviour) { $.ui.ddmanager.prepareOffsets(this, event); } this.dragging = true; this.helper.addClass("ui-sortable-helper"); this._mouseDrag(event); //Execute the drag once - this causes the helper not to be visible before getting its correct position return true; }, _mouseDrag: function(event) { var i, item, itemElement, intersection, o = this.options, scrolled = false; //Compute the helpers position this.position = this._generatePosition(event); this.positionAbs = this._convertPositionTo("absolute"); if (!this.lastPositionAbs) { this.lastPositionAbs = this.positionAbs; } //Do scrolling if(this.options.scroll) { if(this.scrollParent[0] !== document && this.scrollParent[0].tagName !== "HTML") { if((this.overflowOffset.top + this.scrollParent[0].offsetHeight) - event.pageY < o.scrollSensitivity) { this.scrollParent[0].scrollTop = scrolled = this.scrollParent[0].scrollTop + o.scrollSpeed; } else if(event.pageY - this.overflowOffset.top < o.scrollSensitivity) { this.scrollParent[0].scrollTop = scrolled = this.scrollParent[0].scrollTop - o.scrollSpeed; } if((this.overflowOffset.left + this.scrollParent[0].offsetWidth) - event.pageX < o.scrollSensitivity) { this.scrollParent[0].scrollLeft = scrolled = this.scrollParent[0].scrollLeft + o.scrollSpeed; } else if(event.pageX - this.overflowOffset.left < o.scrollSensitivity) { this.scrollParent[0].scrollLeft = scrolled = this.scrollParent[0].scrollLeft - o.scrollSpeed; } } else { if(event.pageY - $(document).scrollTop() < o.scrollSensitivity) { scrolled = $(document).scrollTop($(document).scrollTop() - o.scrollSpeed); } else if($(window).height() - (event.pageY - $(document).scrollTop()) < o.scrollSensitivity) { scrolled = $(document).scrollTop($(document).scrollTop() + o.scrollSpeed); } if(event.pageX - $(document).scrollLeft() < o.scrollSensitivity) { scrolled = $(document).scrollLeft($(document).scrollLeft() - o.scrollSpeed); } else if($(window).width() - (event.pageX - $(document).scrollLeft()) < o.scrollSensitivity) { scrolled = $(document).scrollLeft($(document).scrollLeft() + o.scrollSpeed); } } if(scrolled !== false && $.ui.ddmanager && !o.dropBehaviour) { $.ui.ddmanager.prepareOffsets(this, event); } } //Regenerate the absolute position used for position checks this.positionAbs = this._convertPositionTo("absolute"); //Set the helper position if(!this.options.axis || this.options.axis !== "y") { this.helper[0].style.left = this.position.left+"px"; } if(!this.options.axis || this.options.axis !== "x") { this.helper[0].style.top = this.position.top+"px"; } //Rearrange for (i = this.items.length - 1; i >= 0; i--) { //Cache variables and intersection, continue if no intersection item = this.items[i]; itemElement = item.item[0]; intersection = this._intersectsWithPointer(item); if (!intersection) { continue; } // Only put the placeholder inside the current Container, skip all // items form other containers. This works because when moving // an item from one container to another the // currentContainer is switched before the placeholder is moved. // // Without this moving items in "sub-sortables" can cause the placeholder to jitter // beetween the outer and inner container. if (item.instance !== this.currentContainer) { continue; } // cannot intersect with itself // no useless actions that have been done before // no action if the item moved is the parent of the item checked if (itemElement !== this.currentItem[0] && this.placeholder[intersection === 1 ? "next" : "prev"]()[0] !== itemElement && !$.contains(this.placeholder[0], itemElement) && (this.options.type === "semi-dynamic" ? !$.contains(this.element[0], itemElement) : true) ) { this.direction = intersection === 1 ? "down" : "up"; if (this.options.tolerance === "pointer" || this._intersectsWithSides(item)) { this._rearrange(event, item); } else { break; } this._trigger("change", event, this._uiHash()); break; } } //Post events to containers this._contactContainers(event); //Interconnect with droppables if($.ui.ddmanager) { $.ui.ddmanager.drag(this, event); } //Call callbacks this._trigger("sort", event, this._uiHash()); this.lastPositionAbs = this.positionAbs; return false; }, _mouseStop: function(event, noPropagation) { if(!event) { return; } //If we are using droppables, inform the manager about the drop if ($.ui.ddmanager && !this.options.dropBehaviour) { $.ui.ddmanager.drop(this, event); } if(this.options.revert) { var that = this, cur = this.placeholder.offset(), axis = this.options.axis, animation = {}; if ( !axis || axis === "x" ) { animation.left = cur.left - this.offset.parent.left - this.margins.left + (this.offsetParent[0] === document.body ? 0 : this.offsetParent[0].scrollLeft); } if ( !axis || axis === "y" ) { animation.top = cur.top - this.offset.parent.top - this.margins.top + (this.offsetParent[0] === document.body ? 0 : this.offsetParent[0].scrollTop); } this.reverting = true; $(this.helper).animate( animation, parseInt(this.options.revert, 10) || 500, function() { that._clear(event); }); } else { this._clear(event, noPropagation); } return false; }, cancel: function() { if(this.dragging) { this._mouseUp({ target: null }); if(this.options.helper === "original") { this.currentItem.css(this._storedCSS).removeClass("ui-sortable-helper"); } else { this.currentItem.show(); } //Post deactivating events to containers for (var i = this.containers.length - 1; i >= 0; i--){ this.containers[i]._trigger("deactivate", null, this._uiHash(this)); if(this.containers[i].containerCache.over) { this.containers[i]._trigger("out", null, this._uiHash(this)); this.containers[i].containerCache.over = 0; } } } if (this.placeholder) { //$(this.placeholder[0]).remove(); would have been the jQuery way - unfortunately, it unbinds ALL events from the original node! if(this.placeholder[0].parentNode) { this.placeholder[0].parentNode.removeChild(this.placeholder[0]); } if(this.options.helper !== "original" && this.helper && this.helper[0].parentNode) { this.helper.remove(); } $.extend(this, { helper: null, dragging: false, reverting: false, _noFinalSort: null }); if(this.domPosition.prev) { $(this.domPosition.prev).after(this.currentItem); } else { $(this.domPosition.parent).prepend(this.currentItem); } } return this; }, serialize: function(o) { var items = this._getItemsAsjQuery(o && o.connected), str = []; o = o || {}; $(items).each(function() { var res = ($(o.item || this).attr(o.attribute || "id") || "").match(o.expression || (/(.+)[\-=_](.+)/)); if (res) { str.push((o.key || res[1]+"[]")+"="+(o.key && o.expression ? res[1] : res[2])); } }); if(!str.length && o.key) { str.push(o.key + "="); } return str.join("&"); }, toArray: function(o) { var items = this._getItemsAsjQuery(o && o.connected), ret = []; o = o || {}; items.each(function() { ret.push($(o.item || this).attr(o.attribute || "id") || ""); }); return ret; }, /* Be careful with the following core functions */ _intersectsWith: function(item) { var x1 = this.positionAbs.left, x2 = x1 + this.helperProportions.width, y1 = this.positionAbs.top, y2 = y1 + this.helperProportions.height, l = item.left, r = l + item.width, t = item.top, b = t + item.height, dyClick = this.offset.click.top, dxClick = this.offset.click.left, isOverElementHeight = ( this.options.axis === "x" ) || ( ( y1 + dyClick ) > t && ( y1 + dyClick ) < b ), isOverElementWidth = ( this.options.axis === "y" ) || ( ( x1 + dxClick ) > l && ( x1 + dxClick ) < r ), isOverElement = isOverElementHeight && isOverElementWidth; if ( this.options.tolerance === "pointer" || this.options.forcePointerForContainers || (this.options.tolerance !== "pointer" && this.helperProportions[this.floating ? "width" : "height"] > item[this.floating ? "width" : "height"]) ) { return isOverElement; } else { return (l < x1 + (this.helperProportions.width / 2) && // Right Half x2 - (this.helperProportions.width / 2) < r && // Left Half t < y1 + (this.helperProportions.height / 2) && // Bottom Half y2 - (this.helperProportions.height / 2) < b ); // Top Half } }, _intersectsWithPointer: function(item) { var isOverElementHeight = (this.options.axis === "x") || isOverAxis(this.positionAbs.top + this.offset.click.top, item.top, item.height), isOverElementWidth = (this.options.axis === "y") || isOverAxis(this.positionAbs.left + this.offset.click.left, item.left, item.width), isOverElement = isOverElementHeight && isOverElementWidth, verticalDirection = this._getDragVerticalDirection(), horizontalDirection = this._getDragHorizontalDirection(); if (!isOverElement) { return false; } return this.floating ? ( ((horizontalDirection && horizontalDirection === "right") || verticalDirection === "down") ? 2 : 1 ) : ( verticalDirection && (verticalDirection === "down" ? 2 : 1) ); }, _intersectsWithSides: function(item) { var isOverBottomHalf = isOverAxis(this.positionAbs.top + this.offset.click.top, item.top + (item.height/2), item.height), isOverRightHalf = isOverAxis(this.positionAbs.left + this.offset.click.left, item.left + (item.width/2), item.width), verticalDirection = this._getDragVerticalDirection(), horizontalDirection = this._getDragHorizontalDirection(); if (this.floating && horizontalDirection) { return ((horizontalDirection === "right" && isOverRightHalf) || (horizontalDirection === "left" && !isOverRightHalf)); } else { return verticalDirection && ((verticalDirection === "down" && isOverBottomHalf) || (verticalDirection === "up" && !isOverBottomHalf)); } }, _getDragVerticalDirection: function() { var delta = this.positionAbs.top - this.lastPositionAbs.top; return delta !== 0 && (delta > 0 ? "down" : "up"); }, _getDragHorizontalDirection: function() { var delta = this.positionAbs.left - this.lastPositionAbs.left; return delta !== 0 && (delta > 0 ? "right" : "left"); }, refresh: function(event) { this._refreshItems(event); this.refreshPositions(); return this; }, _connectWith: function() { var options = this.options; return options.connectWith.constructor === String ? [options.connectWith] : options.connectWith; }, _getItemsAsjQuery: function(connected) { var i, j, cur, inst, items = [], queries = [], connectWith = this._connectWith(); if(connectWith && connected) { for (i = connectWith.length - 1; i >= 0; i--){ cur = $(connectWith[i]); for ( j = cur.length - 1; j >= 0; j--){ inst = $.data(cur[j], this.widgetFullName); if(inst && inst !== this && !inst.options.disabled) { queries.push([$.isFunction(inst.options.items) ? inst.options.items.call(inst.element) : $(inst.options.items, inst.element).not(".ui-sortable-helper").not(".ui-sortable-placeholder"), inst]); } } } } queries.push([$.isFunction(this.options.items) ? this.options.items.call(this.element, null, { options: this.options, item: this.currentItem }) : $(this.options.items, this.element).not(".ui-sortable-helper").not(".ui-sortable-placeholder"), this]); for (i = queries.length - 1; i >= 0; i--){ queries[i][0].each(function() { items.push(this); }); } return $(items); }, _removeCurrentsFromItems: function() { var list = this.currentItem.find(":data(" + this.widgetName + "-item)"); this.items = $.grep(this.items, function (item) { for (var j=0; j < list.length; j++) { if(list[j] === item.item[0]) { return false; } } return true; }); }, _refreshItems: function(event) { this.items = []; this.containers = [this]; var i, j, cur, inst, targetData, _queries, item, queriesLength, items = this.items, queries = [[$.isFunction(this.options.items) ? this.options.items.call(this.element[0], event, { item: this.currentItem }) : $(this.options.items, this.element), this]], connectWith = this._connectWith(); if(connectWith && this.ready) { //Shouldn't be run the first time through due to massive slow-down for (i = connectWith.length - 1; i >= 0; i--){ cur = $(connectWith[i]); for (j = cur.length - 1; j >= 0; j--){ inst = $.data(cur[j], this.widgetFullName); if(inst && inst !== this && !inst.options.disabled) { queries.push([$.isFunction(inst.options.items) ? inst.options.items.call(inst.element[0], event, { item: this.currentItem }) : $(inst.options.items, inst.element), inst]); this.containers.push(inst); } } } } for (i = queries.length - 1; i >= 0; i--) { targetData = queries[i][1]; _queries = queries[i][0]; for (j=0, queriesLength = _queries.length; j < queriesLength; j++) { item = $(_queries[j]); item.data(this.widgetName + "-item", targetData); // Data for target checking (mouse manager) items.push({ item: item, instance: targetData, width: 0, height: 0, left: 0, top: 0 }); } } }, refreshPositions: function(fast) { //This has to be redone because due to the item being moved out/into the offsetParent, the offsetParent's position will change if(this.offsetParent && this.helper) { this.offset.parent = this._getParentOffset(); } var i, item, t, p; for (i = this.items.length - 1; i >= 0; i--){ item = this.items[i]; //We ignore calculating positions of all connected containers when we're not over them if(item.instance !== this.currentContainer && this.currentContainer && item.item[0] !== this.currentItem[0]) { continue; } t = this.options.toleranceElement ? $(this.options.toleranceElement, item.item) : item.item; if (!fast) { item.width = t.outerWidth(); item.height = t.outerHeight(); } p = t.offset(); item.left = p.left; item.top = p.top; } if(this.options.custom && this.options.custom.refreshContainers) { this.options.custom.refreshContainers.call(this); } else { for (i = this.containers.length - 1; i >= 0; i--){ p = this.containers[i].element.offset(); this.containers[i].containerCache.left = p.left; this.containers[i].containerCache.top = p.top; this.containers[i].containerCache.width = this.containers[i].element.outerWidth(); this.containers[i].containerCache.height = this.containers[i].element.outerHeight(); } } return this; }, _createPlaceholder: function(that) { that = that || this; var className, o = that.options; if(!o.placeholder || o.placeholder.constructor === String) { className = o.placeholder; o.placeholder = { element: function() { var nodeName = that.currentItem[0].nodeName.toLowerCase(), element = $( "<" + nodeName + ">", that.document[0] ) .addClass(className || that.currentItem[0].className+" ui-sortable-placeholder") .removeClass("ui-sortable-helper"); if ( nodeName === "tr" ) { that.currentItem.children().each(function() { $( "<td>&#160;</td>", that.document[0] ) .attr( "colspan", $( this ).attr( "colspan" ) || 1 ) .appendTo( element ); }); } else if ( nodeName === "img" ) { element.attr( "src", that.currentItem.attr( "src" ) ); } if ( !className ) { element.css( "visibility", "hidden" ); } return element; }, update: function(container, p) { // 1. If a className is set as 'placeholder option, we don't force sizes - the class is responsible for that // 2. The option 'forcePlaceholderSize can be enabled to force it even if a class name is specified if(className && !o.forcePlaceholderSize) { return; } //If the element doesn't have a actual height by itself (without styles coming from a stylesheet), it receives the inline height from the dragged item if(!p.height()) { p.height(that.currentItem.innerHeight() - parseInt(that.currentItem.css("paddingTop")||0, 10) - parseInt(that.currentItem.css("paddingBottom")||0, 10)); } if(!p.width()) { p.width(that.currentItem.innerWidth() - parseInt(that.currentItem.css("paddingLeft")||0, 10) - parseInt(that.currentItem.css("paddingRight")||0, 10)); } } }; } //Create the placeholder that.placeholder = $(o.placeholder.element.call(that.element, that.currentItem)); //Append it after the actual current item that.currentItem.after(that.placeholder); //Update the size of the placeholder (TODO: Logic to fuzzy, see line 316/317) o.placeholder.update(that, that.placeholder); }, _contactContainers: function(event) { var i, j, dist, itemWithLeastDistance, posProperty, sizeProperty, base, cur, nearBottom, floating, innermostContainer = null, innermostIndex = null; // get innermost container that intersects with item for (i = this.containers.length - 1; i >= 0; i--) { // never consider a container that's located within the item itself if($.contains(this.currentItem[0], this.containers[i].element[0])) { continue; } if(this._intersectsWith(this.containers[i].containerCache)) { // if we've already found a container and it's more "inner" than this, then continue if(innermostContainer && $.contains(this.containers[i].element[0], innermostContainer.element[0])) { continue; } innermostContainer = this.containers[i]; innermostIndex = i; } else { // container doesn't intersect. trigger "out" event if necessary if(this.containers[i].containerCache.over) { this.containers[i]._trigger("out", event, this._uiHash(this)); this.containers[i].containerCache.over = 0; } } } // if no intersecting containers found, return if(!innermostContainer) { return; } // move the item into the container if it's not there already if(this.containers.length === 1) { if (!this.containers[innermostIndex].containerCache.over) { this.containers[innermostIndex]._trigger("over", event, this._uiHash(this)); this.containers[innermostIndex].containerCache.over = 1; } } else { //When entering a new container, we will find the item with the least distance and append our item near it dist = 10000; itemWithLeastDistance = null; floating = innermostContainer.floating || isFloating(this.currentItem); posProperty = floating ? "left" : "top"; sizeProperty = floating ? "width" : "height"; base = this.positionAbs[posProperty] + this.offset.click[posProperty]; for (j = this.items.length - 1; j >= 0; j--) { if(!$.contains(this.containers[innermostIndex].element[0], this.items[j].item[0])) { continue; } if(this.items[j].item[0] === this.currentItem[0]) { continue; } if (floating && !isOverAxis(this.positionAbs.top + this.offset.click.top, this.items[j].top, this.items[j].height)) { continue; } cur = this.items[j].item.offset()[posProperty]; nearBottom = false; if(Math.abs(cur - base) > Math.abs(cur + this.items[j][sizeProperty] - base)){ nearBottom = true; cur += this.items[j][sizeProperty]; } if(Math.abs(cur - base) < dist) { dist = Math.abs(cur - base); itemWithLeastDistance = this.items[j]; this.direction = nearBottom ? "up": "down"; } } //Check if dropOnEmpty is enabled if(!itemWithLeastDistance && !this.options.dropOnEmpty) { return; } if(this.currentContainer === this.containers[innermostIndex]) { return; } itemWithLeastDistance ? this._rearrange(event, itemWithLeastDistance, null, true) : this._rearrange(event, null, this.containers[innermostIndex].element, true); this._trigger("change", event, this._uiHash()); this.containers[innermostIndex]._trigger("change", event, this._uiHash(this)); this.currentContainer = this.containers[innermostIndex]; //Update the placeholder this.options.placeholder.update(this.currentContainer, this.placeholder); this.containers[innermostIndex]._trigger("over", event, this._uiHash(this)); this.containers[innermostIndex].containerCache.over = 1; } }, _createHelper: function(event) { var o = this.options, helper = $.isFunction(o.helper) ? $(o.helper.apply(this.element[0], [event, this.currentItem])) : (o.helper === "clone" ? this.currentItem.clone() : this.currentItem); //Add the helper to the DOM if that didn't happen already if(!helper.parents("body").length) { $(o.appendTo !== "parent" ? o.appendTo : this.currentItem[0].parentNode)[0].appendChild(helper[0]); } if(helper[0] === this.currentItem[0]) { this._storedCSS = { width: this.currentItem[0].style.width, height: this.currentItem[0].style.height, position: this.currentItem.css("position"), top: this.currentItem.css("top"), left: this.currentItem.css("left") }; } if(!helper[0].style.width || o.forceHelperSize) { helper.width(this.currentItem.width()); } if(!helper[0].style.height || o.forceHelperSize) { helper.height(this.currentItem.height()); } return helper; }, _adjustOffsetFromHelper: function(obj) { if (typeof obj === "string") { obj = obj.split(" "); } if ($.isArray(obj)) { obj = {left: +obj[0], top: +obj[1] || 0}; } if ("left" in obj) { this.offset.click.left = obj.left + this.margins.left; } if ("right" in obj) { this.offset.click.left = this.helperProportions.width - obj.right + this.margins.left; } if ("top" in obj) { this.offset.click.top = obj.top + this.margins.top; } if ("bottom" in obj) { this.offset.click.top = this.helperProportions.height - obj.bottom + this.margins.top; } }, _getParentOffset: function() { //Get the offsetParent and cache its position this.offsetParent = this.helper.offsetParent(); var po = this.offsetParent.offset(); // This is a special case where we need to modify a offset calculated on start, since the following happened: // 1. The position of the helper is absolute, so it's position is calculated based on the next positioned parent // 2. The actual offset parent is a child of the scroll parent, and the scroll parent isn't the document, which means that // the scroll is included in the initial calculation of the offset of the parent, and never recalculated upon drag if(this.cssPosition === "absolute" && this.scrollParent[0] !== document && $.contains(this.scrollParent[0], this.offsetParent[0])) { po.left += this.scrollParent.scrollLeft(); po.top += this.scrollParent.scrollTop(); } // This needs to be actually done for all browsers, since pageX/pageY includes this information // with an ugly IE fix if( this.offsetParent[0] === document.body || (this.offsetParent[0].tagName && this.offsetParent[0].tagName.toLowerCase() === "html" && $.ui.ie)) { po = { top: 0, left: 0 }; } return { top: po.top + (parseInt(this.offsetParent.css("borderTopWidth"),10) || 0), left: po.left + (parseInt(this.offsetParent.css("borderLeftWidth"),10) || 0) }; }, _getRelativeOffset: function() { if(this.cssPosition === "relative") { var p = this.currentItem.position(); return { top: p.top - (parseInt(this.helper.css("top"),10) || 0) + this.scrollParent.scrollTop(), left: p.left - (parseInt(this.helper.css("left"),10) || 0) + this.scrollParent.scrollLeft() }; } else { return { top: 0, left: 0 }; } }, _cacheMargins: function() { this.margins = { left: (parseInt(this.currentItem.css("marginLeft"),10) || 0), top: (parseInt(this.currentItem.css("marginTop"),10) || 0) }; }, _cacheHelperProportions: function() { this.helperProportions = { width: this.helper.outerWidth(), height: this.helper.outerHeight() }; }, _setContainment: function() { var ce, co, over, o = this.options; if(o.containment === "parent") { o.containment = this.helper[0].parentNode; } if(o.containment === "document" || o.containment === "window") { this.containment = [ 0 - this.offset.relative.left - this.offset.parent.left, 0 - this.offset.relative.top - this.offset.parent.top, $(o.containment === "document" ? document : window).width() - this.helperProportions.width - this.margins.left, ($(o.containment === "document" ? document : window).height() || document.body.parentNode.scrollHeight) - this.helperProportions.height - this.margins.top ]; } if(!(/^(document|window|parent)$/).test(o.containment)) { ce = $(o.containment)[0]; co = $(o.containment).offset(); over = ($(ce).css("overflow") !== "hidden"); this.containment = [ co.left + (parseInt($(ce).css("borderLeftWidth"),10) || 0) + (parseInt($(ce).css("paddingLeft"),10) || 0) - this.margins.left, co.top + (parseInt($(ce).css("borderTopWidth"),10) || 0) + (parseInt($(ce).css("paddingTop"),10) || 0) - this.margins.top, co.left+(over ? Math.max(ce.scrollWidth,ce.offsetWidth) : ce.offsetWidth) - (parseInt($(ce).css("borderLeftWidth"),10) || 0) - (parseInt($(ce).css("paddingRight"),10) || 0) - this.helperProportions.width - this.margins.left, co.top+(over ? Math.max(ce.scrollHeight,ce.offsetHeight) : ce.offsetHeight) - (parseInt($(ce).css("borderTopWidth"),10) || 0) - (parseInt($(ce).css("paddingBottom"),10) || 0) - this.helperProportions.height - this.margins.top ]; } }, _convertPositionTo: function(d, pos) { if(!pos) { pos = this.position; } var mod = d === "absolute" ? 1 : -1, scroll = this.cssPosition === "absolute" && !(this.scrollParent[0] !== document && $.contains(this.scrollParent[0], this.offsetParent[0])) ? this.offsetParent : this.scrollParent, scrollIsRootNode = (/(html|body)/i).test(scroll[0].tagName); return { top: ( pos.top + // The absolute mouse position this.offset.relative.top * mod + // Only for relative positioned nodes: Relative offset from element to offset parent this.offset.parent.top * mod - // The offsetParent's offset without borders (offset + border) ( ( this.cssPosition === "fixed" ? -this.scrollParent.scrollTop() : ( scrollIsRootNode ? 0 : scroll.scrollTop() ) ) * mod) ), left: ( pos.left + // The absolute mouse position this.offset.relative.left * mod + // Only for relative positioned nodes: Relative offset from element to offset parent this.offset.parent.left * mod - // The offsetParent's offset without borders (offset + border) ( ( this.cssPosition === "fixed" ? -this.scrollParent.scrollLeft() : scrollIsRootNode ? 0 : scroll.scrollLeft() ) * mod) ) }; }, _generatePosition: function(event) { var top, left, o = this.options, pageX = event.pageX, pageY = event.pageY, scroll = this.cssPosition === "absolute" && !(this.scrollParent[0] !== document && $.contains(this.scrollParent[0], this.offsetParent[0])) ? this.offsetParent : this.scrollParent, scrollIsRootNode = (/(html|body)/i).test(scroll[0].tagName); // This is another very weird special case that only happens for relative elements: // 1. If the css position is relative // 2. and the scroll parent is the document or similar to the offset parent // we have to refresh the relative offset during the scroll so there are no jumps if(this.cssPosition === "relative" && !(this.scrollParent[0] !== document && this.scrollParent[0] !== this.offsetParent[0])) { this.offset.relative = this._getRelativeOffset(); } /* * - Position constraining - * Constrain the position to a mix of grid, containment. */ if(this.originalPosition) { //If we are not dragging yet, we won't check for options if(this.containment) { if(event.pageX - this.offset.click.left < this.containment[0]) { pageX = this.containment[0] + this.offset.click.left; } if(event.pageY - this.offset.click.top < this.containment[1]) { pageY = this.containment[1] + this.offset.click.top; } if(event.pageX - this.offset.click.left > this.containment[2]) { pageX = this.containment[2] + this.offset.click.left; } if(event.pageY - this.offset.click.top > this.containment[3]) { pageY = this.containment[3] + this.offset.click.top; } } if(o.grid) { top = this.originalPageY + Math.round((pageY - this.originalPageY) / o.grid[1]) * o.grid[1]; pageY = this.containment ? ( (top - this.offset.click.top >= this.containment[1] && top - this.offset.click.top <= this.containment[3]) ? top : ((top - this.offset.click.top >= this.containment[1]) ? top - o.grid[1] : top + o.grid[1])) : top; left = this.originalPageX + Math.round((pageX - this.originalPageX) / o.grid[0]) * o.grid[0]; pageX = this.containment ? ( (left - this.offset.click.left >= this.containment[0] && left - this.offset.click.left <= this.containment[2]) ? left : ((left - this.offset.click.left >= this.containment[0]) ? left - o.grid[0] : left + o.grid[0])) : left; } } return { top: ( pageY - // The absolute mouse position this.offset.click.top - // Click offset (relative to the element) this.offset.relative.top - // Only for relative positioned nodes: Relative offset from element to offset parent this.offset.parent.top + // The offsetParent's offset without borders (offset + border) ( ( this.cssPosition === "fixed" ? -this.scrollParent.scrollTop() : ( scrollIsRootNode ? 0 : scroll.scrollTop() ) )) ), left: ( pageX - // The absolute mouse position this.offset.click.left - // Click offset (relative to the element) this.offset.relative.left - // Only for relative positioned nodes: Relative offset from element to offset parent this.offset.parent.left + // The offsetParent's offset without borders (offset + border) ( ( this.cssPosition === "fixed" ? -this.scrollParent.scrollLeft() : scrollIsRootNode ? 0 : scroll.scrollLeft() )) ) }; }, _rearrange: function(event, i, a, hardRefresh) { a ? a[0].appendChild(this.placeholder[0]) : i.item[0].parentNode.insertBefore(this.placeholder[0], (this.direction === "down" ? i.item[0] : i.item[0].nextSibling)); //Various things done here to improve the performance: // 1. we create a setTimeout, that calls refreshPositions // 2. on the instance, we have a counter variable, that get's higher after every append // 3. on the local scope, we copy the counter variable, and check in the timeout, if it's still the same // 4. this lets only the last addition to the timeout stack through this.counter = this.counter ? ++this.counter : 1; var counter = this.counter; this._delay(function() { if(counter === this.counter) { this.refreshPositions(!hardRefresh); //Precompute after each DOM insertion, NOT on mousemove } }); }, _clear: function(event, noPropagation) { this.reverting = false; // We delay all events that have to be triggered to after the point where the placeholder has been removed and // everything else normalized again var i, delayedTriggers = []; // We first have to update the dom position of the actual currentItem // Note: don't do it if the current item is already removed (by a user), or it gets reappended (see #4088) if(!this._noFinalSort && this.currentItem.parent().length) { this.placeholder.before(this.currentItem); } this._noFinalSort = null; if(this.helper[0] === this.currentItem[0]) { for(i in this._storedCSS) { if(this._storedCSS[i] === "auto" || this._storedCSS[i] === "static") { this._storedCSS[i] = ""; } } this.currentItem.css(this._storedCSS).removeClass("ui-sortable-helper"); } else { this.currentItem.show(); } if(this.fromOutside && !noPropagation) { delayedTriggers.push(function(event) { this._trigger("receive", event, this._uiHash(this.fromOutside)); }); } if((this.fromOutside || this.domPosition.prev !== this.currentItem.prev().not(".ui-sortable-helper")[0] || this.domPosition.parent !== this.currentItem.parent()[0]) && !noPropagation) { delayedTriggers.push(function(event) { this._trigger("update", event, this._uiHash()); }); //Trigger update callback if the DOM position has changed } // Check if the items Container has Changed and trigger appropriate // events. if (this !== this.currentContainer) { if(!noPropagation) { delayedTriggers.push(function(event) { this._trigger("remove", event, this._uiHash()); }); delayedTriggers.push((function(c) { return function(event) { c._trigger("receive", event, this._uiHash(this)); }; }).call(this, this.currentContainer)); delayedTriggers.push((function(c) { return function(event) { c._trigger("update", event, this._uiHash(this)); }; }).call(this, this.currentContainer)); } } //Post events to containers for (i = this.containers.length - 1; i >= 0; i--){ if(!noPropagation) { delayedTriggers.push((function(c) { return function(event) { c._trigger("deactivate", event, this._uiHash(this)); }; }).call(this, this.containers[i])); } if(this.containers[i].containerCache.over) { delayedTriggers.push((function(c) { return function(event) { c._trigger("out", event, this._uiHash(this)); }; }).call(this, this.containers[i])); this.containers[i].containerCache.over = 0; } } //Do what was originally in plugins if ( this.storedCursor ) { this.document.find( "body" ).css( "cursor", this.storedCursor ); this.storedStylesheet.remove(); } if(this._storedOpacity) { this.helper.css("opacity", this._storedOpacity); } if(this._storedZIndex) { this.helper.css("zIndex", this._storedZIndex === "auto" ? "" : this._storedZIndex); } this.dragging = false; if(this.cancelHelperRemoval) { if(!noPropagation) { this._trigger("beforeStop", event, this._uiHash()); for (i=0; i < delayedTriggers.length; i++) { delayedTriggers[i].call(this, event); } //Trigger all delayed events this._trigger("stop", event, this._uiHash()); } this.fromOutside = false; return false; } if(!noPropagation) { this._trigger("beforeStop", event, this._uiHash()); } //$(this.placeholder[0]).remove(); would have been the jQuery way - unfortunately, it unbinds ALL events from the original node! this.placeholder[0].parentNode.removeChild(this.placeholder[0]); if(this.helper[0] !== this.currentItem[0]) { this.helper.remove(); } this.helper = null; if(!noPropagation) { for (i=0; i < delayedTriggers.length; i++) { delayedTriggers[i].call(this, event); } //Trigger all delayed events this._trigger("stop", event, this._uiHash()); } this.fromOutside = false; return true; }, _trigger: function() { if ($.Widget.prototype._trigger.apply(this, arguments) === false) { this.cancel(); } }, _uiHash: function(_inst) { var inst = _inst || this; return { helper: inst.helper, placeholder: inst.placeholder || $([]), position: inst.position, originalPosition: inst.originalPosition, offset: inst.positionAbs, item: inst.currentItem, sender: _inst ? _inst.element : null }; } }); })(jQuery); (function( $, undefined ) { var uid = 0, hideProps = {}, showProps = {}; hideProps.height = hideProps.paddingTop = hideProps.paddingBottom = hideProps.borderTopWidth = hideProps.borderBottomWidth = "hide"; showProps.height = showProps.paddingTop = showProps.paddingBottom = showProps.borderTopWidth = showProps.borderBottomWidth = "show"; $.widget( "ui.accordion", { version: "1.10.3", options: { active: 0, animate: {}, collapsible: false, event: "click", header: "> li > :first-child,> :not(li):even", heightStyle: "auto", icons: { activeHeader: "ui-icon-triangle-1-s", header: "ui-icon-triangle-1-e" }, // callbacks activate: null, beforeActivate: null }, _create: function() { var options = this.options; this.prevShow = this.prevHide = $(); this.element.addClass( "ui-accordion ui-widget ui-helper-reset" ) // ARIA .attr( "role", "tablist" ); // don't allow collapsible: false and active: false / null if ( !options.collapsible && (options.active === false || options.active == null) ) { options.active = 0; } this._processPanels(); // handle negative values if ( options.active < 0 ) { options.active += this.headers.length; } this._refresh(); }, _getCreateEventData: function() { return { header: this.active, panel: !this.active.length ? $() : this.active.next(), content: !this.active.length ? $() : this.active.next() }; }, _createIcons: function() { var icons = this.options.icons; if ( icons ) { $( "<span>" ) .addClass( "ui-accordion-header-icon ui-icon " + icons.header ) .prependTo( this.headers ); this.active.children( ".ui-accordion-header-icon" ) .removeClass( icons.header ) .addClass( icons.activeHeader ); this.headers.addClass( "ui-accordion-icons" ); } }, _destroyIcons: function() { this.headers .removeClass( "ui-accordion-icons" ) .children( ".ui-accordion-header-icon" ) .remove(); }, _destroy: function() { var contents; // clean up main element this.element .removeClass( "ui-accordion ui-widget ui-helper-reset" ) .removeAttr( "role" ); // clean up headers this.headers .removeClass( "ui-accordion-header ui-accordion-header-active ui-helper-reset ui-state-default ui-corner-all ui-state-active ui-state-disabled ui-corner-top" ) .removeAttr( "role" ) .removeAttr( "aria-selected" ) .removeAttr( "aria-controls" ) .removeAttr( "tabIndex" ) .each(function() { if ( /^ui-accordion/.test( this.id ) ) { this.removeAttribute( "id" ); } }); this._destroyIcons(); // clean up content panels contents = this.headers.next() .css( "display", "" ) .removeAttr( "role" ) .removeAttr( "aria-expanded" ) .removeAttr( "aria-hidden" ) .removeAttr( "aria-labelledby" ) .removeClass( "ui-helper-reset ui-widget-content ui-corner-bottom ui-accordion-content ui-accordion-content-active ui-state-disabled" ) .each(function() { if ( /^ui-accordion/.test( this.id ) ) { this.removeAttribute( "id" ); } }); if ( this.options.heightStyle !== "content" ) { contents.css( "height", "" ); } }, _setOption: function( key, value ) { if ( key === "active" ) { // _activate() will handle invalid values and update this.options this._activate( value ); return; } if ( key === "event" ) { if ( this.options.event ) { this._off( this.headers, this.options.event ); } this._setupEvents( value ); } this._super( key, value ); // setting collapsible: false while collapsed; open first panel if ( key === "collapsible" && !value && this.options.active === false ) { this._activate( 0 ); } if ( key === "icons" ) { this._destroyIcons(); if ( value ) { this._createIcons(); } } // #5332 - opacity doesn't cascade to positioned elements in IE // so we need to add the disabled class to the headers and panels if ( key === "disabled" ) { this.headers.add( this.headers.next() ) .toggleClass( "ui-state-disabled", !!value ); } }, _keydown: function( event ) { /*jshint maxcomplexity:15*/ if ( event.altKey || event.ctrlKey ) { return; } var keyCode = $.ui.keyCode, length = this.headers.length, currentIndex = this.headers.index( event.target ), toFocus = false; switch ( event.keyCode ) { case keyCode.RIGHT: case keyCode.DOWN: toFocus = this.headers[ ( currentIndex + 1 ) % length ]; break; case keyCode.LEFT: case keyCode.UP: toFocus = this.headers[ ( currentIndex - 1 + length ) % length ]; break; case keyCode.SPACE: case keyCode.ENTER: this._eventHandler( event ); break; case keyCode.HOME: toFocus = this.headers[ 0 ]; break; case keyCode.END: toFocus = this.headers[ length - 1 ]; break; } if ( toFocus ) { $( event.target ).attr( "tabIndex", -1 ); $( toFocus ).attr( "tabIndex", 0 ); toFocus.focus(); event.preventDefault(); } }, _panelKeyDown : function( event ) { if ( event.keyCode === $.ui.keyCode.UP && event.ctrlKey ) { $( event.currentTarget ).prev().focus(); } }, refresh: function() { var options = this.options; this._processPanels(); // was collapsed or no panel if ( ( options.active === false && options.collapsible === true ) || !this.headers.length ) { options.active = false; this.active = $(); // active false only when collapsible is true } else if ( options.active === false ) { this._activate( 0 ); // was active, but active panel is gone } else if ( this.active.length && !$.contains( this.element[ 0 ], this.active[ 0 ] ) ) { // all remaining panel are disabled if ( this.headers.length === this.headers.find(".ui-state-disabled").length ) { options.active = false; this.active = $(); // activate previous panel } else { this._activate( Math.max( 0, options.active - 1 ) ); } // was active, active panel still exists } else { // make sure active index is correct options.active = this.headers.index( this.active ); } this._destroyIcons(); this._refresh(); }, _processPanels: function() { this.headers = this.element.find( this.options.header ) .addClass( "ui-accordion-header ui-helper-reset ui-state-default ui-corner-all" ); this.headers.next() .addClass( "ui-accordion-content ui-helper-reset ui-widget-content ui-corner-bottom" ) .filter(":not(.ui-accordion-content-active)") .hide(); }, _refresh: function() { var maxHeight, options = this.options, heightStyle = options.heightStyle, parent = this.element.parent(), accordionId = this.accordionId = "ui-accordion-" + (this.element.attr( "id" ) || ++uid); this.active = this._findActive( options.active ) .addClass( "ui-accordion-header-active ui-state-active ui-corner-top" ) .removeClass( "ui-corner-all" ); this.active.next() .addClass( "ui-accordion-content-active" ) .show(); this.headers .attr( "role", "tab" ) .each(function( i ) { var header = $( this ), headerId = header.attr( "id" ), panel = header.next(), panelId = panel.attr( "id" ); if ( !headerId ) { headerId = accordionId + "-header-" + i; header.attr( "id", headerId ); } if ( !panelId ) { panelId = accordionId + "-panel-" + i; panel.attr( "id", panelId ); } header.attr( "aria-controls", panelId ); panel.attr( "aria-labelledby", headerId ); }) .next() .attr( "role", "tabpanel" ); this.headers .not( this.active ) .attr({ "aria-selected": "false", tabIndex: -1 }) .next() .attr({ "aria-expanded": "false", "aria-hidden": "true" }) .hide(); // make sure at least one header is in the tab order if ( !this.active.length ) { this.headers.eq( 0 ).attr( "tabIndex", 0 ); } else { this.active.attr({ "aria-selected": "true", tabIndex: 0 }) .next() .attr({ "aria-expanded": "true", "aria-hidden": "false" }); } this._createIcons(); this._setupEvents( options.event ); if ( heightStyle === "fill" ) { maxHeight = parent.height(); this.element.siblings( ":visible" ).each(function() { var elem = $( this ), position = elem.css( "position" ); if ( position === "absolute" || position === "fixed" ) { return; } maxHeight -= elem.outerHeight( true ); }); this.headers.each(function() { maxHeight -= $( this ).outerHeight( true ); }); this.headers.next() .each(function() { $( this ).height( Math.max( 0, maxHeight - $( this ).innerHeight() + $( this ).height() ) ); }) .css( "overflow", "auto" ); } else if ( heightStyle === "auto" ) { maxHeight = 0; this.headers.next() .each(function() { maxHeight = Math.max( maxHeight, $( this ).css( "height", "" ).height() ); }) .height( maxHeight ); } }, _activate: function( index ) { var active = this._findActive( index )[ 0 ]; // trying to activate the already active panel if ( active === this.active[ 0 ] ) { return; } // trying to collapse, simulate a click on the currently active header active = active || this.active[ 0 ]; this._eventHandler({ target: active, currentTarget: active, preventDefault: $.noop }); }, _findActive: function( selector ) { return typeof selector === "number" ? this.headers.eq( selector ) : $(); }, _setupEvents: function( event ) { var events = { keydown: "_keydown" }; if ( event ) { $.each( event.split(" "), function( index, eventName ) { events[ eventName ] = "_eventHandler"; }); } this._off( this.headers.add( this.headers.next() ) ); this._on( this.headers, events ); this._on( this.headers.next(), { keydown: "_panelKeyDown" }); this._hoverable( this.headers ); this._focusable( this.headers ); }, _eventHandler: function( event ) { var options = this.options, active = this.active, clicked = $( event.currentTarget ), clickedIsActive = clicked[ 0 ] === active[ 0 ], collapsing = clickedIsActive && options.collapsible, toShow = collapsing ? $() : clicked.next(), toHide = active.next(), eventData = { oldHeader: active, oldPanel: toHide, newHeader: collapsing ? $() : clicked, newPanel: toShow }; event.preventDefault(); if ( // click on active header, but not collapsible ( clickedIsActive && !options.collapsible ) || // allow canceling activation ( this._trigger( "beforeActivate", event, eventData ) === false ) ) { return; } options.active = collapsing ? false : this.headers.index( clicked ); // when the call to ._toggle() comes after the class changes // it causes a very odd bug in IE 8 (see #6720) this.active = clickedIsActive ? $() : clicked; this._toggle( eventData ); // switch classes // corner classes on the previously active header stay after the animation active.removeClass( "ui-accordion-header-active ui-state-active" ); if ( options.icons ) { active.children( ".ui-accordion-header-icon" ) .removeClass( options.icons.activeHeader ) .addClass( options.icons.header ); } if ( !clickedIsActive ) { clicked .removeClass( "ui-corner-all" ) .addClass( "ui-accordion-header-active ui-state-active ui-corner-top" ); if ( options.icons ) { clicked.children( ".ui-accordion-header-icon" ) .removeClass( options.icons.header ) .addClass( options.icons.activeHeader ); } clicked .next() .addClass( "ui-accordion-content-active" ); } }, _toggle: function( data ) { var toShow = data.newPanel, toHide = this.prevShow.length ? this.prevShow : data.oldPanel; // handle activating a panel during the animation for another activation this.prevShow.add( this.prevHide ).stop( true, true ); this.prevShow = toShow; this.prevHide = toHide; if ( this.options.animate ) { this._animate( toShow, toHide, data ); } else { toHide.hide(); toShow.show(); this._toggleComplete( data ); } toHide.attr({ "aria-expanded": "false", "aria-hidden": "true" }); toHide.prev().attr( "aria-selected", "false" ); // if we're switching panels, remove the old header from the tab order // if we're opening from collapsed state, remove the previous header from the tab order // if we're collapsing, then keep the collapsing header in the tab order if ( toShow.length && toHide.length ) { toHide.prev().attr( "tabIndex", -1 ); } else if ( toShow.length ) { this.headers.filter(function() { return $( this ).attr( "tabIndex" ) === 0; }) .attr( "tabIndex", -1 ); } toShow .attr({ "aria-expanded": "true", "aria-hidden": "false" }) .prev() .attr({ "aria-selected": "true", tabIndex: 0 }); }, _animate: function( toShow, toHide, data ) { var total, easing, duration, that = this, adjust = 0, down = toShow.length && ( !toHide.length || ( toShow.index() < toHide.index() ) ), animate = this.options.animate || {}, options = down && animate.down || animate, complete = function() { that._toggleComplete( data ); }; if ( typeof options === "number" ) { duration = options; } if ( typeof options === "string" ) { easing = options; } // fall back from options to animation in case of partial down settings easing = easing || options.easing || animate.easing; duration = duration || options.duration || animate.duration; if ( !toHide.length ) { return toShow.animate( showProps, duration, easing, complete ); } if ( !toShow.length ) { return toHide.animate( hideProps, duration, easing, complete ); } total = toShow.show().outerHeight(); toHide.animate( hideProps, { duration: duration, easing: easing, step: function( now, fx ) { fx.now = Math.round( now ); } }); toShow .hide() .animate( showProps, { duration: duration, easing: easing, complete: complete, step: function( now, fx ) { fx.now = Math.round( now ); if ( fx.prop !== "height" ) { adjust += fx.now; } else if ( that.options.heightStyle !== "content" ) { fx.now = Math.round( total - toHide.outerHeight() - adjust ); adjust = 0; } } }); }, _toggleComplete: function( data ) { var toHide = data.oldPanel; toHide .removeClass( "ui-accordion-content-active" ) .prev() .removeClass( "ui-corner-top" ) .addClass( "ui-corner-all" ); // Work around for rendering bug in IE (#5421) if ( toHide.length ) { toHide.parent()[0].className = toHide.parent()[0].className; } this._trigger( "activate", null, data ); } }); })( jQuery ); (function( $, undefined ) { // used to prevent race conditions with remote data sources var requestIndex = 0; $.widget( "ui.autocomplete", { version: "1.10.3", defaultElement: "<input>", options: { appendTo: null, autoFocus: false, delay: 300, minLength: 1, position: { my: "left top", at: "left bottom", collision: "none" }, source: null, // callbacks change: null, close: null, focus: null, open: null, response: null, search: null, select: null }, pending: 0, _create: function() { // Some browsers only repeat keydown events, not keypress events, // so we use the suppressKeyPress flag to determine if we've already // handled the keydown event. #7269 // Unfortunately the code for & in keypress is the same as the up arrow, // so we use the suppressKeyPressRepeat flag to avoid handling keypress // events when we know the keydown event was used to modify the // search term. #7799 var suppressKeyPress, suppressKeyPressRepeat, suppressInput, nodeName = this.element[0].nodeName.toLowerCase(), isTextarea = nodeName === "textarea", isInput = nodeName === "input"; this.isMultiLine = // Textareas are always multi-line isTextarea ? true : // Inputs are always single-line, even if inside a contentEditable element // IE also treats inputs as contentEditable isInput ? false : // All other element types are determined by whether or not they're contentEditable this.element.prop( "isContentEditable" ); this.valueMethod = this.element[ isTextarea || isInput ? "val" : "text" ]; this.isNewMenu = true; this.element .addClass( "ui-autocomplete-input" ) .attr( "autocomplete", "off" ); this._on( this.element, { keydown: function( event ) { /*jshint maxcomplexity:15*/ if ( this.element.prop( "readOnly" ) ) { suppressKeyPress = true; suppressInput = true; suppressKeyPressRepeat = true; return; } suppressKeyPress = false; suppressInput = false; suppressKeyPressRepeat = false; var keyCode = $.ui.keyCode; switch( event.keyCode ) { case keyCode.PAGE_UP: suppressKeyPress = true; this._move( "previousPage", event ); break; case keyCode.PAGE_DOWN: suppressKeyPress = true; this._move( "nextPage", event ); break; case keyCode.UP: suppressKeyPress = true; this._keyEvent( "previous", event ); break; case keyCode.DOWN: suppressKeyPress = true; this._keyEvent( "next", event ); break; case keyCode.ENTER: case keyCode.NUMPAD_ENTER: // when menu is open and has focus if ( this.menu.active ) { // #6055 - Opera still allows the keypress to occur // which causes forms to submit suppressKeyPress = true; event.preventDefault(); this.menu.select( event ); } break; case keyCode.TAB: if ( this.menu.active ) { this.menu.select( event ); } break; case keyCode.ESCAPE: if ( this.menu.element.is( ":visible" ) ) { this._value( this.term ); this.close( event ); // Different browsers have different default behavior for escape // Single press can mean undo or clear // Double press in IE means clear the whole form event.preventDefault(); } break; default: suppressKeyPressRepeat = true; // search timeout should be triggered before the input value is changed this._searchTimeout( event ); break; } }, keypress: function( event ) { if ( suppressKeyPress ) { suppressKeyPress = false; if ( !this.isMultiLine || this.menu.element.is( ":visible" ) ) { event.preventDefault(); } return; } if ( suppressKeyPressRepeat ) { return; } // replicate some key handlers to allow them to repeat in Firefox and Opera var keyCode = $.ui.keyCode; switch( event.keyCode ) { case keyCode.PAGE_UP: this._move( "previousPage", event ); break; case keyCode.PAGE_DOWN: this._move( "nextPage", event ); break; case keyCode.UP: this._keyEvent( "previous", event ); break; case keyCode.DOWN: this._keyEvent( "next", event ); break; } }, input: function( event ) { if ( suppressInput ) { suppressInput = false; event.preventDefault(); return; } this._searchTimeout( event ); }, focus: function() { this.selectedItem = null; this.previous = this._value(); }, blur: function( event ) { if ( this.cancelBlur ) { delete this.cancelBlur; return; } clearTimeout( this.searching ); this.close( event ); this._change( event ); } }); this._initSource(); this.menu = $( "<ul>" ) .addClass( "ui-autocomplete ui-front" ) .appendTo( this._appendTo() ) .menu({ // disable ARIA support, the live region takes care of that role: null }) .hide() .data( "ui-menu" ); this._on( this.menu.element, { mousedown: function( event ) { // prevent moving focus out of the text field event.preventDefault(); // IE doesn't prevent moving focus even with event.preventDefault() // so we set a flag to know when we should ignore the blur event this.cancelBlur = true; this._delay(function() { delete this.cancelBlur; }); // clicking on the scrollbar causes focus to shift to the body // but we can't detect a mouseup or a click immediately afterward // so we have to track the next mousedown and close the menu if // the user clicks somewhere outside of the autocomplete var menuElement = this.menu.element[ 0 ]; if ( !$( event.target ).closest( ".ui-menu-item" ).length ) { this._delay(function() { var that = this; this.document.one( "mousedown", function( event ) { if ( event.target !== that.element[ 0 ] && event.target !== menuElement && !$.contains( menuElement, event.target ) ) { that.close(); } }); }); } }, menufocus: function( event, ui ) { // support: Firefox // Prevent accidental activation of menu items in Firefox (#7024 #9118) if ( this.isNewMenu ) { this.isNewMenu = false; if ( event.originalEvent && /^mouse/.test( event.originalEvent.type ) ) { this.menu.blur(); this.document.one( "mousemove", function() { $( event.target ).trigger( event.originalEvent ); }); return; } } var item = ui.item.data( "ui-autocomplete-item" ); if ( false !== this._trigger( "focus", event, { item: item } ) ) { // use value to match what will end up in the input, if it was a key event if ( event.originalEvent && /^key/.test( event.originalEvent.type ) ) { this._value( item.value ); } } else { // Normally the input is populated with the item's value as the // menu is navigated, causing screen readers to notice a change and // announce the item. Since the focus event was canceled, this doesn't // happen, so we update the live region so that screen readers can // still notice the change and announce it. this.liveRegion.text( item.value ); } }, menuselect: function( event, ui ) { var item = ui.item.data( "ui-autocomplete-item" ), previous = this.previous; // only trigger when focus was lost (click on menu) if ( this.element[0] !== this.document[0].activeElement ) { this.element.focus(); this.previous = previous; // #6109 - IE triggers two focus events and the second // is asynchronous, so we need to reset the previous // term synchronously and asynchronously :-( this._delay(function() { this.previous = previous; this.selectedItem = item; }); } if ( false !== this._trigger( "select", event, { item: item } ) ) { this._value( item.value ); } // reset the term after the select event // this allows custom select handling to work properly this.term = this._value(); this.close( event ); this.selectedItem = item; } }); this.liveRegion = $( "<span>", { role: "status", "aria-live": "polite" }) .addClass( "ui-helper-hidden-accessible" ) .insertBefore( this.element ); // turning off autocomplete prevents the browser from remembering the // value when navigating through history, so we re-enable autocomplete // if the page is unloaded before the widget is destroyed. #7790 this._on( this.window, { beforeunload: function() { this.element.removeAttr( "autocomplete" ); } }); }, _destroy: function() { clearTimeout( this.searching ); this.element .removeClass( "ui-autocomplete-input" ) .removeAttr( "autocomplete" ); this.menu.element.remove(); this.liveRegion.remove(); }, _setOption: function( key, value ) { this._super( key, value ); if ( key === "source" ) { this._initSource(); } if ( key === "appendTo" ) { this.menu.element.appendTo( this._appendTo() ); } if ( key === "disabled" && value && this.xhr ) { this.xhr.abort(); } }, _appendTo: function() { var element = this.options.appendTo; if ( element ) { element = element.jquery || element.nodeType ? $( element ) : this.document.find( element ).eq( 0 ); } if ( !element ) { element = this.element.closest( ".ui-front" ); } if ( !element.length ) { element = this.document[0].body; } return element; }, _initSource: function() { var array, url, that = this; if ( $.isArray(this.options.source) ) { array = this.options.source; this.source = function( request, response ) { response( $.ui.autocomplete.filter( array, request.term ) ); }; } else if ( typeof this.options.source === "string" ) { url = this.options.source; this.source = function( request, response ) { if ( that.xhr ) { that.xhr.abort(); } that.xhr = $.ajax({ url: url, data: request, dataType: "json", success: function( data ) { response( data ); }, error: function() { response( [] ); } }); }; } else { this.source = this.options.source; } }, _searchTimeout: function( event ) { clearTimeout( this.searching ); this.searching = this._delay(function() { // only search if the value has changed if ( this.term !== this._value() ) { this.selectedItem = null; this.search( null, event ); } }, this.options.delay ); }, search: function( value, event ) { value = value != null ? value : this._value(); // always save the actual value, not the one passed as an argument this.term = this._value(); if ( value.length < this.options.minLength ) { return this.close( event ); } if ( this._trigger( "search", event ) === false ) { return; } return this._search( value ); }, _search: function( value ) { this.pending++; this.element.addClass( "ui-autocomplete-loading" ); this.cancelSearch = false; this.source( { term: value }, this._response() ); }, _response: function() { var that = this, index = ++requestIndex; return function( content ) { if ( index === requestIndex ) { that.__response( content ); } that.pending--; if ( !that.pending ) { that.element.removeClass( "ui-autocomplete-loading" ); } }; }, __response: function( content ) { if ( content ) { content = this._normalize( content ); } this._trigger( "response", null, { content: content } ); if ( !this.options.disabled && content && content.length && !this.cancelSearch ) { this._suggest( content ); this._trigger( "open" ); } else { // use ._close() instead of .close() so we don't cancel future searches this._close(); } }, close: function( event ) { this.cancelSearch = true; this._close( event ); }, _close: function( event ) { if ( this.menu.element.is( ":visible" ) ) { this.menu.element.hide(); this.menu.blur(); this.isNewMenu = true; this._trigger( "close", event ); } }, _change: function( event ) { if ( this.previous !== this._value() ) { this._trigger( "change", event, { item: this.selectedItem } ); } }, _normalize: function( items ) { // assume all items have the right format when the first item is complete if ( items.length && items[0].label && items[0].value ) { return items; } return $.map( items, function( item ) { if ( typeof item === "string" ) { return { label: item, value: item }; } return $.extend({ label: item.label || item.value, value: item.value || item.label }, item ); }); }, _suggest: function( items ) { var ul = this.menu.element.empty(); this._renderMenu( ul, items ); this.isNewMenu = true; this.menu.refresh(); // size and position menu ul.show(); this._resizeMenu(); ul.position( $.extend({ of: this.element }, this.options.position )); if ( this.options.autoFocus ) { this.menu.next(); } }, _resizeMenu: function() { var ul = this.menu.element; ul.outerWidth( Math.max( // Firefox wraps long text (possibly a rounding bug) // so we add 1px to avoid the wrapping (#7513) ul.width( "" ).outerWidth() + 1, this.element.outerWidth() ) ); }, _renderMenu: function( ul, items ) { var that = this; $.each( items, function( index, item ) { that._renderItemData( ul, item ); }); }, _renderItemData: function( ul, item ) { return this._renderItem( ul, item ).data( "ui-autocomplete-item", item ); }, _renderItem: function( ul, item ) { return $( "<li>" ) .append( $( "<a>" ).text( item.label ) ) .appendTo( ul ); }, _move: function( direction, event ) { if ( !this.menu.element.is( ":visible" ) ) { this.search( null, event ); return; } if ( this.menu.isFirstItem() && /^previous/.test( direction ) || this.menu.isLastItem() && /^next/.test( direction ) ) { this._value( this.term ); this.menu.blur(); return; } this.menu[ direction ]( event ); }, widget: function() { return this.menu.element; }, _value: function() { return this.valueMethod.apply( this.element, arguments ); }, _keyEvent: function( keyEvent, event ) { if ( !this.isMultiLine || this.menu.element.is( ":visible" ) ) { this._move( keyEvent, event ); // prevents moving cursor to beginning/end of the text field in some browsers event.preventDefault(); } } }); $.extend( $.ui.autocomplete, { escapeRegex: function( value ) { return value.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&"); }, filter: function(array, term) { var matcher = new RegExp( $.ui.autocomplete.escapeRegex(term), "i" ); return $.grep( array, function(value) { return matcher.test( value.label || value.value || value ); }); } }); // live region extension, adding a `messages` option // NOTE: This is an experimental API. We are still investigating // a full solution for string manipulation and internationalization. $.widget( "ui.autocomplete", $.ui.autocomplete, { options: { messages: { noResults: "No search results.", results: function( amount ) { return amount + ( amount > 1 ? " results are" : " result is" ) + " available, use up and down arrow keys to navigate."; } } }, __response: function( content ) { var message; this._superApply( arguments ); if ( this.options.disabled || this.cancelSearch ) { return; } if ( content && content.length ) { message = this.options.messages.results( content.length ); } else { message = this.options.messages.noResults; } this.liveRegion.text( message ); } }); }( jQuery )); (function( $, undefined ) { var lastActive, startXPos, startYPos, clickDragged, baseClasses = "ui-button ui-widget ui-state-default ui-corner-all", stateClasses = "ui-state-hover ui-state-active ", typeClasses = "ui-button-icons-only ui-button-icon-only ui-button-text-icons ui-button-text-icon-primary ui-button-text-icon-secondary ui-button-text-only", formResetHandler = function() { var form = $( this ); setTimeout(function() { form.find( ":ui-button" ).button( "refresh" ); }, 1 ); }, radioGroup = function( radio ) { var name = radio.name, form = radio.form, radios = $( [] ); if ( name ) { name = name.replace( /'/g, "\\'" ); if ( form ) { radios = $( form ).find( "[name='" + name + "']" ); } else { radios = $( "[name='" + name + "']", radio.ownerDocument ) .filter(function() { return !this.form; }); } } return radios; }; $.widget( "ui.button", { version: "1.10.3", defaultElement: "<button>", options: { disabled: null, text: true, label: null, icons: { primary: null, secondary: null } }, _create: function() { this.element.closest( "form" ) .unbind( "reset" + this.eventNamespace ) .bind( "reset" + this.eventNamespace, formResetHandler ); if ( typeof this.options.disabled !== "boolean" ) { this.options.disabled = !!this.element.prop( "disabled" ); } else { this.element.prop( "disabled", this.options.disabled ); } this._determineButtonType(); this.hasTitle = !!this.buttonElement.attr( "title" ); var that = this, options = this.options, toggleButton = this.type === "checkbox" || this.type === "radio", activeClass = !toggleButton ? "ui-state-active" : "", focusClass = "ui-state-focus"; if ( options.label === null ) { options.label = (this.type === "input" ? this.buttonElement.val() : this.buttonElement.html()); } this._hoverable( this.buttonElement ); this.buttonElement .addClass( baseClasses ) .attr( "role", "button" ) .bind( "mouseenter" + this.eventNamespace, function() { if ( options.disabled ) { return; } if ( this === lastActive ) { $( this ).addClass( "ui-state-active" ); } }) .bind( "mouseleave" + this.eventNamespace, function() { if ( options.disabled ) { return; } $( this ).removeClass( activeClass ); }) .bind( "click" + this.eventNamespace, function( event ) { if ( options.disabled ) { event.preventDefault(); event.stopImmediatePropagation(); } }); this.element .bind( "focus" + this.eventNamespace, function() { // no need to check disabled, focus won't be triggered anyway that.buttonElement.addClass( focusClass ); }) .bind( "blur" + this.eventNamespace, function() { that.buttonElement.removeClass( focusClass ); }); if ( toggleButton ) { this.element.bind( "change" + this.eventNamespace, function() { if ( clickDragged ) { return; } that.refresh(); }); // if mouse moves between mousedown and mouseup (drag) set clickDragged flag // prevents issue where button state changes but checkbox/radio checked state // does not in Firefox (see ticket #6970) this.buttonElement .bind( "mousedown" + this.eventNamespace, function( event ) { if ( options.disabled ) { return; } clickDragged = false; startXPos = event.pageX; startYPos = event.pageY; }) .bind( "mouseup" + this.eventNamespace, function( event ) { if ( options.disabled ) { return; } if ( startXPos !== event.pageX || startYPos !== event.pageY ) { clickDragged = true; } }); } if ( this.type === "checkbox" ) { this.buttonElement.bind( "click" + this.eventNamespace, function() { if ( options.disabled || clickDragged ) { return false; } }); } else if ( this.type === "radio" ) { this.buttonElement.bind( "click" + this.eventNamespace, function() { if ( options.disabled || clickDragged ) { return false; } $( this ).addClass( "ui-state-active" ); that.buttonElement.attr( "aria-pressed", "true" ); var radio = that.element[ 0 ]; radioGroup( radio ) .not( radio ) .map(function() { return $( this ).button( "widget" )[ 0 ]; }) .removeClass( "ui-state-active" ) .attr( "aria-pressed", "false" ); }); } else { this.buttonElement .bind( "mousedown" + this.eventNamespace, function() { if ( options.disabled ) { return false; } $( this ).addClass( "ui-state-active" ); lastActive = this; that.document.one( "mouseup", function() { lastActive = null; }); }) .bind( "mouseup" + this.eventNamespace, function() { if ( options.disabled ) { return false; } $( this ).removeClass( "ui-state-active" ); }) .bind( "keydown" + this.eventNamespace, function(event) { if ( options.disabled ) { return false; } if ( event.keyCode === $.ui.keyCode.SPACE || event.keyCode === $.ui.keyCode.ENTER ) { $( this ).addClass( "ui-state-active" ); } }) // see #8559, we bind to blur here in case the button element loses // focus between keydown and keyup, it would be left in an "active" state .bind( "keyup" + this.eventNamespace + " blur" + this.eventNamespace, function() { $( this ).removeClass( "ui-state-active" ); }); if ( this.buttonElement.is("a") ) { this.buttonElement.keyup(function(event) { if ( event.keyCode === $.ui.keyCode.SPACE ) { // TODO pass through original event correctly (just as 2nd argument doesn't work) $( this ).click(); } }); } } // TODO: pull out $.Widget's handling for the disabled option into // $.Widget.prototype._setOptionDisabled so it's easy to proxy and can // be overridden by individual plugins this._setOption( "disabled", options.disabled ); this._resetButton(); }, _determineButtonType: function() { var ancestor, labelSelector, checked; if ( this.element.is("[type=checkbox]") ) { this.type = "checkbox"; } else if ( this.element.is("[type=radio]") ) { this.type = "radio"; } else if ( this.element.is("input") ) { this.type = "input"; } else { this.type = "button"; } if ( this.type === "checkbox" || this.type === "radio" ) { // we don't search against the document in case the element // is disconnected from the DOM ancestor = this.element.parents().last(); labelSelector = "label[for='" + this.element.attr("id") + "']"; this.buttonElement = ancestor.find( labelSelector ); if ( !this.buttonElement.length ) { ancestor = ancestor.length ? ancestor.siblings() : this.element.siblings(); this.buttonElement = ancestor.filter( labelSelector ); if ( !this.buttonElement.length ) { this.buttonElement = ancestor.find( labelSelector ); } } this.element.addClass( "ui-helper-hidden-accessible" ); checked = this.element.is( ":checked" ); if ( checked ) { this.buttonElement.addClass( "ui-state-active" ); } this.buttonElement.prop( "aria-pressed", checked ); } else { this.buttonElement = this.element; } }, widget: function() { return this.buttonElement; }, _destroy: function() { this.element .removeClass( "ui-helper-hidden-accessible" ); this.buttonElement .removeClass( baseClasses + " " + stateClasses + " " + typeClasses ) .removeAttr( "role" ) .removeAttr( "aria-pressed" ) .html( this.buttonElement.find(".ui-button-text").html() ); if ( !this.hasTitle ) { this.buttonElement.removeAttr( "title" ); } }, _setOption: function( key, value ) { this._super( key, value ); if ( key === "disabled" ) { if ( value ) { this.element.prop( "disabled", true ); } else { this.element.prop( "disabled", false ); } return; } this._resetButton(); }, refresh: function() { //See #8237 & #8828 var isDisabled = this.element.is( "input, button" ) ? this.element.is( ":disabled" ) : this.element.hasClass( "ui-button-disabled" ); if ( isDisabled !== this.options.disabled ) { this._setOption( "disabled", isDisabled ); } if ( this.type === "radio" ) { radioGroup( this.element[0] ).each(function() { if ( $( this ).is( ":checked" ) ) { $( this ).button( "widget" ) .addClass( "ui-state-active" ) .attr( "aria-pressed", "true" ); } else { $( this ).button( "widget" ) .removeClass( "ui-state-active" ) .attr( "aria-pressed", "false" ); } }); } else if ( this.type === "checkbox" ) { if ( this.element.is( ":checked" ) ) { this.buttonElement .addClass( "ui-state-active" ) .attr( "aria-pressed", "true" ); } else { this.buttonElement .removeClass( "ui-state-active" ) .attr( "aria-pressed", "false" ); } } }, _resetButton: function() { if ( this.type === "input" ) { if ( this.options.label ) { this.element.val( this.options.label ); } return; } var buttonElement = this.buttonElement.removeClass( typeClasses ), buttonText = $( "<span></span>", this.document[0] ) .addClass( "ui-button-text" ) .html( this.options.label ) .appendTo( buttonElement.empty() ) .text(), icons = this.options.icons, multipleIcons = icons.primary && icons.secondary, buttonClasses = []; if ( icons.primary || icons.secondary ) { if ( this.options.text ) { buttonClasses.push( "ui-button-text-icon" + ( multipleIcons ? "s" : ( icons.primary ? "-primary" : "-secondary" ) ) ); } if ( icons.primary ) { buttonElement.prepend( "<span class='ui-button-icon-primary ui-icon " + icons.primary + "'></span>" ); } if ( icons.secondary ) { buttonElement.append( "<span class='ui-button-icon-secondary ui-icon " + icons.secondary + "'></span>" ); } if ( !this.options.text ) { buttonClasses.push( multipleIcons ? "ui-button-icons-only" : "ui-button-icon-only" ); if ( !this.hasTitle ) { buttonElement.attr( "title", $.trim( buttonText ) ); } } } else { buttonClasses.push( "ui-button-text-only" ); } buttonElement.addClass( buttonClasses.join( " " ) ); } }); $.widget( "ui.buttonset", { version: "1.10.3", options: { items: "button, input[type=button], input[type=submit], input[type=reset], input[type=checkbox], input[type=radio], a, :data(ui-button)" }, _create: function() { this.element.addClass( "ui-buttonset" ); }, _init: function() { this.refresh(); }, _setOption: function( key, value ) { if ( key === "disabled" ) { this.buttons.button( "option", key, value ); } this._super( key, value ); }, refresh: function() { var rtl = this.element.css( "direction" ) === "rtl"; this.buttons = this.element.find( this.options.items ) .filter( ":ui-button" ) .button( "refresh" ) .end() .not( ":ui-button" ) .button() .end() .map(function() { return $( this ).button( "widget" )[ 0 ]; }) .removeClass( "ui-corner-all ui-corner-left ui-corner-right" ) .filter( ":first" ) .addClass( rtl ? "ui-corner-right" : "ui-corner-left" ) .end() .filter( ":last" ) .addClass( rtl ? "ui-corner-left" : "ui-corner-right" ) .end() .end(); }, _destroy: function() { this.element.removeClass( "ui-buttonset" ); this.buttons .map(function() { return $( this ).button( "widget" )[ 0 ]; }) .removeClass( "ui-corner-left ui-corner-right" ) .end() .button( "destroy" ); } }); }( jQuery ) ); (function( $, undefined ) { $.extend($.ui, { datepicker: { version: "1.10.3" } }); var PROP_NAME = "datepicker", instActive; /* Date picker manager. Use the singleton instance of this class, $.datepicker, to interact with the date picker. Settings for (groups of) date pickers are maintained in an instance object, allowing multiple different settings on the same page. */ function Datepicker() { this._curInst = null; // The current instance in use this._keyEvent = false; // If the last event was a key event this._disabledInputs = []; // List of date picker inputs that have been disabled this._datepickerShowing = false; // True if the popup picker is showing , false if not this._inDialog = false; // True if showing within a "dialog", false if not this._mainDivId = "ui-datepicker-div"; // The ID of the main datepicker division this._inlineClass = "ui-datepicker-inline"; // The name of the inline marker class this._appendClass = "ui-datepicker-append"; // The name of the append marker class this._triggerClass = "ui-datepicker-trigger"; // The name of the trigger marker class this._dialogClass = "ui-datepicker-dialog"; // The name of the dialog marker class this._disableClass = "ui-datepicker-disabled"; // The name of the disabled covering marker class this._unselectableClass = "ui-datepicker-unselectable"; // The name of the unselectable cell marker class this._currentClass = "ui-datepicker-current-day"; // The name of the current day marker class this._dayOverClass = "ui-datepicker-days-cell-over"; // The name of the day hover marker class this.regional = []; // Available regional settings, indexed by language code this.regional[""] = { // Default regional settings closeText: "Done", // Display text for close link prevText: "Prev", // Display text for previous month link nextText: "Next", // Display text for next month link currentText: "Today", // Display text for current month link monthNames: ["January","February","March","April","May","June", "July","August","September","October","November","December"], // Names of months for drop-down and formatting monthNamesShort: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"], // For formatting dayNames: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"], // For formatting dayNamesShort: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"], // For formatting dayNamesMin: ["Su","Mo","Tu","We","Th","Fr","Sa"], // Column headings for days starting at Sunday weekHeader: "Wk", // Column header for week of the year dateFormat: "mm/dd/yy", // See format options on parseDate firstDay: 0, // The first day of the week, Sun = 0, Mon = 1, ... isRTL: false, // True if right-to-left language, false if left-to-right showMonthAfterYear: false, // True if the year select precedes month, false for month then year yearSuffix: "" // Additional text to append to the year in the month headers }; this._defaults = { // Global defaults for all the date picker instances showOn: "focus", // "focus" for popup on focus, // "button" for trigger button, or "both" for either showAnim: "fadeIn", // Name of jQuery animation for popup showOptions: {}, // Options for enhanced animations defaultDate: null, // Used when field is blank: actual date, // +/-number for offset from today, null for today appendText: "", // Display text following the input box, e.g. showing the format buttonText: "...", // Text for trigger button buttonImage: "", // URL for trigger button image buttonImageOnly: false, // True if the image appears alone, false if it appears on a button hideIfNoPrevNext: false, // True to hide next/previous month links // if not applicable, false to just disable them navigationAsDateFormat: false, // True if date formatting applied to prev/today/next links gotoCurrent: false, // True if today link goes back to current selection instead changeMonth: false, // True if month can be selected directly, false if only prev/next changeYear: false, // True if year can be selected directly, false if only prev/next yearRange: "c-10:c+10", // Range of years to display in drop-down, // either relative to today's year (-nn:+nn), relative to currently displayed year // (c-nn:c+nn), absolute (nnnn:nnnn), or a combination of the above (nnnn:-n) showOtherMonths: false, // True to show dates in other months, false to leave blank selectOtherMonths: false, // True to allow selection of dates in other months, false for unselectable showWeek: false, // True to show week of the year, false to not show it calculateWeek: this.iso8601Week, // How to calculate the week of the year, // takes a Date and returns the number of the week for it shortYearCutoff: "+10", // Short year values < this are in the current century, // > this are in the previous century, // string value starting with "+" for current year + value minDate: null, // The earliest selectable date, or null for no limit maxDate: null, // The latest selectable date, or null for no limit duration: "fast", // Duration of display/closure beforeShowDay: null, // Function that takes a date and returns an array with // [0] = true if selectable, false if not, [1] = custom CSS class name(s) or "", // [2] = cell title (optional), e.g. $.datepicker.noWeekends beforeShow: null, // Function that takes an input field and // returns a set of custom settings for the date picker onSelect: null, // Define a callback function when a date is selected onChangeMonthYear: null, // Define a callback function when the month or year is changed onClose: null, // Define a callback function when the datepicker is closed numberOfMonths: 1, // Number of months to show at a time showCurrentAtPos: 0, // The position in multipe months at which to show the current month (starting at 0) stepMonths: 1, // Number of months to step back/forward stepBigMonths: 12, // Number of months to step back/forward for the big links altField: "", // Selector for an alternate field to store selected dates into altFormat: "", // The date format to use for the alternate field constrainInput: true, // The input is constrained by the current date format showButtonPanel: false, // True to show button panel, false to not show it autoSize: false, // True to size the input for the date format, false to leave as is disabled: false // The initial disabled state }; $.extend(this._defaults, this.regional[""]); this.dpDiv = bindHover($("<div id='" + this._mainDivId + "' class='ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all'></div>")); } $.extend(Datepicker.prototype, { /* Class name added to elements to indicate already configured with a date picker. */ markerClassName: "hasDatepicker", //Keep track of the maximum number of rows displayed (see #7043) maxRows: 4, // TODO rename to "widget" when switching to widget factory _widgetDatepicker: function() { return this.dpDiv; }, /* Override the default settings for all instances of the date picker. * @param settings object - the new settings to use as defaults (anonymous object) * @return the manager object */ setDefaults: function(settings) { extendRemove(this._defaults, settings || {}); return this; }, /* Attach the date picker to a jQuery selection. * @param target element - the target input field or division or span * @param settings object - the new settings to use for this date picker instance (anonymous) */ _attachDatepicker: function(target, settings) { var nodeName, inline, inst; nodeName = target.nodeName.toLowerCase(); inline = (nodeName === "div" || nodeName === "span"); if (!target.id) { this.uuid += 1; target.id = "dp" + this.uuid; } inst = this._newInst($(target), inline); inst.settings = $.extend({}, settings || {}); if (nodeName === "input") { this._connectDatepicker(target, inst); } else if (inline) { this._inlineDatepicker(target, inst); } }, /* Create a new instance object. */ _newInst: function(target, inline) { var id = target[0].id.replace(/([^A-Za-z0-9_\-])/g, "\\\\$1"); // escape jQuery meta chars return {id: id, input: target, // associated target selectedDay: 0, selectedMonth: 0, selectedYear: 0, // current selection drawMonth: 0, drawYear: 0, // month being drawn inline: inline, // is datepicker inline or not dpDiv: (!inline ? this.dpDiv : // presentation div bindHover($("<div class='" + this._inlineClass + " ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all'></div>")))}; }, /* Attach the date picker to an input field. */ _connectDatepicker: function(target, inst) { var input = $(target); inst.append = $([]); inst.trigger = $([]); if (input.hasClass(this.markerClassName)) { return; } this._attachments(input, inst); input.addClass(this.markerClassName).keydown(this._doKeyDown). keypress(this._doKeyPress).keyup(this._doKeyUp); this._autoSize(inst); $.data(target, PROP_NAME, inst); //If disabled option is true, disable the datepicker once it has been attached to the input (see ticket #5665) if( inst.settings.disabled ) { this._disableDatepicker( target ); } }, /* Make attachments based on settings. */ _attachments: function(input, inst) { var showOn, buttonText, buttonImage, appendText = this._get(inst, "appendText"), isRTL = this._get(inst, "isRTL"); if (inst.append) { inst.append.remove(); } if (appendText) { inst.append = $("<span class='" + this._appendClass + "'>" + appendText + "</span>"); input[isRTL ? "before" : "after"](inst.append); } input.unbind("focus", this._showDatepicker); if (inst.trigger) { inst.trigger.remove(); } showOn = this._get(inst, "showOn"); if (showOn === "focus" || showOn === "both") { // pop-up date picker when in the marked field input.focus(this._showDatepicker); } if (showOn === "button" || showOn === "both") { // pop-up date picker when button clicked buttonText = this._get(inst, "buttonText"); buttonImage = this._get(inst, "buttonImage"); inst.trigger = $(this._get(inst, "buttonImageOnly") ? $("<img/>").addClass(this._triggerClass). attr({ src: buttonImage, alt: buttonText, title: buttonText }) : $("<button type='button'></button>").addClass(this._triggerClass). html(!buttonImage ? buttonText : $("<img/>").attr( { src:buttonImage, alt:buttonText, title:buttonText }))); input[isRTL ? "before" : "after"](inst.trigger); inst.trigger.click(function() { if ($.datepicker._datepickerShowing && $.datepicker._lastInput === input[0]) { $.datepicker._hideDatepicker(); } else if ($.datepicker._datepickerShowing && $.datepicker._lastInput !== input[0]) { $.datepicker._hideDatepicker(); $.datepicker._showDatepicker(input[0]); } else { $.datepicker._showDatepicker(input[0]); } return false; }); } }, /* Apply the maximum length for the date format. */ _autoSize: function(inst) { if (this._get(inst, "autoSize") && !inst.inline) { var findMax, max, maxI, i, date = new Date(2009, 12 - 1, 20), // Ensure double digits dateFormat = this._get(inst, "dateFormat"); if (dateFormat.match(/[DM]/)) { findMax = function(names) { max = 0; maxI = 0; for (i = 0; i < names.length; i++) { if (names[i].length > max) { max = names[i].length; maxI = i; } } return maxI; }; date.setMonth(findMax(this._get(inst, (dateFormat.match(/MM/) ? "monthNames" : "monthNamesShort")))); date.setDate(findMax(this._get(inst, (dateFormat.match(/DD/) ? "dayNames" : "dayNamesShort"))) + 20 - date.getDay()); } inst.input.attr("size", this._formatDate(inst, date).length); } }, /* Attach an inline date picker to a div. */ _inlineDatepicker: function(target, inst) { var divSpan = $(target); if (divSpan.hasClass(this.markerClassName)) { return; } divSpan.addClass(this.markerClassName).append(inst.dpDiv); $.data(target, PROP_NAME, inst); this._setDate(inst, this._getDefaultDate(inst), true); this._updateDatepicker(inst); this._updateAlternate(inst); //If disabled option is true, disable the datepicker before showing it (see ticket #5665) if( inst.settings.disabled ) { this._disableDatepicker( target ); } // Set display:block in place of inst.dpDiv.show() which won't work on disconnected elements // http://bugs.jqueryui.com/ticket/7552 - A Datepicker created on a detached div has zero height inst.dpDiv.css( "display", "block" ); }, /* Pop-up the date picker in a "dialog" box. * @param input element - ignored * @param date string or Date - the initial date to display * @param onSelect function - the function to call when a date is selected * @param settings object - update the dialog date picker instance's settings (anonymous object) * @param pos int[2] - coordinates for the dialog's position within the screen or * event - with x/y coordinates or * leave empty for default (screen centre) * @return the manager object */ _dialogDatepicker: function(input, date, onSelect, settings, pos) { var id, browserWidth, browserHeight, scrollX, scrollY, inst = this._dialogInst; // internal instance if (!inst) { this.uuid += 1; id = "dp" + this.uuid; this._dialogInput = $("<input type='text' id='" + id + "' style='position: absolute; top: -100px; width: 0px;'/>"); this._dialogInput.keydown(this._doKeyDown); $("body").append(this._dialogInput); inst = this._dialogInst = this._newInst(this._dialogInput, false); inst.settings = {}; $.data(this._dialogInput[0], PROP_NAME, inst); } extendRemove(inst.settings, settings || {}); date = (date && date.constructor === Date ? this._formatDate(inst, date) : date); this._dialogInput.val(date); this._pos = (pos ? (pos.length ? pos : [pos.pageX, pos.pageY]) : null); if (!this._pos) { browserWidth = document.documentElement.clientWidth; browserHeight = document.documentElement.clientHeight; scrollX = document.documentElement.scrollLeft || document.body.scrollLeft; scrollY = document.documentElement.scrollTop || document.body.scrollTop; this._pos = // should use actual width/height below [(browserWidth / 2) - 100 + scrollX, (browserHeight / 2) - 150 + scrollY]; } // move input on screen for focus, but hidden behind dialog this._dialogInput.css("left", (this._pos[0] + 20) + "px").css("top", this._pos[1] + "px"); inst.settings.onSelect = onSelect; this._inDialog = true; this.dpDiv.addClass(this._dialogClass); this._showDatepicker(this._dialogInput[0]); if ($.blockUI) { $.blockUI(this.dpDiv); } $.data(this._dialogInput[0], PROP_NAME, inst); return this; }, /* Detach a datepicker from its control. * @param target element - the target input field or division or span */ _destroyDatepicker: function(target) { var nodeName, $target = $(target), inst = $.data(target, PROP_NAME); if (!$target.hasClass(this.markerClassName)) { return; } nodeName = target.nodeName.toLowerCase(); $.removeData(target, PROP_NAME); if (nodeName === "input") { inst.append.remove(); inst.trigger.remove(); $target.removeClass(this.markerClassName). unbind("focus", this._showDatepicker). unbind("keydown", this._doKeyDown). unbind("keypress", this._doKeyPress). unbind("keyup", this._doKeyUp); } else if (nodeName === "div" || nodeName === "span") { $target.removeClass(this.markerClassName).empty(); } }, /* Enable the date picker to a jQuery selection. * @param target element - the target input field or division or span */ _enableDatepicker: function(target) { var nodeName, inline, $target = $(target), inst = $.data(target, PROP_NAME); if (!$target.hasClass(this.markerClassName)) { return; } nodeName = target.nodeName.toLowerCase(); if (nodeName === "input") { target.disabled = false; inst.trigger.filter("button"). each(function() { this.disabled = false; }).end(). filter("img").css({opacity: "1.0", cursor: ""}); } else if (nodeName === "div" || nodeName === "span") { inline = $target.children("." + this._inlineClass); inline.children().removeClass("ui-state-disabled"); inline.find("select.ui-datepicker-month, select.ui-datepicker-year"). prop("disabled", false); } this._disabledInputs = $.map(this._disabledInputs, function(value) { return (value === target ? null : value); }); // delete entry }, /* Disable the date picker to a jQuery selection. * @param target element - the target input field or division or span */ _disableDatepicker: function(target) { var nodeName, inline, $target = $(target), inst = $.data(target, PROP_NAME); if (!$target.hasClass(this.markerClassName)) { return; } nodeName = target.nodeName.toLowerCase(); if (nodeName === "input") { target.disabled = true; inst.trigger.filter("button"). each(function() { this.disabled = true; }).end(). filter("img").css({opacity: "0.5", cursor: "default"}); } else if (nodeName === "div" || nodeName === "span") { inline = $target.children("." + this._inlineClass); inline.children().addClass("ui-state-disabled"); inline.find("select.ui-datepicker-month, select.ui-datepicker-year"). prop("disabled", true); } this._disabledInputs = $.map(this._disabledInputs, function(value) { return (value === target ? null : value); }); // delete entry this._disabledInputs[this._disabledInputs.length] = target; }, /* Is the first field in a jQuery collection disabled as a datepicker? * @param target element - the target input field or division or span * @return boolean - true if disabled, false if enabled */ _isDisabledDatepicker: function(target) { if (!target) { return false; } for (var i = 0; i < this._disabledInputs.length; i++) { if (this._disabledInputs[i] === target) { return true; } } return false; }, /* Retrieve the instance data for the target control. * @param target element - the target input field or division or span * @return object - the associated instance data * @throws error if a jQuery problem getting data */ _getInst: function(target) { try { return $.data(target, PROP_NAME); } catch (err) { throw "Missing instance data for this datepicker"; } }, /* Update or retrieve the settings for a date picker attached to an input field or division. * @param target element - the target input field or division or span * @param name object - the new settings to update or * string - the name of the setting to change or retrieve, * when retrieving also "all" for all instance settings or * "defaults" for all global defaults * @param value any - the new value for the setting * (omit if above is an object or to retrieve a value) */ _optionDatepicker: function(target, name, value) { var settings, date, minDate, maxDate, inst = this._getInst(target); if (arguments.length === 2 && typeof name === "string") { return (name === "defaults" ? $.extend({}, $.datepicker._defaults) : (inst ? (name === "all" ? $.extend({}, inst.settings) : this._get(inst, name)) : null)); } settings = name || {}; if (typeof name === "string") { settings = {}; settings[name] = value; } if (inst) { if (this._curInst === inst) { this._hideDatepicker(); } date = this._getDateDatepicker(target, true); minDate = this._getMinMaxDate(inst, "min"); maxDate = this._getMinMaxDate(inst, "max"); extendRemove(inst.settings, settings); // reformat the old minDate/maxDate values if dateFormat changes and a new minDate/maxDate isn't provided if (minDate !== null && settings.dateFormat !== undefined && settings.minDate === undefined) { inst.settings.minDate = this._formatDate(inst, minDate); } if (maxDate !== null && settings.dateFormat !== undefined && settings.maxDate === undefined) { inst.settings.maxDate = this._formatDate(inst, maxDate); } if ( "disabled" in settings ) { if ( settings.disabled ) { this._disableDatepicker(target); } else { this._enableDatepicker(target); } } this._attachments($(target), inst); this._autoSize(inst); this._setDate(inst, date); this._updateAlternate(inst); this._updateDatepicker(inst); } }, // change method deprecated _changeDatepicker: function(target, name, value) { this._optionDatepicker(target, name, value); }, /* Redraw the date picker attached to an input field or division. * @param target element - the target input field or division or span */ _refreshDatepicker: function(target) { var inst = this._getInst(target); if (inst) { this._updateDatepicker(inst); } }, /* Set the dates for a jQuery selection. * @param target element - the target input field or division or span * @param date Date - the new date */ _setDateDatepicker: function(target, date) { var inst = this._getInst(target); if (inst) { this._setDate(inst, date); this._updateDatepicker(inst); this._updateAlternate(inst); } }, /* Get the date(s) for the first entry in a jQuery selection. * @param target element - the target input field or division or span * @param noDefault boolean - true if no default date is to be used * @return Date - the current date */ _getDateDatepicker: function(target, noDefault) { var inst = this._getInst(target); if (inst && !inst.inline) { this._setDateFromField(inst, noDefault); } return (inst ? this._getDate(inst) : null); }, /* Handle keystrokes. */ _doKeyDown: function(event) { var onSelect, dateStr, sel, inst = $.datepicker._getInst(event.target), handled = true, isRTL = inst.dpDiv.is(".ui-datepicker-rtl"); inst._keyEvent = true; if ($.datepicker._datepickerShowing) { switch (event.keyCode) { case 9: $.datepicker._hideDatepicker(); handled = false; break; // hide on tab out case 13: sel = $("td." + $.datepicker._dayOverClass + ":not(." + $.datepicker._currentClass + ")", inst.dpDiv); if (sel[0]) { $.datepicker._selectDay(event.target, inst.selectedMonth, inst.selectedYear, sel[0]); } onSelect = $.datepicker._get(inst, "onSelect"); if (onSelect) { dateStr = $.datepicker._formatDate(inst); // trigger custom callback onSelect.apply((inst.input ? inst.input[0] : null), [dateStr, inst]); } else { $.datepicker._hideDatepicker(); } return false; // don't submit the form case 27: $.datepicker._hideDatepicker(); break; // hide on escape case 33: $.datepicker._adjustDate(event.target, (event.ctrlKey ? -$.datepicker._get(inst, "stepBigMonths") : -$.datepicker._get(inst, "stepMonths")), "M"); break; // previous month/year on page up/+ ctrl case 34: $.datepicker._adjustDate(event.target, (event.ctrlKey ? +$.datepicker._get(inst, "stepBigMonths") : +$.datepicker._get(inst, "stepMonths")), "M"); break; // next month/year on page down/+ ctrl case 35: if (event.ctrlKey || event.metaKey) { $.datepicker._clearDate(event.target); } handled = event.ctrlKey || event.metaKey; break; // clear on ctrl or command +end case 36: if (event.ctrlKey || event.metaKey) { $.datepicker._gotoToday(event.target); } handled = event.ctrlKey || event.metaKey; break; // current on ctrl or command +home case 37: if (event.ctrlKey || event.metaKey) { $.datepicker._adjustDate(event.target, (isRTL ? +1 : -1), "D"); } handled = event.ctrlKey || event.metaKey; // -1 day on ctrl or command +left if (event.originalEvent.altKey) { $.datepicker._adjustDate(event.target, (event.ctrlKey ? -$.datepicker._get(inst, "stepBigMonths") : -$.datepicker._get(inst, "stepMonths")), "M"); } // next month/year on alt +left on Mac break; case 38: if (event.ctrlKey || event.metaKey) { $.datepicker._adjustDate(event.target, -7, "D"); } handled = event.ctrlKey || event.metaKey; break; // -1 week on ctrl or command +up case 39: if (event.ctrlKey || event.metaKey) { $.datepicker._adjustDate(event.target, (isRTL ? -1 : +1), "D"); } handled = event.ctrlKey || event.metaKey; // +1 day on ctrl or command +right if (event.originalEvent.altKey) { $.datepicker._adjustDate(event.target, (event.ctrlKey ? +$.datepicker._get(inst, "stepBigMonths") : +$.datepicker._get(inst, "stepMonths")), "M"); } // next month/year on alt +right break; case 40: if (event.ctrlKey || event.metaKey) { $.datepicker._adjustDate(event.target, +7, "D"); } handled = event.ctrlKey || event.metaKey; break; // +1 week on ctrl or command +down default: handled = false; } } else if (event.keyCode === 36 && event.ctrlKey) { // display the date picker on ctrl+home $.datepicker._showDatepicker(this); } else { handled = false; } if (handled) { event.preventDefault(); event.stopPropagation(); } }, /* Filter entered characters - based on date format. */ _doKeyPress: function(event) { var chars, chr, inst = $.datepicker._getInst(event.target); if ($.datepicker._get(inst, "constrainInput")) { chars = $.datepicker._possibleChars($.datepicker._get(inst, "dateFormat")); chr = String.fromCharCode(event.charCode == null ? event.keyCode : event.charCode); return event.ctrlKey || event.metaKey || (chr < " " || !chars || chars.indexOf(chr) > -1); } }, /* Synchronise manual entry and field/alternate field. */ _doKeyUp: function(event) { var date, inst = $.datepicker._getInst(event.target); if (inst.input.val() !== inst.lastVal) { try { date = $.datepicker.parseDate($.datepicker._get(inst, "dateFormat"), (inst.input ? inst.input.val() : null), $.datepicker._getFormatConfig(inst)); if (date) { // only if valid $.datepicker._setDateFromField(inst); $.datepicker._updateAlternate(inst); $.datepicker._updateDatepicker(inst); } } catch (err) { } } return true; }, /* Pop-up the date picker for a given input field. * If false returned from beforeShow event handler do not show. * @param input element - the input field attached to the date picker or * event - if triggered by focus */ _showDatepicker: function(input) { input = input.target || input; if (input.nodeName.toLowerCase() !== "input") { // find from button/image trigger input = $("input", input.parentNode)[0]; } if ($.datepicker._isDisabledDatepicker(input) || $.datepicker._lastInput === input) { // already here return; } var inst, beforeShow, beforeShowSettings, isFixed, offset, showAnim, duration; inst = $.datepicker._getInst(input); if ($.datepicker._curInst && $.datepicker._curInst !== inst) { $.datepicker._curInst.dpDiv.stop(true, true); if ( inst && $.datepicker._datepickerShowing ) { $.datepicker._hideDatepicker( $.datepicker._curInst.input[0] ); } } beforeShow = $.datepicker._get(inst, "beforeShow"); beforeShowSettings = beforeShow ? beforeShow.apply(input, [input, inst]) : {}; if(beforeShowSettings === false){ return; } extendRemove(inst.settings, beforeShowSettings); inst.lastVal = null; $.datepicker._lastInput = input; $.datepicker._setDateFromField(inst); if ($.datepicker._inDialog) { // hide cursor input.value = ""; } if (!$.datepicker._pos) { // position below input $.datepicker._pos = $.datepicker._findPos(input); $.datepicker._pos[1] += input.offsetHeight; // add the height } isFixed = false; $(input).parents().each(function() { isFixed |= $(this).css("position") === "fixed"; return !isFixed; }); offset = {left: $.datepicker._pos[0], top: $.datepicker._pos[1]}; $.datepicker._pos = null; //to avoid flashes on Firefox inst.dpDiv.empty(); // determine sizing offscreen inst.dpDiv.css({position: "absolute", display: "block", top: "-1000px"}); $.datepicker._updateDatepicker(inst); // fix width for dynamic number of date pickers // and adjust position before showing offset = $.datepicker._checkOffset(inst, offset, isFixed); inst.dpDiv.css({position: ($.datepicker._inDialog && $.blockUI ? "static" : (isFixed ? "fixed" : "absolute")), display: "none", left: offset.left + "px", top: offset.top + "px"}); if (!inst.inline) { showAnim = $.datepicker._get(inst, "showAnim"); duration = $.datepicker._get(inst, "duration"); inst.dpDiv.zIndex($(input).zIndex()+1); $.datepicker._datepickerShowing = true; if ( $.effects && $.effects.effect[ showAnim ] ) { inst.dpDiv.show(showAnim, $.datepicker._get(inst, "showOptions"), duration); } else { inst.dpDiv[showAnim || "show"](showAnim ? duration : null); } if ( $.datepicker._shouldFocusInput( inst ) ) { inst.input.focus(); } $.datepicker._curInst = inst; } }, /* Generate the date picker content. */ _updateDatepicker: function(inst) { this.maxRows = 4; //Reset the max number of rows being displayed (see #7043) instActive = inst; // for delegate hover events inst.dpDiv.empty().append(this._generateHTML(inst)); this._attachHandlers(inst); inst.dpDiv.find("." + this._dayOverClass + " a").mouseover(); var origyearshtml, numMonths = this._getNumberOfMonths(inst), cols = numMonths[1], width = 17; inst.dpDiv.removeClass("ui-datepicker-multi-2 ui-datepicker-multi-3 ui-datepicker-multi-4").width(""); if (cols > 1) { inst.dpDiv.addClass("ui-datepicker-multi-" + cols).css("width", (width * cols) + "em"); } inst.dpDiv[(numMonths[0] !== 1 || numMonths[1] !== 1 ? "add" : "remove") + "Class"]("ui-datepicker-multi"); inst.dpDiv[(this._get(inst, "isRTL") ? "add" : "remove") + "Class"]("ui-datepicker-rtl"); if (inst === $.datepicker._curInst && $.datepicker._datepickerShowing && $.datepicker._shouldFocusInput( inst ) ) { inst.input.focus(); } // deffered render of the years select (to avoid flashes on Firefox) if( inst.yearshtml ){ origyearshtml = inst.yearshtml; setTimeout(function(){ //assure that inst.yearshtml didn't change. if( origyearshtml === inst.yearshtml && inst.yearshtml ){ inst.dpDiv.find("select.ui-datepicker-year:first").replaceWith(inst.yearshtml); } origyearshtml = inst.yearshtml = null; }, 0); } }, // #6694 - don't focus the input if it's already focused // this breaks the change event in IE // Support: IE and jQuery <1.9 _shouldFocusInput: function( inst ) { return inst.input && inst.input.is( ":visible" ) && !inst.input.is( ":disabled" ) && !inst.input.is( ":focus" ); }, /* Check positioning to remain on screen. */ _checkOffset: function(inst, offset, isFixed) { var dpWidth = inst.dpDiv.outerWidth(), dpHeight = inst.dpDiv.outerHeight(), inputWidth = inst.input ? inst.input.outerWidth() : 0, inputHeight = inst.input ? inst.input.outerHeight() : 0, viewWidth = document.documentElement.clientWidth + (isFixed ? 0 : $(document).scrollLeft()), viewHeight = document.documentElement.clientHeight + (isFixed ? 0 : $(document).scrollTop()); offset.left -= (this._get(inst, "isRTL") ? (dpWidth - inputWidth) : 0); offset.left -= (isFixed && offset.left === inst.input.offset().left) ? $(document).scrollLeft() : 0; offset.top -= (isFixed && offset.top === (inst.input.offset().top + inputHeight)) ? $(document).scrollTop() : 0; // now check if datepicker is showing outside window viewport - move to a better place if so. offset.left -= Math.min(offset.left, (offset.left + dpWidth > viewWidth && viewWidth > dpWidth) ? Math.abs(offset.left + dpWidth - viewWidth) : 0); offset.top -= Math.min(offset.top, (offset.top + dpHeight > viewHeight && viewHeight > dpHeight) ? Math.abs(dpHeight + inputHeight) : 0); return offset; }, /* Find an object's position on the screen. */ _findPos: function(obj) { var position, inst = this._getInst(obj), isRTL = this._get(inst, "isRTL"); while (obj && (obj.type === "hidden" || obj.nodeType !== 1 || $.expr.filters.hidden(obj))) { obj = obj[isRTL ? "previousSibling" : "nextSibling"]; } position = $(obj).offset(); return [position.left, position.top]; }, /* Hide the date picker from view. * @param input element - the input field attached to the date picker */ _hideDatepicker: function(input) { var showAnim, duration, postProcess, onClose, inst = this._curInst; if (!inst || (input && inst !== $.data(input, PROP_NAME))) { return; } if (this._datepickerShowing) { showAnim = this._get(inst, "showAnim"); duration = this._get(inst, "duration"); postProcess = function() { $.datepicker._tidyDialog(inst); }; // DEPRECATED: after BC for 1.8.x $.effects[ showAnim ] is not needed if ( $.effects && ( $.effects.effect[ showAnim ] || $.effects[ showAnim ] ) ) { inst.dpDiv.hide(showAnim, $.datepicker._get(inst, "showOptions"), duration, postProcess); } else { inst.dpDiv[(showAnim === "slideDown" ? "slideUp" : (showAnim === "fadeIn" ? "fadeOut" : "hide"))]((showAnim ? duration : null), postProcess); } if (!showAnim) { postProcess(); } this._datepickerShowing = false; onClose = this._get(inst, "onClose"); if (onClose) { onClose.apply((inst.input ? inst.input[0] : null), [(inst.input ? inst.input.val() : ""), inst]); } this._lastInput = null; if (this._inDialog) { this._dialogInput.css({ position: "absolute", left: "0", top: "-100px" }); if ($.blockUI) { $.unblockUI(); $("body").append(this.dpDiv); } } this._inDialog = false; } }, /* Tidy up after a dialog display. */ _tidyDialog: function(inst) { inst.dpDiv.removeClass(this._dialogClass).unbind(".ui-datepicker-calendar"); }, /* Close date picker if clicked elsewhere. */ _checkExternalClick: function(event) { if (!$.datepicker._curInst) { return; } var $target = $(event.target), inst = $.datepicker._getInst($target[0]); if ( ( ( $target[0].id !== $.datepicker._mainDivId && $target.parents("#" + $.datepicker._mainDivId).length === 0 && !$target.hasClass($.datepicker.markerClassName) && !$target.closest("." + $.datepicker._triggerClass).length && $.datepicker._datepickerShowing && !($.datepicker._inDialog && $.blockUI) ) ) || ( $target.hasClass($.datepicker.markerClassName) && $.datepicker._curInst !== inst ) ) { $.datepicker._hideDatepicker(); } }, /* Adjust one of the date sub-fields. */ _adjustDate: function(id, offset, period) { var target = $(id), inst = this._getInst(target[0]); if (this._isDisabledDatepicker(target[0])) { return; } this._adjustInstDate(inst, offset + (period === "M" ? this._get(inst, "showCurrentAtPos") : 0), // undo positioning period); this._updateDatepicker(inst); }, /* Action for current link. */ _gotoToday: function(id) { var date, target = $(id), inst = this._getInst(target[0]); if (this._get(inst, "gotoCurrent") && inst.currentDay) { inst.selectedDay = inst.currentDay; inst.drawMonth = inst.selectedMonth = inst.currentMonth; inst.drawYear = inst.selectedYear = inst.currentYear; } else { date = new Date(); inst.selectedDay = date.getDate(); inst.drawMonth = inst.selectedMonth = date.getMonth(); inst.drawYear = inst.selectedYear = date.getFullYear(); } this._notifyChange(inst); this._adjustDate(target); }, /* Action for selecting a new month/year. */ _selectMonthYear: function(id, select, period) { var target = $(id), inst = this._getInst(target[0]); inst["selected" + (period === "M" ? "Month" : "Year")] = inst["draw" + (period === "M" ? "Month" : "Year")] = parseInt(select.options[select.selectedIndex].value,10); this._notifyChange(inst); this._adjustDate(target); }, /* Action for selecting a day. */ _selectDay: function(id, month, year, td) { var inst, target = $(id); if ($(td).hasClass(this._unselectableClass) || this._isDisabledDatepicker(target[0])) { return; } inst = this._getInst(target[0]); inst.selectedDay = inst.currentDay = $("a", td).html(); inst.selectedMonth = inst.currentMonth = month; inst.selectedYear = inst.currentYear = year; this._selectDate(id, this._formatDate(inst, inst.currentDay, inst.currentMonth, inst.currentYear)); }, /* Erase the input field and hide the date picker. */ _clearDate: function(id) { var target = $(id); this._selectDate(target, ""); }, /* Update the input field with the selected date. */ _selectDate: function(id, dateStr) { var onSelect, target = $(id), inst = this._getInst(target[0]); dateStr = (dateStr != null ? dateStr : this._formatDate(inst)); if (inst.input) { inst.input.val(dateStr); } this._updateAlternate(inst); onSelect = this._get(inst, "onSelect"); if (onSelect) { onSelect.apply((inst.input ? inst.input[0] : null), [dateStr, inst]); // trigger custom callback } else if (inst.input) { inst.input.trigger("change"); // fire the change event } if (inst.inline){ this._updateDatepicker(inst); } else { this._hideDatepicker(); this._lastInput = inst.input[0]; if (typeof(inst.input[0]) !== "object") { inst.input.focus(); // restore focus } this._lastInput = null; } }, /* Update any alternate field to synchronise with the main field. */ _updateAlternate: function(inst) { var altFormat, date, dateStr, altField = this._get(inst, "altField"); if (altField) { // update alternate field too altFormat = this._get(inst, "altFormat") || this._get(inst, "dateFormat"); date = this._getDate(inst); dateStr = this.formatDate(altFormat, date, this._getFormatConfig(inst)); $(altField).each(function() { $(this).val(dateStr); }); } }, /* Set as beforeShowDay function to prevent selection of weekends. * @param date Date - the date to customise * @return [boolean, string] - is this date selectable?, what is its CSS class? */ noWeekends: function(date) { var day = date.getDay(); return [(day > 0 && day < 6), ""]; }, /* Set as calculateWeek to determine the week of the year based on the ISO 8601 definition. * @param date Date - the date to get the week for * @return number - the number of the week within the year that contains this date */ iso8601Week: function(date) { var time, checkDate = new Date(date.getTime()); // Find Thursday of this week starting on Monday checkDate.setDate(checkDate.getDate() + 4 - (checkDate.getDay() || 7)); time = checkDate.getTime(); checkDate.setMonth(0); // Compare with Jan 1 checkDate.setDate(1); return Math.floor(Math.round((time - checkDate) / 86400000) / 7) + 1; }, /* Parse a string value into a date object. * See formatDate below for the possible formats. * * @param format string - the expected format of the date * @param value string - the date in the above format * @param settings Object - attributes include: * shortYearCutoff number - the cutoff year for determining the century (optional) * dayNamesShort string[7] - abbreviated names of the days from Sunday (optional) * dayNames string[7] - names of the days from Sunday (optional) * monthNamesShort string[12] - abbreviated names of the months (optional) * monthNames string[12] - names of the months (optional) * @return Date - the extracted date value or null if value is blank */ parseDate: function (format, value, settings) { if (format == null || value == null) { throw "Invalid arguments"; } value = (typeof value === "object" ? value.toString() : value + ""); if (value === "") { return null; } var iFormat, dim, extra, iValue = 0, shortYearCutoffTemp = (settings ? settings.shortYearCutoff : null) || this._defaults.shortYearCutoff, shortYearCutoff = (typeof shortYearCutoffTemp !== "string" ? shortYearCutoffTemp : new Date().getFullYear() % 100 + parseInt(shortYearCutoffTemp, 10)), dayNamesShort = (settings ? settings.dayNamesShort : null) || this._defaults.dayNamesShort, dayNames = (settings ? settings.dayNames : null) || this._defaults.dayNames, monthNamesShort = (settings ? settings.monthNamesShort : null) || this._defaults.monthNamesShort, monthNames = (settings ? settings.monthNames : null) || this._defaults.monthNames, year = -1, month = -1, day = -1, doy = -1, literal = false, date, // Check whether a format character is doubled lookAhead = function(match) { var matches = (iFormat + 1 < format.length && format.charAt(iFormat + 1) === match); if (matches) { iFormat++; } return matches; }, // Extract a number from the string value getNumber = function(match) { var isDoubled = lookAhead(match), size = (match === "@" ? 14 : (match === "!" ? 20 : (match === "y" && isDoubled ? 4 : (match === "o" ? 3 : 2)))), digits = new RegExp("^\\d{1," + size + "}"), num = value.substring(iValue).match(digits); if (!num) { throw "Missing number at position " + iValue; } iValue += num[0].length; return parseInt(num[0], 10); }, // Extract a name from the string value and convert to an index getName = function(match, shortNames, longNames) { var index = -1, names = $.map(lookAhead(match) ? longNames : shortNames, function (v, k) { return [ [k, v] ]; }).sort(function (a, b) { return -(a[1].length - b[1].length); }); $.each(names, function (i, pair) { var name = pair[1]; if (value.substr(iValue, name.length).toLowerCase() === name.toLowerCase()) { index = pair[0]; iValue += name.length; return false; } }); if (index !== -1) { return index + 1; } else { throw "Unknown name at position " + iValue; } }, // Confirm that a literal character matches the string value checkLiteral = function() { if (value.charAt(iValue) !== format.charAt(iFormat)) { throw "Unexpected literal at position " + iValue; } iValue++; }; for (iFormat = 0; iFormat < format.length; iFormat++) { if (literal) { if (format.charAt(iFormat) === "'" && !lookAhead("'")) { literal = false; } else { checkLiteral(); } } else { switch (format.charAt(iFormat)) { case "d": day = getNumber("d"); break; case "D": getName("D", dayNamesShort, dayNames); break; case "o": doy = getNumber("o"); break; case "m": month = getNumber("m"); break; case "M": month = getName("M", monthNamesShort, monthNames); break; case "y": year = getNumber("y"); break; case "@": date = new Date(getNumber("@")); year = date.getFullYear(); month = date.getMonth() + 1; day = date.getDate(); break; case "!": date = new Date((getNumber("!") - this._ticksTo1970) / 10000); year = date.getFullYear(); month = date.getMonth() + 1; day = date.getDate(); break; case "'": if (lookAhead("'")){ checkLiteral(); } else { literal = true; } break; default: checkLiteral(); } } } if (iValue < value.length){ extra = value.substr(iValue); if (!/^\s+/.test(extra)) { throw "Extra/unparsed characters found in date: " + extra; } } if (year === -1) { year = new Date().getFullYear(); } else if (year < 100) { year += new Date().getFullYear() - new Date().getFullYear() % 100 + (year <= shortYearCutoff ? 0 : -100); } if (doy > -1) { month = 1; day = doy; do { dim = this._getDaysInMonth(year, month - 1); if (day <= dim) { break; } month++; day -= dim; } while (true); } date = this._daylightSavingAdjust(new Date(year, month - 1, day)); if (date.getFullYear() !== year || date.getMonth() + 1 !== month || date.getDate() !== day) { throw "Invalid date"; // E.g. 31/02/00 } return date; }, /* Standard date formats. */ ATOM: "yy-mm-dd", // RFC 3339 (ISO 8601) COOKIE: "D, dd M yy", ISO_8601: "yy-mm-dd", RFC_822: "D, d M y", RFC_850: "DD, dd-M-y", RFC_1036: "D, d M y", RFC_1123: "D, d M yy", RFC_2822: "D, d M yy", RSS: "D, d M y", // RFC 822 TICKS: "!", TIMESTAMP: "@", W3C: "yy-mm-dd", // ISO 8601 _ticksTo1970: (((1970 - 1) * 365 + Math.floor(1970 / 4) - Math.floor(1970 / 100) + Math.floor(1970 / 400)) * 24 * 60 * 60 * 10000000), /* Format a date object into a string value. * The format can be combinations of the following: * d - day of month (no leading zero) * dd - day of month (two digit) * o - day of year (no leading zeros) * oo - day of year (three digit) * D - day name short * DD - day name long * m - month of year (no leading zero) * mm - month of year (two digit) * M - month name short * MM - month name long * y - year (two digit) * yy - year (four digit) * @ - Unix timestamp (ms since 01/01/1970) * ! - Windows ticks (100ns since 01/01/0001) * "..." - literal text * '' - single quote * * @param format string - the desired format of the date * @param date Date - the date value to format * @param settings Object - attributes include: * dayNamesShort string[7] - abbreviated names of the days from Sunday (optional) * dayNames string[7] - names of the days from Sunday (optional) * monthNamesShort string[12] - abbreviated names of the months (optional) * monthNames string[12] - names of the months (optional) * @return string - the date in the above format */ formatDate: function (format, date, settings) { if (!date) { return ""; } var iFormat, dayNamesShort = (settings ? settings.dayNamesShort : null) || this._defaults.dayNamesShort, dayNames = (settings ? settings.dayNames : null) || this._defaults.dayNames, monthNamesShort = (settings ? settings.monthNamesShort : null) || this._defaults.monthNamesShort, monthNames = (settings ? settings.monthNames : null) || this._defaults.monthNames, // Check whether a format character is doubled lookAhead = function(match) { var matches = (iFormat + 1 < format.length && format.charAt(iFormat + 1) === match); if (matches) { iFormat++; } return matches; }, // Format a number, with leading zero if necessary formatNumber = function(match, value, len) { var num = "" + value; if (lookAhead(match)) { while (num.length < len) { num = "0" + num; } } return num; }, // Format a name, short or long as requested formatName = function(match, value, shortNames, longNames) { return (lookAhead(match) ? longNames[value] : shortNames[value]); }, output = "", literal = false; if (date) { for (iFormat = 0; iFormat < format.length; iFormat++) { if (literal) { if (format.charAt(iFormat) === "'" && !lookAhead("'")) { literal = false; } else { output += format.charAt(iFormat); } } else { switch (format.charAt(iFormat)) { case "d": output += formatNumber("d", date.getDate(), 2); break; case "D": output += formatName("D", date.getDay(), dayNamesShort, dayNames); break; case "o": output += formatNumber("o", Math.round((new Date(date.getFullYear(), date.getMonth(), date.getDate()).getTime() - new Date(date.getFullYear(), 0, 0).getTime()) / 86400000), 3); break; case "m": output += formatNumber("m", date.getMonth() + 1, 2); break; case "M": output += formatName("M", date.getMonth(), monthNamesShort, monthNames); break; case "y": output += (lookAhead("y") ? date.getFullYear() : (date.getYear() % 100 < 10 ? "0" : "") + date.getYear() % 100); break; case "@": output += date.getTime(); break; case "!": output += date.getTime() * 10000 + this._ticksTo1970; break; case "'": if (lookAhead("'")) { output += "'"; } else { literal = true; } break; default: output += format.charAt(iFormat); } } } } return output; }, /* Extract all possible characters from the date format. */ _possibleChars: function (format) { var iFormat, chars = "", literal = false, // Check whether a format character is doubled lookAhead = function(match) { var matches = (iFormat + 1 < format.length && format.charAt(iFormat + 1) === match); if (matches) { iFormat++; } return matches; }; for (iFormat = 0; iFormat < format.length; iFormat++) { if (literal) { if (format.charAt(iFormat) === "'" && !lookAhead("'")) { literal = false; } else { chars += format.charAt(iFormat); } } else { switch (format.charAt(iFormat)) { case "d": case "m": case "y": case "@": chars += "0123456789"; break; case "D": case "M": return null; // Accept anything case "'": if (lookAhead("'")) { chars += "'"; } else { literal = true; } break; default: chars += format.charAt(iFormat); } } } return chars; }, /* Get a setting value, defaulting if necessary. */ _get: function(inst, name) { return inst.settings[name] !== undefined ? inst.settings[name] : this._defaults[name]; }, /* Parse existing date and initialise date picker. */ _setDateFromField: function(inst, noDefault) { if (inst.input.val() === inst.lastVal) { return; } var dateFormat = this._get(inst, "dateFormat"), dates = inst.lastVal = inst.input ? inst.input.val() : null, defaultDate = this._getDefaultDate(inst), date = defaultDate, settings = this._getFormatConfig(inst); try { date = this.parseDate(dateFormat, dates, settings) || defaultDate; } catch (event) { dates = (noDefault ? "" : dates); } inst.selectedDay = date.getDate(); inst.drawMonth = inst.selectedMonth = date.getMonth(); inst.drawYear = inst.selectedYear = date.getFullYear(); inst.currentDay = (dates ? date.getDate() : 0); inst.currentMonth = (dates ? date.getMonth() : 0); inst.currentYear = (dates ? date.getFullYear() : 0); this._adjustInstDate(inst); }, /* Retrieve the default date shown on opening. */ _getDefaultDate: function(inst) { return this._restrictMinMax(inst, this._determineDate(inst, this._get(inst, "defaultDate"), new Date())); }, /* A date may be specified as an exact value or a relative one. */ _determineDate: function(inst, date, defaultDate) { var offsetNumeric = function(offset) { var date = new Date(); date.setDate(date.getDate() + offset); return date; }, offsetString = function(offset) { try { return $.datepicker.parseDate($.datepicker._get(inst, "dateFormat"), offset, $.datepicker._getFormatConfig(inst)); } catch (e) { // Ignore } var date = (offset.toLowerCase().match(/^c/) ? $.datepicker._getDate(inst) : null) || new Date(), year = date.getFullYear(), month = date.getMonth(), day = date.getDate(), pattern = /([+\-]?[0-9]+)\s*(d|D|w|W|m|M|y|Y)?/g, matches = pattern.exec(offset); while (matches) { switch (matches[2] || "d") { case "d" : case "D" : day += parseInt(matches[1],10); break; case "w" : case "W" : day += parseInt(matches[1],10) * 7; break; case "m" : case "M" : month += parseInt(matches[1],10); day = Math.min(day, $.datepicker._getDaysInMonth(year, month)); break; case "y": case "Y" : year += parseInt(matches[1],10); day = Math.min(day, $.datepicker._getDaysInMonth(year, month)); break; } matches = pattern.exec(offset); } return new Date(year, month, day); }, newDate = (date == null || date === "" ? defaultDate : (typeof date === "string" ? offsetString(date) : (typeof date === "number" ? (isNaN(date) ? defaultDate : offsetNumeric(date)) : new Date(date.getTime())))); newDate = (newDate && newDate.toString() === "Invalid Date" ? defaultDate : newDate); if (newDate) { newDate.setHours(0); newDate.setMinutes(0); newDate.setSeconds(0); newDate.setMilliseconds(0); } return this._daylightSavingAdjust(newDate); }, /* Handle switch to/from daylight saving. * Hours may be non-zero on daylight saving cut-over: * > 12 when midnight changeover, but then cannot generate * midnight datetime, so jump to 1AM, otherwise reset. * @param date (Date) the date to check * @return (Date) the corrected date */ _daylightSavingAdjust: function(date) { if (!date) { return null; } date.setHours(date.getHours() > 12 ? date.getHours() + 2 : 0); return date; }, /* Set the date(s) directly. */ _setDate: function(inst, date, noChange) { var clear = !date, origMonth = inst.selectedMonth, origYear = inst.selectedYear, newDate = this._restrictMinMax(inst, this._determineDate(inst, date, new Date())); inst.selectedDay = inst.currentDay = newDate.getDate(); inst.drawMonth = inst.selectedMonth = inst.currentMonth = newDate.getMonth(); inst.drawYear = inst.selectedYear = inst.currentYear = newDate.getFullYear(); if ((origMonth !== inst.selectedMonth || origYear !== inst.selectedYear) && !noChange) { this._notifyChange(inst); } this._adjustInstDate(inst); if (inst.input) { inst.input.val(clear ? "" : this._formatDate(inst)); } }, /* Retrieve the date(s) directly. */ _getDate: function(inst) { var startDate = (!inst.currentYear || (inst.input && inst.input.val() === "") ? null : this._daylightSavingAdjust(new Date( inst.currentYear, inst.currentMonth, inst.currentDay))); return startDate; }, /* Attach the onxxx handlers. These are declared statically so * they work with static code transformers like Caja. */ _attachHandlers: function(inst) { var stepMonths = this._get(inst, "stepMonths"), id = "#" + inst.id.replace( /\\\\/g, "\\" ); inst.dpDiv.find("[data-handler]").map(function () { var handler = { prev: function () { $.datepicker._adjustDate(id, -stepMonths, "M"); }, next: function () { $.datepicker._adjustDate(id, +stepMonths, "M"); }, hide: function () { $.datepicker._hideDatepicker(); }, today: function () { $.datepicker._gotoToday(id); }, selectDay: function () { $.datepicker._selectDay(id, +this.getAttribute("data-month"), +this.getAttribute("data-year"), this); return false; }, selectMonth: function () { $.datepicker._selectMonthYear(id, this, "M"); return false; }, selectYear: function () { $.datepicker._selectMonthYear(id, this, "Y"); return false; } }; $(this).bind(this.getAttribute("data-event"), handler[this.getAttribute("data-handler")]); }); }, /* Generate the HTML for the current state of the date picker. */ _generateHTML: function(inst) { var maxDraw, prevText, prev, nextText, next, currentText, gotoDate, controls, buttonPanel, firstDay, showWeek, dayNames, dayNamesMin, monthNames, monthNamesShort, beforeShowDay, showOtherMonths, selectOtherMonths, defaultDate, html, dow, row, group, col, selectedDate, cornerClass, calender, thead, day, daysInMonth, leadDays, curRows, numRows, printDate, dRow, tbody, daySettings, otherMonth, unselectable, tempDate = new Date(), today = this._daylightSavingAdjust( new Date(tempDate.getFullYear(), tempDate.getMonth(), tempDate.getDate())), // clear time isRTL = this._get(inst, "isRTL"), showButtonPanel = this._get(inst, "showButtonPanel"), hideIfNoPrevNext = this._get(inst, "hideIfNoPrevNext"), navigationAsDateFormat = this._get(inst, "navigationAsDateFormat"), numMonths = this._getNumberOfMonths(inst), showCurrentAtPos = this._get(inst, "showCurrentAtPos"), stepMonths = this._get(inst, "stepMonths"), isMultiMonth = (numMonths[0] !== 1 || numMonths[1] !== 1), currentDate = this._daylightSavingAdjust((!inst.currentDay ? new Date(9999, 9, 9) : new Date(inst.currentYear, inst.currentMonth, inst.currentDay))), minDate = this._getMinMaxDate(inst, "min"), maxDate = this._getMinMaxDate(inst, "max"), drawMonth = inst.drawMonth - showCurrentAtPos, drawYear = inst.drawYear; if (drawMonth < 0) { drawMonth += 12; drawYear--; } if (maxDate) { maxDraw = this._daylightSavingAdjust(new Date(maxDate.getFullYear(), maxDate.getMonth() - (numMonths[0] * numMonths[1]) + 1, maxDate.getDate())); maxDraw = (minDate && maxDraw < minDate ? minDate : maxDraw); while (this._daylightSavingAdjust(new Date(drawYear, drawMonth, 1)) > maxDraw) { drawMonth--; if (drawMonth < 0) { drawMonth = 11; drawYear--; } } } inst.drawMonth = drawMonth; inst.drawYear = drawYear; prevText = this._get(inst, "prevText"); prevText = (!navigationAsDateFormat ? prevText : this.formatDate(prevText, this._daylightSavingAdjust(new Date(drawYear, drawMonth - stepMonths, 1)), this._getFormatConfig(inst))); prev = (this._canAdjustMonth(inst, -1, drawYear, drawMonth) ? "<a class='ui-datepicker-prev ui-corner-all' data-handler='prev' data-event='click'" + " title='" + prevText + "'><span class='ui-icon ui-icon-circle-triangle-" + ( isRTL ? "e" : "w") + "'>" + prevText + "</span></a>" : (hideIfNoPrevNext ? "" : "<a class='ui-datepicker-prev ui-corner-all ui-state-disabled' title='"+ prevText +"'><span class='ui-icon ui-icon-circle-triangle-" + ( isRTL ? "e" : "w") + "'>" + prevText + "</span></a>")); nextText = this._get(inst, "nextText"); nextText = (!navigationAsDateFormat ? nextText : this.formatDate(nextText, this._daylightSavingAdjust(new Date(drawYear, drawMonth + stepMonths, 1)), this._getFormatConfig(inst))); next = (this._canAdjustMonth(inst, +1, drawYear, drawMonth) ? "<a class='ui-datepicker-next ui-corner-all' data-handler='next' data-event='click'" + " title='" + nextText + "'><span class='ui-icon ui-icon-circle-triangle-" + ( isRTL ? "w" : "e") + "'>" + nextText + "</span></a>" : (hideIfNoPrevNext ? "" : "<a class='ui-datepicker-next ui-corner-all ui-state-disabled' title='"+ nextText + "'><span class='ui-icon ui-icon-circle-triangle-" + ( isRTL ? "w" : "e") + "'>" + nextText + "</span></a>")); currentText = this._get(inst, "currentText"); gotoDate = (this._get(inst, "gotoCurrent") && inst.currentDay ? currentDate : today); currentText = (!navigationAsDateFormat ? currentText : this.formatDate(currentText, gotoDate, this._getFormatConfig(inst))); controls = (!inst.inline ? "<button type='button' class='ui-datepicker-close ui-state-default ui-priority-primary ui-corner-all' data-handler='hide' data-event='click'>" + this._get(inst, "closeText") + "</button>" : ""); buttonPanel = (showButtonPanel) ? "<div class='ui-datepicker-buttonpane ui-widget-content'>" + (isRTL ? controls : "") + (this._isInRange(inst, gotoDate) ? "<button type='button' class='ui-datepicker-current ui-state-default ui-priority-secondary ui-corner-all' data-handler='today' data-event='click'" + ">" + currentText + "</button>" : "") + (isRTL ? "" : controls) + "</div>" : ""; firstDay = parseInt(this._get(inst, "firstDay"),10); firstDay = (isNaN(firstDay) ? 0 : firstDay); showWeek = this._get(inst, "showWeek"); dayNames = this._get(inst, "dayNames"); dayNamesMin = this._get(inst, "dayNamesMin"); monthNames = this._get(inst, "monthNames"); monthNamesShort = this._get(inst, "monthNamesShort"); beforeShowDay = this._get(inst, "beforeShowDay"); showOtherMonths = this._get(inst, "showOtherMonths"); selectOtherMonths = this._get(inst, "selectOtherMonths"); defaultDate = this._getDefaultDate(inst); html = ""; dow; for (row = 0; row < numMonths[0]; row++) { group = ""; this.maxRows = 4; for (col = 0; col < numMonths[1]; col++) { selectedDate = this._daylightSavingAdjust(new Date(drawYear, drawMonth, inst.selectedDay)); cornerClass = " ui-corner-all"; calender = ""; if (isMultiMonth) { calender += "<div class='ui-datepicker-group"; if (numMonths[1] > 1) { switch (col) { case 0: calender += " ui-datepicker-group-first"; cornerClass = " ui-corner-" + (isRTL ? "right" : "left"); break; case numMonths[1]-1: calender += " ui-datepicker-group-last"; cornerClass = " ui-corner-" + (isRTL ? "left" : "right"); break; default: calender += " ui-datepicker-group-middle"; cornerClass = ""; break; } } calender += "'>"; } calender += "<div class='ui-datepicker-header ui-widget-header ui-helper-clearfix" + cornerClass + "'>" + (/all|left/.test(cornerClass) && row === 0 ? (isRTL ? next : prev) : "") + (/all|right/.test(cornerClass) && row === 0 ? (isRTL ? prev : next) : "") + this._generateMonthYearHeader(inst, drawMonth, drawYear, minDate, maxDate, row > 0 || col > 0, monthNames, monthNamesShort) + // draw month headers "</div><table class='ui-datepicker-calendar'><thead>" + "<tr>"; thead = (showWeek ? "<th class='ui-datepicker-week-col'>" + this._get(inst, "weekHeader") + "</th>" : ""); for (dow = 0; dow < 7; dow++) { // days of the week day = (dow + firstDay) % 7; thead += "<th" + ((dow + firstDay + 6) % 7 >= 5 ? " class='ui-datepicker-week-end'" : "") + ">" + "<span title='" + dayNames[day] + "'>" + dayNamesMin[day] + "</span></th>"; } calender += thead + "</tr></thead><tbody>"; daysInMonth = this._getDaysInMonth(drawYear, drawMonth); if (drawYear === inst.selectedYear && drawMonth === inst.selectedMonth) { inst.selectedDay = Math.min(inst.selectedDay, daysInMonth); } leadDays = (this._getFirstDayOfMonth(drawYear, drawMonth) - firstDay + 7) % 7; curRows = Math.ceil((leadDays + daysInMonth) / 7); // calculate the number of rows to generate numRows = (isMultiMonth ? this.maxRows > curRows ? this.maxRows : curRows : curRows); //If multiple months, use the higher number of rows (see #7043) this.maxRows = numRows; printDate = this._daylightSavingAdjust(new Date(drawYear, drawMonth, 1 - leadDays)); for (dRow = 0; dRow < numRows; dRow++) { // create date picker rows calender += "<tr>"; tbody = (!showWeek ? "" : "<td class='ui-datepicker-week-col'>" + this._get(inst, "calculateWeek")(printDate) + "</td>"); for (dow = 0; dow < 7; dow++) { // create date picker days daySettings = (beforeShowDay ? beforeShowDay.apply((inst.input ? inst.input[0] : null), [printDate]) : [true, ""]); otherMonth = (printDate.getMonth() !== drawMonth); unselectable = (otherMonth && !selectOtherMonths) || !daySettings[0] || (minDate && printDate < minDate) || (maxDate && printDate > maxDate); tbody += "<td class='" + ((dow + firstDay + 6) % 7 >= 5 ? " ui-datepicker-week-end" : "") + // highlight weekends (otherMonth ? " ui-datepicker-other-month" : "") + // highlight days from other months ((printDate.getTime() === selectedDate.getTime() && drawMonth === inst.selectedMonth && inst._keyEvent) || // user pressed key (defaultDate.getTime() === printDate.getTime() && defaultDate.getTime() === selectedDate.getTime()) ? // or defaultDate is current printedDate and defaultDate is selectedDate " " + this._dayOverClass : "") + // highlight selected day (unselectable ? " " + this._unselectableClass + " ui-state-disabled": "") + // highlight unselectable days (otherMonth && !showOtherMonths ? "" : " " + daySettings[1] + // highlight custom dates (printDate.getTime() === currentDate.getTime() ? " " + this._currentClass : "") + // highlight selected day (printDate.getTime() === today.getTime() ? " ui-datepicker-today" : "")) + "'" + // highlight today (if different) ((!otherMonth || showOtherMonths) && daySettings[2] ? " title='" + daySettings[2].replace(/'/g, "&#39;") + "'" : "") + // cell title (unselectable ? "" : " data-handler='selectDay' data-event='click' data-month='" + printDate.getMonth() + "' data-year='" + printDate.getFullYear() + "'") + ">" + // actions (otherMonth && !showOtherMonths ? "&#xa0;" : // display for other months (unselectable ? "<span class='ui-state-default'>" + printDate.getDate() + "</span>" : "<a class='ui-state-default" + (printDate.getTime() === today.getTime() ? " ui-state-highlight" : "") + (printDate.getTime() === currentDate.getTime() ? " ui-state-active" : "") + // highlight selected day (otherMonth ? " ui-priority-secondary" : "") + // distinguish dates from other months "' href='#'>" + printDate.getDate() + "</a>")) + "</td>"; // display selectable date printDate.setDate(printDate.getDate() + 1); printDate = this._daylightSavingAdjust(printDate); } calender += tbody + "</tr>"; } drawMonth++; if (drawMonth > 11) { drawMonth = 0; drawYear++; } calender += "</tbody></table>" + (isMultiMonth ? "</div>" + ((numMonths[0] > 0 && col === numMonths[1]-1) ? "<div class='ui-datepicker-row-break'></div>" : "") : ""); group += calender; } html += group; } html += buttonPanel; inst._keyEvent = false; return html; }, /* Generate the month and year header. */ _generateMonthYearHeader: function(inst, drawMonth, drawYear, minDate, maxDate, secondary, monthNames, monthNamesShort) { var inMinYear, inMaxYear, month, years, thisYear, determineYear, year, endYear, changeMonth = this._get(inst, "changeMonth"), changeYear = this._get(inst, "changeYear"), showMonthAfterYear = this._get(inst, "showMonthAfterYear"), html = "<div class='ui-datepicker-title'>", monthHtml = ""; // month selection if (secondary || !changeMonth) { monthHtml += "<span class='ui-datepicker-month'>" + monthNames[drawMonth] + "</span>"; } else { inMinYear = (minDate && minDate.getFullYear() === drawYear); inMaxYear = (maxDate && maxDate.getFullYear() === drawYear); monthHtml += "<select class='ui-datepicker-month' data-handler='selectMonth' data-event='change'>"; for ( month = 0; month < 12; month++) { if ((!inMinYear || month >= minDate.getMonth()) && (!inMaxYear || month <= maxDate.getMonth())) { monthHtml += "<option value='" + month + "'" + (month === drawMonth ? " selected='selected'" : "") + ">" + monthNamesShort[month] + "</option>"; } } monthHtml += "</select>"; } if (!showMonthAfterYear) { html += monthHtml + (secondary || !(changeMonth && changeYear) ? "&#xa0;" : ""); } // year selection if ( !inst.yearshtml ) { inst.yearshtml = ""; if (secondary || !changeYear) { html += "<span class='ui-datepicker-year'>" + drawYear + "</span>"; } else { // determine range of years to display years = this._get(inst, "yearRange").split(":"); thisYear = new Date().getFullYear(); determineYear = function(value) { var year = (value.match(/c[+\-].*/) ? drawYear + parseInt(value.substring(1), 10) : (value.match(/[+\-].*/) ? thisYear + parseInt(value, 10) : parseInt(value, 10))); return (isNaN(year) ? thisYear : year); }; year = determineYear(years[0]); endYear = Math.max(year, determineYear(years[1] || "")); year = (minDate ? Math.max(year, minDate.getFullYear()) : year); endYear = (maxDate ? Math.min(endYear, maxDate.getFullYear()) : endYear); inst.yearshtml += "<select class='ui-datepicker-year' data-handler='selectYear' data-event='change'>"; for (; year <= endYear; year++) { inst.yearshtml += "<option value='" + year + "'" + (year === drawYear ? " selected='selected'" : "") + ">" + year + "</option>"; } inst.yearshtml += "</select>"; html += inst.yearshtml; inst.yearshtml = null; } } html += this._get(inst, "yearSuffix"); if (showMonthAfterYear) { html += (secondary || !(changeMonth && changeYear) ? "&#xa0;" : "") + monthHtml; } html += "</div>"; // Close datepicker_header return html; }, /* Adjust one of the date sub-fields. */ _adjustInstDate: function(inst, offset, period) { var year = inst.drawYear + (period === "Y" ? offset : 0), month = inst.drawMonth + (period === "M" ? offset : 0), day = Math.min(inst.selectedDay, this._getDaysInMonth(year, month)) + (period === "D" ? offset : 0), date = this._restrictMinMax(inst, this._daylightSavingAdjust(new Date(year, month, day))); inst.selectedDay = date.getDate(); inst.drawMonth = inst.selectedMonth = date.getMonth(); inst.drawYear = inst.selectedYear = date.getFullYear(); if (period === "M" || period === "Y") { this._notifyChange(inst); } }, /* Ensure a date is within any min/max bounds. */ _restrictMinMax: function(inst, date) { var minDate = this._getMinMaxDate(inst, "min"), maxDate = this._getMinMaxDate(inst, "max"), newDate = (minDate && date < minDate ? minDate : date); return (maxDate && newDate > maxDate ? maxDate : newDate); }, /* Notify change of month/year. */ _notifyChange: function(inst) { var onChange = this._get(inst, "onChangeMonthYear"); if (onChange) { onChange.apply((inst.input ? inst.input[0] : null), [inst.selectedYear, inst.selectedMonth + 1, inst]); } }, /* Determine the number of months to show. */ _getNumberOfMonths: function(inst) { var numMonths = this._get(inst, "numberOfMonths"); return (numMonths == null ? [1, 1] : (typeof numMonths === "number" ? [1, numMonths] : numMonths)); }, /* Determine the current maximum date - ensure no time components are set. */ _getMinMaxDate: function(inst, minMax) { return this._determineDate(inst, this._get(inst, minMax + "Date"), null); }, /* Find the number of days in a given month. */ _getDaysInMonth: function(year, month) { return 32 - this._daylightSavingAdjust(new Date(year, month, 32)).getDate(); }, /* Find the day of the week of the first of a month. */ _getFirstDayOfMonth: function(year, month) { return new Date(year, month, 1).getDay(); }, /* Determines if we should allow a "next/prev" month display change. */ _canAdjustMonth: function(inst, offset, curYear, curMonth) { var numMonths = this._getNumberOfMonths(inst), date = this._daylightSavingAdjust(new Date(curYear, curMonth + (offset < 0 ? offset : numMonths[0] * numMonths[1]), 1)); if (offset < 0) { date.setDate(this._getDaysInMonth(date.getFullYear(), date.getMonth())); } return this._isInRange(inst, date); }, /* Is the given date in the accepted range? */ _isInRange: function(inst, date) { var yearSplit, currentYear, minDate = this._getMinMaxDate(inst, "min"), maxDate = this._getMinMaxDate(inst, "max"), minYear = null, maxYear = null, years = this._get(inst, "yearRange"); if (years){ yearSplit = years.split(":"); currentYear = new Date().getFullYear(); minYear = parseInt(yearSplit[0], 10); maxYear = parseInt(yearSplit[1], 10); if ( yearSplit[0].match(/[+\-].*/) ) { minYear += currentYear; } if ( yearSplit[1].match(/[+\-].*/) ) { maxYear += currentYear; } } return ((!minDate || date.getTime() >= minDate.getTime()) && (!maxDate || date.getTime() <= maxDate.getTime()) && (!minYear || date.getFullYear() >= minYear) && (!maxYear || date.getFullYear() <= maxYear)); }, /* Provide the configuration settings for formatting/parsing. */ _getFormatConfig: function(inst) { var shortYearCutoff = this._get(inst, "shortYearCutoff"); shortYearCutoff = (typeof shortYearCutoff !== "string" ? shortYearCutoff : new Date().getFullYear() % 100 + parseInt(shortYearCutoff, 10)); return {shortYearCutoff: shortYearCutoff, dayNamesShort: this._get(inst, "dayNamesShort"), dayNames: this._get(inst, "dayNames"), monthNamesShort: this._get(inst, "monthNamesShort"), monthNames: this._get(inst, "monthNames")}; }, /* Format the given date for display. */ _formatDate: function(inst, day, month, year) { if (!day) { inst.currentDay = inst.selectedDay; inst.currentMonth = inst.selectedMonth; inst.currentYear = inst.selectedYear; } var date = (day ? (typeof day === "object" ? day : this._daylightSavingAdjust(new Date(year, month, day))) : this._daylightSavingAdjust(new Date(inst.currentYear, inst.currentMonth, inst.currentDay))); return this.formatDate(this._get(inst, "dateFormat"), date, this._getFormatConfig(inst)); } }); /* * Bind hover events for datepicker elements. * Done via delegate so the binding only occurs once in the lifetime of the parent div. * Global instActive, set by _updateDatepicker allows the handlers to find their way back to the active picker. */ function bindHover(dpDiv) { var selector = "button, .ui-datepicker-prev, .ui-datepicker-next, .ui-datepicker-calendar td a"; return dpDiv.delegate(selector, "mouseout", function() { $(this).removeClass("ui-state-hover"); if (this.className.indexOf("ui-datepicker-prev") !== -1) { $(this).removeClass("ui-datepicker-prev-hover"); } if (this.className.indexOf("ui-datepicker-next") !== -1) { $(this).removeClass("ui-datepicker-next-hover"); } }) .delegate(selector, "mouseover", function(){ if (!$.datepicker._isDisabledDatepicker( instActive.inline ? dpDiv.parent()[0] : instActive.input[0])) { $(this).parents(".ui-datepicker-calendar").find("a").removeClass("ui-state-hover"); $(this).addClass("ui-state-hover"); if (this.className.indexOf("ui-datepicker-prev") !== -1) { $(this).addClass("ui-datepicker-prev-hover"); } if (this.className.indexOf("ui-datepicker-next") !== -1) { $(this).addClass("ui-datepicker-next-hover"); } } }); } /* jQuery extend now ignores nulls! */ function extendRemove(target, props) { $.extend(target, props); for (var name in props) { if (props[name] == null) { target[name] = props[name]; } } return target; } /* Invoke the datepicker functionality. @param options string - a command, optionally followed by additional parameters or Object - settings for attaching new datepicker functionality @return jQuery object */ $.fn.datepicker = function(options){ /* Verify an empty collection wasn't passed - Fixes #6976 */ if ( !this.length ) { return this; } /* Initialise the date picker. */ if (!$.datepicker.initialized) { $(document).mousedown($.datepicker._checkExternalClick); $.datepicker.initialized = true; } /* Append datepicker main container to body if not exist. */ if ($("#"+$.datepicker._mainDivId).length === 0) { $("body").append($.datepicker.dpDiv); } var otherArgs = Array.prototype.slice.call(arguments, 1); if (typeof options === "string" && (options === "isDisabled" || options === "getDate" || options === "widget")) { return $.datepicker["_" + options + "Datepicker"]. apply($.datepicker, [this[0]].concat(otherArgs)); } if (options === "option" && arguments.length === 2 && typeof arguments[1] === "string") { return $.datepicker["_" + options + "Datepicker"]. apply($.datepicker, [this[0]].concat(otherArgs)); } return this.each(function() { typeof options === "string" ? $.datepicker["_" + options + "Datepicker"]. apply($.datepicker, [this].concat(otherArgs)) : $.datepicker._attachDatepicker(this, options); }); }; $.datepicker = new Datepicker(); // singleton instance $.datepicker.initialized = false; $.datepicker.uuid = new Date().getTime(); $.datepicker.version = "1.10.3"; })(jQuery); (function( $, undefined ) { var sizeRelatedOptions = { buttons: true, height: true, maxHeight: true, maxWidth: true, minHeight: true, minWidth: true, width: true }, resizableRelatedOptions = { maxHeight: true, maxWidth: true, minHeight: true, minWidth: true }; $.widget( "ui.dialog", { version: "1.10.3", options: { appendTo: "body", autoOpen: true, buttons: [], closeOnEscape: true, closeText: "close", dialogClass: "", draggable: true, hide: null, height: "auto", maxHeight: null, maxWidth: null, minHeight: 150, minWidth: 150, modal: false, position: { my: "center", at: "center", of: window, collision: "fit", // Ensure the titlebar is always visible using: function( pos ) { var topOffset = $( this ).css( pos ).offset().top; if ( topOffset < 0 ) { $( this ).css( "top", pos.top - topOffset ); } } }, resizable: true, show: null, title: null, width: 300, // callbacks beforeClose: null, close: null, drag: null, dragStart: null, dragStop: null, focus: null, open: null, resize: null, resizeStart: null, resizeStop: null }, _create: function() { this.originalCss = { display: this.element[0].style.display, width: this.element[0].style.width, minHeight: this.element[0].style.minHeight, maxHeight: this.element[0].style.maxHeight, height: this.element[0].style.height }; this.originalPosition = { parent: this.element.parent(), index: this.element.parent().children().index( this.element ) }; this.originalTitle = this.element.attr("title"); this.options.title = this.options.title || this.originalTitle; this._createWrapper(); this.element .show() .removeAttr("title") .addClass("ui-dialog-content ui-widget-content") .appendTo( this.uiDialog ); this._createTitlebar(); this._createButtonPane(); if ( this.options.draggable && $.fn.draggable ) { this._makeDraggable(); } if ( this.options.resizable && $.fn.resizable ) { this._makeResizable(); } this._isOpen = false; }, _init: function() { if ( this.options.autoOpen ) { this.open(); } }, _appendTo: function() { var element = this.options.appendTo; if ( element && (element.jquery || element.nodeType) ) { return $( element ); } return this.document.find( element || "body" ).eq( 0 ); }, _destroy: function() { var next, originalPosition = this.originalPosition; this._destroyOverlay(); this.element .removeUniqueId() .removeClass("ui-dialog-content ui-widget-content") .css( this.originalCss ) // Without detaching first, the following becomes really slow .detach(); this.uiDialog.stop( true, true ).remove(); if ( this.originalTitle ) { this.element.attr( "title", this.originalTitle ); } next = originalPosition.parent.children().eq( originalPosition.index ); // Don't try to place the dialog next to itself (#8613) if ( next.length && next[0] !== this.element[0] ) { next.before( this.element ); } else { originalPosition.parent.append( this.element ); } }, widget: function() { return this.uiDialog; }, disable: $.noop, enable: $.noop, close: function( event ) { var that = this; if ( !this._isOpen || this._trigger( "beforeClose", event ) === false ) { return; } this._isOpen = false; this._destroyOverlay(); if ( !this.opener.filter(":focusable").focus().length ) { // Hiding a focused element doesn't trigger blur in WebKit // so in case we have nothing to focus on, explicitly blur the active element // https://bugs.webkit.org/show_bug.cgi?id=47182 $( this.document[0].activeElement ).blur(); } this._hide( this.uiDialog, this.options.hide, function() { that._trigger( "close", event ); }); }, isOpen: function() { return this._isOpen; }, moveToTop: function() { this._moveToTop(); }, _moveToTop: function( event, silent ) { var moved = !!this.uiDialog.nextAll(":visible").insertBefore( this.uiDialog ).length; if ( moved && !silent ) { this._trigger( "focus", event ); } return moved; }, open: function() { var that = this; if ( this._isOpen ) { if ( this._moveToTop() ) { this._focusTabbable(); } return; } this._isOpen = true; this.opener = $( this.document[0].activeElement ); this._size(); this._position(); this._createOverlay(); this._moveToTop( null, true ); this._show( this.uiDialog, this.options.show, function() { that._focusTabbable(); that._trigger("focus"); }); this._trigger("open"); }, _focusTabbable: function() { // Set focus to the first match: // 1. First element inside the dialog matching [autofocus] // 2. Tabbable element inside the content element // 3. Tabbable element inside the buttonpane // 4. The close button // 5. The dialog itself var hasFocus = this.element.find("[autofocus]"); if ( !hasFocus.length ) { hasFocus = this.element.find(":tabbable"); } if ( !hasFocus.length ) { hasFocus = this.uiDialogButtonPane.find(":tabbable"); } if ( !hasFocus.length ) { hasFocus = this.uiDialogTitlebarClose.filter(":tabbable"); } if ( !hasFocus.length ) { hasFocus = this.uiDialog; } hasFocus.eq( 0 ).focus(); }, _keepFocus: function( event ) { function checkFocus() { var activeElement = this.document[0].activeElement, isActive = this.uiDialog[0] === activeElement || $.contains( this.uiDialog[0], activeElement ); if ( !isActive ) { this._focusTabbable(); } } event.preventDefault(); checkFocus.call( this ); // support: IE // IE <= 8 doesn't prevent moving focus even with event.preventDefault() // so we check again later this._delay( checkFocus ); }, _createWrapper: function() { this.uiDialog = $("<div>") .addClass( "ui-dialog ui-widget ui-widget-content ui-corner-all ui-front " + this.options.dialogClass ) .hide() .attr({ // Setting tabIndex makes the div focusable tabIndex: -1, role: "dialog" }) .appendTo( this._appendTo() ); this._on( this.uiDialog, { keydown: function( event ) { if ( this.options.closeOnEscape && !event.isDefaultPrevented() && event.keyCode && event.keyCode === $.ui.keyCode.ESCAPE ) { event.preventDefault(); this.close( event ); return; } // prevent tabbing out of dialogs if ( event.keyCode !== $.ui.keyCode.TAB ) { return; } var tabbables = this.uiDialog.find(":tabbable"), first = tabbables.filter(":first"), last = tabbables.filter(":last"); if ( ( event.target === last[0] || event.target === this.uiDialog[0] ) && !event.shiftKey ) { first.focus( 1 ); event.preventDefault(); } else if ( ( event.target === first[0] || event.target === this.uiDialog[0] ) && event.shiftKey ) { last.focus( 1 ); event.preventDefault(); } }, mousedown: function( event ) { if ( this._moveToTop( event ) ) { this._focusTabbable(); } } }); // We assume that any existing aria-describedby attribute means // that the dialog content is marked up properly // otherwise we brute force the content as the description if ( !this.element.find("[aria-describedby]").length ) { this.uiDialog.attr({ "aria-describedby": this.element.uniqueId().attr("id") }); } }, _createTitlebar: function() { var uiDialogTitle; this.uiDialogTitlebar = $("<div>") .addClass("ui-dialog-titlebar ui-widget-header ui-corner-all ui-helper-clearfix") .prependTo( this.uiDialog ); this._on( this.uiDialogTitlebar, { mousedown: function( event ) { // Don't prevent click on close button (#8838) // Focusing a dialog that is partially scrolled out of view // causes the browser to scroll it into view, preventing the click event if ( !$( event.target ).closest(".ui-dialog-titlebar-close") ) { // Dialog isn't getting focus when dragging (#8063) this.uiDialog.focus(); } } }); this.uiDialogTitlebarClose = $("<button></button>") .button({ label: this.options.closeText, icons: { primary: "ui-icon-closethick" }, text: false }) .addClass("ui-dialog-titlebar-close") .appendTo( this.uiDialogTitlebar ); this._on( this.uiDialogTitlebarClose, { click: function( event ) { event.preventDefault(); this.close( event ); } }); uiDialogTitle = $("<span>") .uniqueId() .addClass("ui-dialog-title") .prependTo( this.uiDialogTitlebar ); this._title( uiDialogTitle ); this.uiDialog.attr({ "aria-labelledby": uiDialogTitle.attr("id") }); }, _title: function( title ) { if ( !this.options.title ) { title.html("&#160;"); } title.text( this.options.title ); }, _createButtonPane: function() { this.uiDialogButtonPane = $("<div>") .addClass("ui-dialog-buttonpane ui-widget-content ui-helper-clearfix"); this.uiButtonSet = $("<div>") .addClass("ui-dialog-buttonset") .appendTo( this.uiDialogButtonPane ); this._createButtons(); }, _createButtons: function() { var that = this, buttons = this.options.buttons; // if we already have a button pane, remove it this.uiDialogButtonPane.remove(); this.uiButtonSet.empty(); if ( $.isEmptyObject( buttons ) || ($.isArray( buttons ) && !buttons.length) ) { this.uiDialog.removeClass("ui-dialog-buttons"); return; } $.each( buttons, function( name, props ) { var click, buttonOptions; props = $.isFunction( props ) ? { click: props, text: name } : props; // Default to a non-submitting button props = $.extend( { type: "button" }, props ); // Change the context for the click callback to be the main element click = props.click; props.click = function() { click.apply( that.element[0], arguments ); }; buttonOptions = { icons: props.icons, text: props.showText }; delete props.icons; delete props.showText; $( "<button></button>", props ) .button( buttonOptions ) .appendTo( that.uiButtonSet ); }); this.uiDialog.addClass("ui-dialog-buttons"); this.uiDialogButtonPane.appendTo( this.uiDialog ); }, _makeDraggable: function() { var that = this, options = this.options; function filteredUi( ui ) { return { position: ui.position, offset: ui.offset }; } this.uiDialog.draggable({ cancel: ".ui-dialog-content, .ui-dialog-titlebar-close", handle: ".ui-dialog-titlebar", containment: "document", start: function( event, ui ) { $( this ).addClass("ui-dialog-dragging"); that._blockFrames(); that._trigger( "dragStart", event, filteredUi( ui ) ); }, drag: function( event, ui ) { that._trigger( "drag", event, filteredUi( ui ) ); }, stop: function( event, ui ) { options.position = [ ui.position.left - that.document.scrollLeft(), ui.position.top - that.document.scrollTop() ]; $( this ).removeClass("ui-dialog-dragging"); that._unblockFrames(); that._trigger( "dragStop", event, filteredUi( ui ) ); } }); }, _makeResizable: function() { var that = this, options = this.options, handles = options.resizable, // .ui-resizable has position: relative defined in the stylesheet // but dialogs have to use absolute or fixed positioning position = this.uiDialog.css("position"), resizeHandles = typeof handles === "string" ? handles : "n,e,s,w,se,sw,ne,nw"; function filteredUi( ui ) { return { originalPosition: ui.originalPosition, originalSize: ui.originalSize, position: ui.position, size: ui.size }; } this.uiDialog.resizable({ cancel: ".ui-dialog-content", containment: "document", alsoResize: this.element, maxWidth: options.maxWidth, maxHeight: options.maxHeight, minWidth: options.minWidth, minHeight: this._minHeight(), handles: resizeHandles, start: function( event, ui ) { $( this ).addClass("ui-dialog-resizing"); that._blockFrames(); that._trigger( "resizeStart", event, filteredUi( ui ) ); }, resize: function( event, ui ) { that._trigger( "resize", event, filteredUi( ui ) ); }, stop: function( event, ui ) { options.height = $( this ).height(); options.width = $( this ).width(); $( this ).removeClass("ui-dialog-resizing"); that._unblockFrames(); that._trigger( "resizeStop", event, filteredUi( ui ) ); } }) .css( "position", position ); }, _minHeight: function() { var options = this.options; return options.height === "auto" ? options.minHeight : Math.min( options.minHeight, options.height ); }, _position: function() { // Need to show the dialog to get the actual offset in the position plugin var isVisible = this.uiDialog.is(":visible"); if ( !isVisible ) { this.uiDialog.show(); } this.uiDialog.position( this.options.position ); if ( !isVisible ) { this.uiDialog.hide(); } }, _setOptions: function( options ) { var that = this, resize = false, resizableOptions = {}; $.each( options, function( key, value ) { that._setOption( key, value ); if ( key in sizeRelatedOptions ) { resize = true; } if ( key in resizableRelatedOptions ) { resizableOptions[ key ] = value; } }); if ( resize ) { this._size(); this._position(); } if ( this.uiDialog.is(":data(ui-resizable)") ) { this.uiDialog.resizable( "option", resizableOptions ); } }, _setOption: function( key, value ) { /*jshint maxcomplexity:15*/ var isDraggable, isResizable, uiDialog = this.uiDialog; if ( key === "dialogClass" ) { uiDialog .removeClass( this.options.dialogClass ) .addClass( value ); } if ( key === "disabled" ) { return; } this._super( key, value ); if ( key === "appendTo" ) { this.uiDialog.appendTo( this._appendTo() ); } if ( key === "buttons" ) { this._createButtons(); } if ( key === "closeText" ) { this.uiDialogTitlebarClose.button({ // Ensure that we always pass a string label: "" + value }); } if ( key === "draggable" ) { isDraggable = uiDialog.is(":data(ui-draggable)"); if ( isDraggable && !value ) { uiDialog.draggable("destroy"); } if ( !isDraggable && value ) { this._makeDraggable(); } } if ( key === "position" ) { this._position(); } if ( key === "resizable" ) { // currently resizable, becoming non-resizable isResizable = uiDialog.is(":data(ui-resizable)"); if ( isResizable && !value ) { uiDialog.resizable("destroy"); } // currently resizable, changing handles if ( isResizable && typeof value === "string" ) { uiDialog.resizable( "option", "handles", value ); } // currently non-resizable, becoming resizable if ( !isResizable && value !== false ) { this._makeResizable(); } } if ( key === "title" ) { this._title( this.uiDialogTitlebar.find(".ui-dialog-title") ); } }, _size: function() { // If the user has resized the dialog, the .ui-dialog and .ui-dialog-content // divs will both have width and height set, so we need to reset them var nonContentHeight, minContentHeight, maxContentHeight, options = this.options; // Reset content sizing this.element.show().css({ width: "auto", minHeight: 0, maxHeight: "none", height: 0 }); if ( options.minWidth > options.width ) { options.width = options.minWidth; } // reset wrapper sizing // determine the height of all the non-content elements nonContentHeight = this.uiDialog.css({ height: "auto", width: options.width }) .outerHeight(); minContentHeight = Math.max( 0, options.minHeight - nonContentHeight ); maxContentHeight = typeof options.maxHeight === "number" ? Math.max( 0, options.maxHeight - nonContentHeight ) : "none"; if ( options.height === "auto" ) { this.element.css({ minHeight: minContentHeight, maxHeight: maxContentHeight, height: "auto" }); } else { this.element.height( Math.max( 0, options.height - nonContentHeight ) ); } if (this.uiDialog.is(":data(ui-resizable)") ) { this.uiDialog.resizable( "option", "minHeight", this._minHeight() ); } }, _blockFrames: function() { this.iframeBlocks = this.document.find( "iframe" ).map(function() { var iframe = $( this ); return $( "<div>" ) .css({ position: "absolute", width: iframe.outerWidth(), height: iframe.outerHeight() }) .appendTo( iframe.parent() ) .offset( iframe.offset() )[0]; }); }, _unblockFrames: function() { if ( this.iframeBlocks ) { this.iframeBlocks.remove(); delete this.iframeBlocks; } }, _allowInteraction: function( event ) { if ( $( event.target ).closest(".ui-dialog").length ) { return true; } // TODO: Remove hack when datepicker implements // the .ui-front logic (#8989) return !!$( event.target ).closest(".ui-datepicker").length; }, _createOverlay: function() { if ( !this.options.modal ) { return; } var that = this, widgetFullName = this.widgetFullName; if ( !$.ui.dialog.overlayInstances ) { // Prevent use of anchors and inputs. // We use a delay in case the overlay is created from an // event that we're going to be cancelling. (#2804) this._delay(function() { // Handle .dialog().dialog("close") (#4065) if ( $.ui.dialog.overlayInstances ) { this.document.bind( "focusin.dialog", function( event ) { if ( !that._allowInteraction( event ) ) { event.preventDefault(); $(".ui-dialog:visible:last .ui-dialog-content") .data( widgetFullName )._focusTabbable(); } }); } }); } this.overlay = $("<div>") .addClass("ui-widget-overlay ui-front") .appendTo( this._appendTo() ); this._on( this.overlay, { mousedown: "_keepFocus" }); $.ui.dialog.overlayInstances++; }, _destroyOverlay: function() { if ( !this.options.modal ) { return; } if ( this.overlay ) { $.ui.dialog.overlayInstances--; if ( !$.ui.dialog.overlayInstances ) { this.document.unbind( "focusin.dialog" ); } this.overlay.remove(); this.overlay = null; } } }); $.ui.dialog.overlayInstances = 0; // DEPRECATED if ( $.uiBackCompat !== false ) { // position option with array notation // just override with old implementation $.widget( "ui.dialog", $.ui.dialog, { _position: function() { var position = this.options.position, myAt = [], offset = [ 0, 0 ], isVisible; if ( position ) { if ( typeof position === "string" || (typeof position === "object" && "0" in position ) ) { myAt = position.split ? position.split(" ") : [ position[0], position[1] ]; if ( myAt.length === 1 ) { myAt[1] = myAt[0]; } $.each( [ "left", "top" ], function( i, offsetPosition ) { if ( +myAt[ i ] === myAt[ i ] ) { offset[ i ] = myAt[ i ]; myAt[ i ] = offsetPosition; } }); position = { my: myAt[0] + (offset[0] < 0 ? offset[0] : "+" + offset[0]) + " " + myAt[1] + (offset[1] < 0 ? offset[1] : "+" + offset[1]), at: myAt.join(" ") }; } position = $.extend( {}, $.ui.dialog.prototype.options.position, position ); } else { position = $.ui.dialog.prototype.options.position; } // need to show the dialog to get the actual offset in the position plugin isVisible = this.uiDialog.is(":visible"); if ( !isVisible ) { this.uiDialog.show(); } this.uiDialog.position( position ); if ( !isVisible ) { this.uiDialog.hide(); } } }); } }( jQuery ) ); (function( $, undefined ) { $.widget( "ui.menu", { version: "1.10.3", defaultElement: "<ul>", delay: 300, options: { icons: { submenu: "ui-icon-carat-1-e" }, menus: "ul", position: { my: "left top", at: "right top" }, role: "menu", // callbacks blur: null, focus: null, select: null }, _create: function() { this.activeMenu = this.element; // flag used to prevent firing of the click handler // as the event bubbles up through nested menus this.mouseHandled = false; this.element .uniqueId() .addClass( "ui-menu ui-widget ui-widget-content ui-corner-all" ) .toggleClass( "ui-menu-icons", !!this.element.find( ".ui-icon" ).length ) .attr({ role: this.options.role, tabIndex: 0 }) // need to catch all clicks on disabled menu // not possible through _on .bind( "click" + this.eventNamespace, $.proxy(function( event ) { if ( this.options.disabled ) { event.preventDefault(); } }, this )); if ( this.options.disabled ) { this.element .addClass( "ui-state-disabled" ) .attr( "aria-disabled", "true" ); } this._on({ // Prevent focus from sticking to links inside menu after clicking // them (focus should always stay on UL during navigation). "mousedown .ui-menu-item > a": function( event ) { event.preventDefault(); }, "click .ui-state-disabled > a": function( event ) { event.preventDefault(); }, "click .ui-menu-item:has(a)": function( event ) { var target = $( event.target ).closest( ".ui-menu-item" ); if ( !this.mouseHandled && target.not( ".ui-state-disabled" ).length ) { this.mouseHandled = true; this.select( event ); // Open submenu on click if ( target.has( ".ui-menu" ).length ) { this.expand( event ); } else if ( !this.element.is( ":focus" ) ) { // Redirect focus to the menu this.element.trigger( "focus", [ true ] ); // If the active item is on the top level, let it stay active. // Otherwise, blur the active item since it is no longer visible. if ( this.active && this.active.parents( ".ui-menu" ).length === 1 ) { clearTimeout( this.timer ); } } } }, "mouseenter .ui-menu-item": function( event ) { var target = $( event.currentTarget ); // Remove ui-state-active class from siblings of the newly focused menu item // to avoid a jump caused by adjacent elements both having a class with a border target.siblings().children( ".ui-state-active" ).removeClass( "ui-state-active" ); this.focus( event, target ); }, mouseleave: "collapseAll", "mouseleave .ui-menu": "collapseAll", focus: function( event, keepActiveItem ) { // If there's already an active item, keep it active // If not, activate the first item var item = this.active || this.element.children( ".ui-menu-item" ).eq( 0 ); if ( !keepActiveItem ) { this.focus( event, item ); } }, blur: function( event ) { this._delay(function() { if ( !$.contains( this.element[0], this.document[0].activeElement ) ) { this.collapseAll( event ); } }); }, keydown: "_keydown" }); this.refresh(); // Clicks outside of a menu collapse any open menus this._on( this.document, { click: function( event ) { if ( !$( event.target ).closest( ".ui-menu" ).length ) { this.collapseAll( event ); } // Reset the mouseHandled flag this.mouseHandled = false; } }); }, _destroy: function() { // Destroy (sub)menus this.element .removeAttr( "aria-activedescendant" ) .find( ".ui-menu" ).addBack() .removeClass( "ui-menu ui-widget ui-widget-content ui-corner-all ui-menu-icons" ) .removeAttr( "role" ) .removeAttr( "tabIndex" ) .removeAttr( "aria-labelledby" ) .removeAttr( "aria-expanded" ) .removeAttr( "aria-hidden" ) .removeAttr( "aria-disabled" ) .removeUniqueId() .show(); // Destroy menu items this.element.find( ".ui-menu-item" ) .removeClass( "ui-menu-item" ) .removeAttr( "role" ) .removeAttr( "aria-disabled" ) .children( "a" ) .removeUniqueId() .removeClass( "ui-corner-all ui-state-hover" ) .removeAttr( "tabIndex" ) .removeAttr( "role" ) .removeAttr( "aria-haspopup" ) .children().each( function() { var elem = $( this ); if ( elem.data( "ui-menu-submenu-carat" ) ) { elem.remove(); } }); // Destroy menu dividers this.element.find( ".ui-menu-divider" ).removeClass( "ui-menu-divider ui-widget-content" ); }, _keydown: function( event ) { /*jshint maxcomplexity:20*/ var match, prev, character, skip, regex, preventDefault = true; function escape( value ) { return value.replace( /[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&" ); } switch ( event.keyCode ) { case $.ui.keyCode.PAGE_UP: this.previousPage( event ); break; case $.ui.keyCode.PAGE_DOWN: this.nextPage( event ); break; case $.ui.keyCode.HOME: this._move( "first", "first", event ); break; case $.ui.keyCode.END: this._move( "last", "last", event ); break; case $.ui.keyCode.UP: this.previous( event ); break; case $.ui.keyCode.DOWN: this.next( event ); break; case $.ui.keyCode.LEFT: this.collapse( event ); break; case $.ui.keyCode.RIGHT: if ( this.active && !this.active.is( ".ui-state-disabled" ) ) { this.expand( event ); } break; case $.ui.keyCode.ENTER: case $.ui.keyCode.SPACE: this._activate( event ); break; case $.ui.keyCode.ESCAPE: this.collapse( event ); break; default: preventDefault = false; prev = this.previousFilter || ""; character = String.fromCharCode( event.keyCode ); skip = false; clearTimeout( this.filterTimer ); if ( character === prev ) { skip = true; } else { character = prev + character; } regex = new RegExp( "^" + escape( character ), "i" ); match = this.activeMenu.children( ".ui-menu-item" ).filter(function() { return regex.test( $( this ).children( "a" ).text() ); }); match = skip && match.index( this.active.next() ) !== -1 ? this.active.nextAll( ".ui-menu-item" ) : match; // If no matches on the current filter, reset to the last character pressed // to move down the menu to the first item that starts with that character if ( !match.length ) { character = String.fromCharCode( event.keyCode ); regex = new RegExp( "^" + escape( character ), "i" ); match = this.activeMenu.children( ".ui-menu-item" ).filter(function() { return regex.test( $( this ).children( "a" ).text() ); }); } if ( match.length ) { this.focus( event, match ); if ( match.length > 1 ) { this.previousFilter = character; this.filterTimer = this._delay(function() { delete this.previousFilter; }, 1000 ); } else { delete this.previousFilter; } } else { delete this.previousFilter; } } if ( preventDefault ) { event.preventDefault(); } }, _activate: function( event ) { if ( !this.active.is( ".ui-state-disabled" ) ) { if ( this.active.children( "a[aria-haspopup='true']" ).length ) { this.expand( event ); } else { this.select( event ); } } }, refresh: function() { var menus, icon = this.options.icons.submenu, submenus = this.element.find( this.options.menus ); // Initialize nested menus submenus.filter( ":not(.ui-menu)" ) .addClass( "ui-menu ui-widget ui-widget-content ui-corner-all" ) .hide() .attr({ role: this.options.role, "aria-hidden": "true", "aria-expanded": "false" }) .each(function() { var menu = $( this ), item = menu.prev( "a" ), submenuCarat = $( "<span>" ) .addClass( "ui-menu-icon ui-icon " + icon ) .data( "ui-menu-submenu-carat", true ); item .attr( "aria-haspopup", "true" ) .prepend( submenuCarat ); menu.attr( "aria-labelledby", item.attr( "id" ) ); }); menus = submenus.add( this.element ); // Don't refresh list items that are already adapted menus.children( ":not(.ui-menu-item):has(a)" ) .addClass( "ui-menu-item" ) .attr( "role", "presentation" ) .children( "a" ) .uniqueId() .addClass( "ui-corner-all" ) .attr({ tabIndex: -1, role: this._itemRole() }); // Initialize unlinked menu-items containing spaces and/or dashes only as dividers menus.children( ":not(.ui-menu-item)" ).each(function() { var item = $( this ); // hyphen, em dash, en dash if ( !/[^\-\u2014\u2013\s]/.test( item.text() ) ) { item.addClass( "ui-widget-content ui-menu-divider" ); } }); // Add aria-disabled attribute to any disabled menu item menus.children( ".ui-state-disabled" ).attr( "aria-disabled", "true" ); // If the active item has been removed, blur the menu if ( this.active && !$.contains( this.element[ 0 ], this.active[ 0 ] ) ) { this.blur(); } }, _itemRole: function() { return { menu: "menuitem", listbox: "option" }[ this.options.role ]; }, _setOption: function( key, value ) { if ( key === "icons" ) { this.element.find( ".ui-menu-icon" ) .removeClass( this.options.icons.submenu ) .addClass( value.submenu ); } this._super( key, value ); }, focus: function( event, item ) { var nested, focused; this.blur( event, event && event.type === "focus" ); this._scrollIntoView( item ); this.active = item.first(); focused = this.active.children( "a" ).addClass( "ui-state-focus" ); // Only update aria-activedescendant if there's a role // otherwise we assume focus is managed elsewhere if ( this.options.role ) { this.element.attr( "aria-activedescendant", focused.attr( "id" ) ); } // Highlight active parent menu item, if any this.active .parent() .closest( ".ui-menu-item" ) .children( "a:first" ) .addClass( "ui-state-active" ); if ( event && event.type === "keydown" ) { this._close(); } else { this.timer = this._delay(function() { this._close(); }, this.delay ); } nested = item.children( ".ui-menu" ); if ( nested.length && ( /^mouse/.test( event.type ) ) ) { this._startOpening(nested); } this.activeMenu = item.parent(); this._trigger( "focus", event, { item: item } ); }, _scrollIntoView: function( item ) { var borderTop, paddingTop, offset, scroll, elementHeight, itemHeight; if ( this._hasScroll() ) { borderTop = parseFloat( $.css( this.activeMenu[0], "borderTopWidth" ) ) || 0; paddingTop = parseFloat( $.css( this.activeMenu[0], "paddingTop" ) ) || 0; offset = item.offset().top - this.activeMenu.offset().top - borderTop - paddingTop; scroll = this.activeMenu.scrollTop(); elementHeight = this.activeMenu.height(); itemHeight = item.height(); if ( offset < 0 ) { this.activeMenu.scrollTop( scroll + offset ); } else if ( offset + itemHeight > elementHeight ) { this.activeMenu.scrollTop( scroll + offset - elementHeight + itemHeight ); } } }, blur: function( event, fromFocus ) { if ( !fromFocus ) { clearTimeout( this.timer ); } if ( !this.active ) { return; } this.active.children( "a" ).removeClass( "ui-state-focus" ); this.active = null; this._trigger( "blur", event, { item: this.active } ); }, _startOpening: function( submenu ) { clearTimeout( this.timer ); // Don't open if already open fixes a Firefox bug that caused a .5 pixel // shift in the submenu position when mousing over the carat icon if ( submenu.attr( "aria-hidden" ) !== "true" ) { return; } this.timer = this._delay(function() { this._close(); this._open( submenu ); }, this.delay ); }, _open: function( submenu ) { var position = $.extend({ of: this.active }, this.options.position ); clearTimeout( this.timer ); this.element.find( ".ui-menu" ).not( submenu.parents( ".ui-menu" ) ) .hide() .attr( "aria-hidden", "true" ); submenu .show() .removeAttr( "aria-hidden" ) .attr( "aria-expanded", "true" ) .position( position ); }, collapseAll: function( event, all ) { clearTimeout( this.timer ); this.timer = this._delay(function() { // If we were passed an event, look for the submenu that contains the event var currentMenu = all ? this.element : $( event && event.target ).closest( this.element.find( ".ui-menu" ) ); // If we found no valid submenu ancestor, use the main menu to close all sub menus anyway if ( !currentMenu.length ) { currentMenu = this.element; } this._close( currentMenu ); this.blur( event ); this.activeMenu = currentMenu; }, this.delay ); }, // With no arguments, closes the currently active menu - if nothing is active // it closes all menus. If passed an argument, it will search for menus BELOW _close: function( startMenu ) { if ( !startMenu ) { startMenu = this.active ? this.active.parent() : this.element; } startMenu .find( ".ui-menu" ) .hide() .attr( "aria-hidden", "true" ) .attr( "aria-expanded", "false" ) .end() .find( "a.ui-state-active" ) .removeClass( "ui-state-active" ); }, collapse: function( event ) { var newItem = this.active && this.active.parent().closest( ".ui-menu-item", this.element ); if ( newItem && newItem.length ) { this._close(); this.focus( event, newItem ); } }, expand: function( event ) { var newItem = this.active && this.active .children( ".ui-menu " ) .children( ".ui-menu-item" ) .first(); if ( newItem && newItem.length ) { this._open( newItem.parent() ); // Delay so Firefox will not hide activedescendant change in expanding submenu from AT this._delay(function() { this.focus( event, newItem ); }); } }, next: function( event ) { this._move( "next", "first", event ); }, previous: function( event ) { this._move( "prev", "last", event ); }, isFirstItem: function() { return this.active && !this.active.prevAll( ".ui-menu-item" ).length; }, isLastItem: function() { return this.active && !this.active.nextAll( ".ui-menu-item" ).length; }, _move: function( direction, filter, event ) { var next; if ( this.active ) { if ( direction === "first" || direction === "last" ) { next = this.active [ direction === "first" ? "prevAll" : "nextAll" ]( ".ui-menu-item" ) .eq( -1 ); } else { next = this.active [ direction + "All" ]( ".ui-menu-item" ) .eq( 0 ); } } if ( !next || !next.length || !this.active ) { next = this.activeMenu.children( ".ui-menu-item" )[ filter ](); } this.focus( event, next ); }, nextPage: function( event ) { var item, base, height; if ( !this.active ) { this.next( event ); return; } if ( this.isLastItem() ) { return; } if ( this._hasScroll() ) { base = this.active.offset().top; height = this.element.height(); this.active.nextAll( ".ui-menu-item" ).each(function() { item = $( this ); return item.offset().top - base - height < 0; }); this.focus( event, item ); } else { this.focus( event, this.activeMenu.children( ".ui-menu-item" ) [ !this.active ? "first" : "last" ]() ); } }, previousPage: function( event ) { var item, base, height; if ( !this.active ) { this.next( event ); return; } if ( this.isFirstItem() ) { return; } if ( this._hasScroll() ) { base = this.active.offset().top; height = this.element.height(); this.active.prevAll( ".ui-menu-item" ).each(function() { item = $( this ); return item.offset().top - base + height > 0; }); this.focus( event, item ); } else { this.focus( event, this.activeMenu.children( ".ui-menu-item" ).first() ); } }, _hasScroll: function() { return this.element.outerHeight() < this.element.prop( "scrollHeight" ); }, select: function( event ) { // TODO: It should never be possible to not have an active item at this // point, but the tests don't trigger mouseenter before click. this.active = this.active || $( event.target ).closest( ".ui-menu-item" ); var ui = { item: this.active }; if ( !this.active.has( ".ui-menu" ).length ) { this.collapseAll( event, true ); } this._trigger( "select", event, ui ); } }); }( jQuery )); (function( $, undefined ) { $.widget( "ui.progressbar", { version: "1.10.3", options: { max: 100, value: 0, change: null, complete: null }, min: 0, _create: function() { // Constrain initial value this.oldValue = this.options.value = this._constrainedValue(); this.element .addClass( "ui-progressbar ui-widget ui-widget-content ui-corner-all" ) .attr({ // Only set static values, aria-valuenow and aria-valuemax are // set inside _refreshValue() role: "progressbar", "aria-valuemin": this.min }); this.valueDiv = $( "<div class='ui-progressbar-value ui-widget-header ui-corner-left'></div>" ) .appendTo( this.element ); this._refreshValue(); }, _destroy: function() { this.element .removeClass( "ui-progressbar ui-widget ui-widget-content ui-corner-all" ) .removeAttr( "role" ) .removeAttr( "aria-valuemin" ) .removeAttr( "aria-valuemax" ) .removeAttr( "aria-valuenow" ); this.valueDiv.remove(); }, value: function( newValue ) { if ( newValue === undefined ) { return this.options.value; } this.options.value = this._constrainedValue( newValue ); this._refreshValue(); }, _constrainedValue: function( newValue ) { if ( newValue === undefined ) { newValue = this.options.value; } this.indeterminate = newValue === false; // sanitize value if ( typeof newValue !== "number" ) { newValue = 0; } return this.indeterminate ? false : Math.min( this.options.max, Math.max( this.min, newValue ) ); }, _setOptions: function( options ) { // Ensure "value" option is set after other values (like max) var value = options.value; delete options.value; this._super( options ); this.options.value = this._constrainedValue( value ); this._refreshValue(); }, _setOption: function( key, value ) { if ( key === "max" ) { // Don't allow a max less than min value = Math.max( this.min, value ); } this._super( key, value ); }, _percentage: function() { return this.indeterminate ? 100 : 100 * ( this.options.value - this.min ) / ( this.options.max - this.min ); }, _refreshValue: function() { var value = this.options.value, percentage = this._percentage(); this.valueDiv .toggle( this.indeterminate || value > this.min ) .toggleClass( "ui-corner-right", value === this.options.max ) .width( percentage.toFixed(0) + "%" ); this.element.toggleClass( "ui-progressbar-indeterminate", this.indeterminate ); if ( this.indeterminate ) { this.element.removeAttr( "aria-valuenow" ); if ( !this.overlayDiv ) { this.overlayDiv = $( "<div class='ui-progressbar-overlay'></div>" ).appendTo( this.valueDiv ); } } else { this.element.attr({ "aria-valuemax": this.options.max, "aria-valuenow": value }); if ( this.overlayDiv ) { this.overlayDiv.remove(); this.overlayDiv = null; } } if ( this.oldValue !== value ) { this.oldValue = value; this._trigger( "change" ); } if ( value === this.options.max ) { this._trigger( "complete" ); } } }); })( jQuery ); (function( $, undefined ) { // number of pages in a slider // (how many times can you page up/down to go through the whole range) var numPages = 5; $.widget( "ui.slider", $.ui.mouse, { version: "1.10.3", widgetEventPrefix: "slide", options: { animate: false, distance: 0, max: 100, min: 0, orientation: "horizontal", range: false, step: 1, value: 0, values: null, // callbacks change: null, slide: null, start: null, stop: null }, _create: function() { this._keySliding = false; this._mouseSliding = false; this._animateOff = true; this._handleIndex = null; this._detectOrientation(); this._mouseInit(); this.element .addClass( "ui-slider" + " ui-slider-" + this.orientation + " ui-widget" + " ui-widget-content" + " ui-corner-all"); this._refresh(); this._setOption( "disabled", this.options.disabled ); this._animateOff = false; }, _refresh: function() { this._createRange(); this._createHandles(); this._setupEvents(); this._refreshValue(); }, _createHandles: function() { var i, handleCount, options = this.options, existingHandles = this.element.find( ".ui-slider-handle" ).addClass( "ui-state-default ui-corner-all" ), handle = "<a class='ui-slider-handle ui-state-default ui-corner-all' href='#'></a>", handles = []; handleCount = ( options.values && options.values.length ) || 1; if ( existingHandles.length > handleCount ) { existingHandles.slice( handleCount ).remove(); existingHandles = existingHandles.slice( 0, handleCount ); } for ( i = existingHandles.length; i < handleCount; i++ ) { handles.push( handle ); } this.handles = existingHandles.add( $( handles.join( "" ) ).appendTo( this.element ) ); this.handle = this.handles.eq( 0 ); this.handles.each(function( i ) { $( this ).data( "ui-slider-handle-index", i ); }); }, _createRange: function() { var options = this.options, classes = ""; if ( options.range ) { if ( options.range === true ) { if ( !options.values ) { options.values = [ this._valueMin(), this._valueMin() ]; } else if ( options.values.length && options.values.length !== 2 ) { options.values = [ options.values[0], options.values[0] ]; } else if ( $.isArray( options.values ) ) { options.values = options.values.slice(0); } } if ( !this.range || !this.range.length ) { this.range = $( "<div></div>" ) .appendTo( this.element ); classes = "ui-slider-range" + // note: this isn't the most fittingly semantic framework class for this element, // but worked best visually with a variety of themes " ui-widget-header ui-corner-all"; } else { this.range.removeClass( "ui-slider-range-min ui-slider-range-max" ) // Handle range switching from true to min/max .css({ "left": "", "bottom": "" }); } this.range.addClass( classes + ( ( options.range === "min" || options.range === "max" ) ? " ui-slider-range-" + options.range : "" ) ); } else { this.range = $([]); } }, _setupEvents: function() { var elements = this.handles.add( this.range ).filter( "a" ); this._off( elements ); this._on( elements, this._handleEvents ); this._hoverable( elements ); this._focusable( elements ); }, _destroy: function() { this.handles.remove(); this.range.remove(); this.element .removeClass( "ui-slider" + " ui-slider-horizontal" + " ui-slider-vertical" + " ui-widget" + " ui-widget-content" + " ui-corner-all" ); this._mouseDestroy(); }, _mouseCapture: function( event ) { var position, normValue, distance, closestHandle, index, allowed, offset, mouseOverHandle, that = this, o = this.options; if ( o.disabled ) { return false; } this.elementSize = { width: this.element.outerWidth(), height: this.element.outerHeight() }; this.elementOffset = this.element.offset(); position = { x: event.pageX, y: event.pageY }; normValue = this._normValueFromMouse( position ); distance = this._valueMax() - this._valueMin() + 1; this.handles.each(function( i ) { var thisDistance = Math.abs( normValue - that.values(i) ); if (( distance > thisDistance ) || ( distance === thisDistance && (i === that._lastChangedValue || that.values(i) === o.min ))) { distance = thisDistance; closestHandle = $( this ); index = i; } }); allowed = this._start( event, index ); if ( allowed === false ) { return false; } this._mouseSliding = true; this._handleIndex = index; closestHandle .addClass( "ui-state-active" ) .focus(); offset = closestHandle.offset(); mouseOverHandle = !$( event.target ).parents().addBack().is( ".ui-slider-handle" ); this._clickOffset = mouseOverHandle ? { left: 0, top: 0 } : { left: event.pageX - offset.left - ( closestHandle.width() / 2 ), top: event.pageY - offset.top - ( closestHandle.height() / 2 ) - ( parseInt( closestHandle.css("borderTopWidth"), 10 ) || 0 ) - ( parseInt( closestHandle.css("borderBottomWidth"), 10 ) || 0) + ( parseInt( closestHandle.css("marginTop"), 10 ) || 0) }; if ( !this.handles.hasClass( "ui-state-hover" ) ) { this._slide( event, index, normValue ); } this._animateOff = true; return true; }, _mouseStart: function() { return true; }, _mouseDrag: function( event ) { var position = { x: event.pageX, y: event.pageY }, normValue = this._normValueFromMouse( position ); this._slide( event, this._handleIndex, normValue ); return false; }, _mouseStop: function( event ) { this.handles.removeClass( "ui-state-active" ); this._mouseSliding = false; this._stop( event, this._handleIndex ); this._change( event, this._handleIndex ); this._handleIndex = null; this._clickOffset = null; this._animateOff = false; return false; }, _detectOrientation: function() { this.orientation = ( this.options.orientation === "vertical" ) ? "vertical" : "horizontal"; }, _normValueFromMouse: function( position ) { var pixelTotal, pixelMouse, percentMouse, valueTotal, valueMouse; if ( this.orientation === "horizontal" ) { pixelTotal = this.elementSize.width; pixelMouse = position.x - this.elementOffset.left - ( this._clickOffset ? this._clickOffset.left : 0 ); } else { pixelTotal = this.elementSize.height; pixelMouse = position.y - this.elementOffset.top - ( this._clickOffset ? this._clickOffset.top : 0 ); } percentMouse = ( pixelMouse / pixelTotal ); if ( percentMouse > 1 ) { percentMouse = 1; } if ( percentMouse < 0 ) { percentMouse = 0; } if ( this.orientation === "vertical" ) { percentMouse = 1 - percentMouse; } valueTotal = this._valueMax() - this._valueMin(); valueMouse = this._valueMin() + percentMouse * valueTotal; return this._trimAlignValue( valueMouse ); }, _start: function( event, index ) { var uiHash = { handle: this.handles[ index ], value: this.value() }; if ( this.options.values && this.options.values.length ) { uiHash.value = this.values( index ); uiHash.values = this.values(); } return this._trigger( "start", event, uiHash ); }, _slide: function( event, index, newVal ) { var otherVal, newValues, allowed; if ( this.options.values && this.options.values.length ) { otherVal = this.values( index ? 0 : 1 ); if ( ( this.options.values.length === 2 && this.options.range === true ) && ( ( index === 0 && newVal > otherVal) || ( index === 1 && newVal < otherVal ) ) ) { newVal = otherVal; } if ( newVal !== this.values( index ) ) { newValues = this.values(); newValues[ index ] = newVal; // A slide can be canceled by returning false from the slide callback allowed = this._trigger( "slide", event, { handle: this.handles[ index ], value: newVal, values: newValues } ); otherVal = this.values( index ? 0 : 1 ); if ( allowed !== false ) { this.values( index, newVal, true ); } } } else { if ( newVal !== this.value() ) { // A slide can be canceled by returning false from the slide callback allowed = this._trigger( "slide", event, { handle: this.handles[ index ], value: newVal } ); if ( allowed !== false ) { this.value( newVal ); } } } }, _stop: function( event, index ) { var uiHash = { handle: this.handles[ index ], value: this.value() }; if ( this.options.values && this.options.values.length ) { uiHash.value = this.values( index ); uiHash.values = this.values(); } this._trigger( "stop", event, uiHash ); }, _change: function( event, index ) { if ( !this._keySliding && !this._mouseSliding ) { var uiHash = { handle: this.handles[ index ], value: this.value() }; if ( this.options.values && this.options.values.length ) { uiHash.value = this.values( index ); uiHash.values = this.values(); } //store the last changed value index for reference when handles overlap this._lastChangedValue = index; this._trigger( "change", event, uiHash ); } }, value: function( newValue ) { if ( arguments.length ) { this.options.value = this._trimAlignValue( newValue ); this._refreshValue(); this._change( null, 0 ); return; } return this._value(); }, values: function( index, newValue ) { var vals, newValues, i; if ( arguments.length > 1 ) { this.options.values[ index ] = this._trimAlignValue( newValue ); this._refreshValue(); this._change( null, index ); return; } if ( arguments.length ) { if ( $.isArray( arguments[ 0 ] ) ) { vals = this.options.values; newValues = arguments[ 0 ]; for ( i = 0; i < vals.length; i += 1 ) { vals[ i ] = this._trimAlignValue( newValues[ i ] ); this._change( null, i ); } this._refreshValue(); } else { if ( this.options.values && this.options.values.length ) { return this._values( index ); } else { return this.value(); } } } else { return this._values(); } }, _setOption: function( key, value ) { var i, valsLength = 0; if ( key === "range" && this.options.range === true ) { if ( value === "min" ) { this.options.value = this._values( 0 ); this.options.values = null; } else if ( value === "max" ) { this.options.value = this._values( this.options.values.length-1 ); this.options.values = null; } } if ( $.isArray( this.options.values ) ) { valsLength = this.options.values.length; } $.Widget.prototype._setOption.apply( this, arguments ); switch ( key ) { case "orientation": this._detectOrientation(); this.element .removeClass( "ui-slider-horizontal ui-slider-vertical" ) .addClass( "ui-slider-" + this.orientation ); this._refreshValue(); break; case "value": this._animateOff = true; this._refreshValue(); this._change( null, 0 ); this._animateOff = false; break; case "values": this._animateOff = true; this._refreshValue(); for ( i = 0; i < valsLength; i += 1 ) { this._change( null, i ); } this._animateOff = false; break; case "min": case "max": this._animateOff = true; this._refreshValue(); this._animateOff = false; break; case "range": this._animateOff = true; this._refresh(); this._animateOff = false; break; } }, //internal value getter // _value() returns value trimmed by min and max, aligned by step _value: function() { var val = this.options.value; val = this._trimAlignValue( val ); return val; }, //internal values getter // _values() returns array of values trimmed by min and max, aligned by step // _values( index ) returns single value trimmed by min and max, aligned by step _values: function( index ) { var val, vals, i; if ( arguments.length ) { val = this.options.values[ index ]; val = this._trimAlignValue( val ); return val; } else if ( this.options.values && this.options.values.length ) { // .slice() creates a copy of the array // this copy gets trimmed by min and max and then returned vals = this.options.values.slice(); for ( i = 0; i < vals.length; i+= 1) { vals[ i ] = this._trimAlignValue( vals[ i ] ); } return vals; } else { return []; } }, // returns the step-aligned value that val is closest to, between (inclusive) min and max _trimAlignValue: function( val ) { if ( val <= this._valueMin() ) { return this._valueMin(); } if ( val >= this._valueMax() ) { return this._valueMax(); } var step = ( this.options.step > 0 ) ? this.options.step : 1, valModStep = (val - this._valueMin()) % step, alignValue = val - valModStep; if ( Math.abs(valModStep) * 2 >= step ) { alignValue += ( valModStep > 0 ) ? step : ( -step ); } // Since JavaScript has problems with large floats, round // the final value to 5 digits after the decimal point (see #4124) return parseFloat( alignValue.toFixed(5) ); }, _valueMin: function() { return this.options.min; }, _valueMax: function() { return this.options.max; }, _refreshValue: function() { var lastValPercent, valPercent, value, valueMin, valueMax, oRange = this.options.range, o = this.options, that = this, animate = ( !this._animateOff ) ? o.animate : false, _set = {}; if ( this.options.values && this.options.values.length ) { this.handles.each(function( i ) { valPercent = ( that.values(i) - that._valueMin() ) / ( that._valueMax() - that._valueMin() ) * 100; _set[ that.orientation === "horizontal" ? "left" : "bottom" ] = valPercent + "%"; $( this ).stop( 1, 1 )[ animate ? "animate" : "css" ]( _set, o.animate ); if ( that.options.range === true ) { if ( that.orientation === "horizontal" ) { if ( i === 0 ) { that.range.stop( 1, 1 )[ animate ? "animate" : "css" ]( { left: valPercent + "%" }, o.animate ); } if ( i === 1 ) { that.range[ animate ? "animate" : "css" ]( { width: ( valPercent - lastValPercent ) + "%" }, { queue: false, duration: o.animate } ); } } else { if ( i === 0 ) { that.range.stop( 1, 1 )[ animate ? "animate" : "css" ]( { bottom: ( valPercent ) + "%" }, o.animate ); } if ( i === 1 ) { that.range[ animate ? "animate" : "css" ]( { height: ( valPercent - lastValPercent ) + "%" }, { queue: false, duration: o.animate } ); } } } lastValPercent = valPercent; }); } else { value = this.value(); valueMin = this._valueMin(); valueMax = this._valueMax(); valPercent = ( valueMax !== valueMin ) ? ( value - valueMin ) / ( valueMax - valueMin ) * 100 : 0; _set[ this.orientation === "horizontal" ? "left" : "bottom" ] = valPercent + "%"; this.handle.stop( 1, 1 )[ animate ? "animate" : "css" ]( _set, o.animate ); if ( oRange === "min" && this.orientation === "horizontal" ) { this.range.stop( 1, 1 )[ animate ? "animate" : "css" ]( { width: valPercent + "%" }, o.animate ); } if ( oRange === "max" && this.orientation === "horizontal" ) { this.range[ animate ? "animate" : "css" ]( { width: ( 100 - valPercent ) + "%" }, { queue: false, duration: o.animate } ); } if ( oRange === "min" && this.orientation === "vertical" ) { this.range.stop( 1, 1 )[ animate ? "animate" : "css" ]( { height: valPercent + "%" }, o.animate ); } if ( oRange === "max" && this.orientation === "vertical" ) { this.range[ animate ? "animate" : "css" ]( { height: ( 100 - valPercent ) + "%" }, { queue: false, duration: o.animate } ); } } }, _handleEvents: { keydown: function( event ) { /*jshint maxcomplexity:25*/ var allowed, curVal, newVal, step, index = $( event.target ).data( "ui-slider-handle-index" ); switch ( event.keyCode ) { case $.ui.keyCode.HOME: case $.ui.keyCode.END: case $.ui.keyCode.PAGE_UP: case $.ui.keyCode.PAGE_DOWN: case $.ui.keyCode.UP: case $.ui.keyCode.RIGHT: case $.ui.keyCode.DOWN: case $.ui.keyCode.LEFT: event.preventDefault(); if ( !this._keySliding ) { this._keySliding = true; $( event.target ).addClass( "ui-state-active" ); allowed = this._start( event, index ); if ( allowed === false ) { return; } } break; } step = this.options.step; if ( this.options.values && this.options.values.length ) { curVal = newVal = this.values( index ); } else { curVal = newVal = this.value(); } switch ( event.keyCode ) { case $.ui.keyCode.HOME: newVal = this._valueMin(); break; case $.ui.keyCode.END: newVal = this._valueMax(); break; case $.ui.keyCode.PAGE_UP: newVal = this._trimAlignValue( curVal + ( (this._valueMax() - this._valueMin()) / numPages ) ); break; case $.ui.keyCode.PAGE_DOWN: newVal = this._trimAlignValue( curVal - ( (this._valueMax() - this._valueMin()) / numPages ) ); break; case $.ui.keyCode.UP: case $.ui.keyCode.RIGHT: if ( curVal === this._valueMax() ) { return; } newVal = this._trimAlignValue( curVal + step ); break; case $.ui.keyCode.DOWN: case $.ui.keyCode.LEFT: if ( curVal === this._valueMin() ) { return; } newVal = this._trimAlignValue( curVal - step ); break; } this._slide( event, index, newVal ); }, click: function( event ) { event.preventDefault(); }, keyup: function( event ) { var index = $( event.target ).data( "ui-slider-handle-index" ); if ( this._keySliding ) { this._keySliding = false; this._stop( event, index ); this._change( event, index ); $( event.target ).removeClass( "ui-state-active" ); } } } }); }(jQuery)); (function( $ ) { function modifier( fn ) { return function() { var previous = this.element.val(); fn.apply( this, arguments ); this._refresh(); if ( previous !== this.element.val() ) { this._trigger( "change" ); } }; } $.widget( "ui.spinner", { version: "1.10.3", defaultElement: "<input>", widgetEventPrefix: "spin", options: { culture: null, icons: { down: "ui-icon-triangle-1-s", up: "ui-icon-triangle-1-n" }, incremental: true, max: null, min: null, numberFormat: null, page: 10, step: 1, change: null, spin: null, start: null, stop: null }, _create: function() { // handle string values that need to be parsed this._setOption( "max", this.options.max ); this._setOption( "min", this.options.min ); this._setOption( "step", this.options.step ); // format the value, but don't constrain this._value( this.element.val(), true ); this._draw(); this._on( this._events ); this._refresh(); // turning off autocomplete prevents the browser from remembering the // value when navigating through history, so we re-enable autocomplete // if the page is unloaded before the widget is destroyed. #7790 this._on( this.window, { beforeunload: function() { this.element.removeAttr( "autocomplete" ); } }); }, _getCreateOptions: function() { var options = {}, element = this.element; $.each( [ "min", "max", "step" ], function( i, option ) { var value = element.attr( option ); if ( value !== undefined && value.length ) { options[ option ] = value; } }); return options; }, _events: { keydown: function( event ) { if ( this._start( event ) && this._keydown( event ) ) { event.preventDefault(); } }, keyup: "_stop", focus: function() { this.previous = this.element.val(); }, blur: function( event ) { if ( this.cancelBlur ) { delete this.cancelBlur; return; } this._stop(); this._refresh(); if ( this.previous !== this.element.val() ) { this._trigger( "change", event ); } }, mousewheel: function( event, delta ) { if ( !delta ) { return; } if ( !this.spinning && !this._start( event ) ) { return false; } this._spin( (delta > 0 ? 1 : -1) * this.options.step, event ); clearTimeout( this.mousewheelTimer ); this.mousewheelTimer = this._delay(function() { if ( this.spinning ) { this._stop( event ); } }, 100 ); event.preventDefault(); }, "mousedown .ui-spinner-button": function( event ) { var previous; // We never want the buttons to have focus; whenever the user is // interacting with the spinner, the focus should be on the input. // If the input is focused then this.previous is properly set from // when the input first received focus. If the input is not focused // then we need to set this.previous based on the value before spinning. previous = this.element[0] === this.document[0].activeElement ? this.previous : this.element.val(); function checkFocus() { var isActive = this.element[0] === this.document[0].activeElement; if ( !isActive ) { this.element.focus(); this.previous = previous; // support: IE // IE sets focus asynchronously, so we need to check if focus // moved off of the input because the user clicked on the button. this._delay(function() { this.previous = previous; }); } } // ensure focus is on (or stays on) the text field event.preventDefault(); checkFocus.call( this ); // support: IE // IE doesn't prevent moving focus even with event.preventDefault() // so we set a flag to know when we should ignore the blur event // and check (again) if focus moved off of the input. this.cancelBlur = true; this._delay(function() { delete this.cancelBlur; checkFocus.call( this ); }); if ( this._start( event ) === false ) { return; } this._repeat( null, $( event.currentTarget ).hasClass( "ui-spinner-up" ) ? 1 : -1, event ); }, "mouseup .ui-spinner-button": "_stop", "mouseenter .ui-spinner-button": function( event ) { // button will add ui-state-active if mouse was down while mouseleave and kept down if ( !$( event.currentTarget ).hasClass( "ui-state-active" ) ) { return; } if ( this._start( event ) === false ) { return false; } this._repeat( null, $( event.currentTarget ).hasClass( "ui-spinner-up" ) ? 1 : -1, event ); }, // TODO: do we really want to consider this a stop? // shouldn't we just stop the repeater and wait until mouseup before // we trigger the stop event? "mouseleave .ui-spinner-button": "_stop" }, _draw: function() { var uiSpinner = this.uiSpinner = this.element .addClass( "ui-spinner-input" ) .attr( "autocomplete", "off" ) .wrap( this._uiSpinnerHtml() ) .parent() // add buttons .append( this._buttonHtml() ); this.element.attr( "role", "spinbutton" ); // button bindings this.buttons = uiSpinner.find( ".ui-spinner-button" ) .attr( "tabIndex", -1 ) .button() .removeClass( "ui-corner-all" ); // IE 6 doesn't understand height: 50% for the buttons // unless the wrapper has an explicit height if ( this.buttons.height() > Math.ceil( uiSpinner.height() * 0.5 ) && uiSpinner.height() > 0 ) { uiSpinner.height( uiSpinner.height() ); } // disable spinner if element was already disabled if ( this.options.disabled ) { this.disable(); } }, _keydown: function( event ) { var options = this.options, keyCode = $.ui.keyCode; switch ( event.keyCode ) { case keyCode.UP: this._repeat( null, 1, event ); return true; case keyCode.DOWN: this._repeat( null, -1, event ); return true; case keyCode.PAGE_UP: this._repeat( null, options.page, event ); return true; case keyCode.PAGE_DOWN: this._repeat( null, -options.page, event ); return true; } return false; }, _uiSpinnerHtml: function() { return "<span class='ui-spinner ui-widget ui-widget-content ui-corner-all'></span>"; }, _buttonHtml: function() { return "" + "<a class='ui-spinner-button ui-spinner-up ui-corner-tr'>" + "<span class='ui-icon " + this.options.icons.up + "'>&#9650;</span>" + "</a>" + "<a class='ui-spinner-button ui-spinner-down ui-corner-br'>" + "<span class='ui-icon " + this.options.icons.down + "'>&#9660;</span>" + "</a>"; }, _start: function( event ) { if ( !this.spinning && this._trigger( "start", event ) === false ) { return false; } if ( !this.counter ) { this.counter = 1; } this.spinning = true; return true; }, _repeat: function( i, steps, event ) { i = i || 500; clearTimeout( this.timer ); this.timer = this._delay(function() { this._repeat( 40, steps, event ); }, i ); this._spin( steps * this.options.step, event ); }, _spin: function( step, event ) { var value = this.value() || 0; if ( !this.counter ) { this.counter = 1; } value = this._adjustValue( value + step * this._increment( this.counter ) ); if ( !this.spinning || this._trigger( "spin", event, { value: value } ) !== false) { this._value( value ); this.counter++; } }, _increment: function( i ) { var incremental = this.options.incremental; if ( incremental ) { return $.isFunction( incremental ) ? incremental( i ) : Math.floor( i*i*i/50000 - i*i/500 + 17*i/200 + 1 ); } return 1; }, _precision: function() { var precision = this._precisionOf( this.options.step ); if ( this.options.min !== null ) { precision = Math.max( precision, this._precisionOf( this.options.min ) ); } return precision; }, _precisionOf: function( num ) { var str = num.toString(), decimal = str.indexOf( "." ); return decimal === -1 ? 0 : str.length - decimal - 1; }, _adjustValue: function( value ) { var base, aboveMin, options = this.options; // make sure we're at a valid step // - find out where we are relative to the base (min or 0) base = options.min !== null ? options.min : 0; aboveMin = value - base; // - round to the nearest step aboveMin = Math.round(aboveMin / options.step) * options.step; // - rounding is based on 0, so adjust back to our base value = base + aboveMin; // fix precision from bad JS floating point math value = parseFloat( value.toFixed( this._precision() ) ); // clamp the value if ( options.max !== null && value > options.max) { return options.max; } if ( options.min !== null && value < options.min ) { return options.min; } return value; }, _stop: function( event ) { if ( !this.spinning ) { return; } clearTimeout( this.timer ); clearTimeout( this.mousewheelTimer ); this.counter = 0; this.spinning = false; this._trigger( "stop", event ); }, _setOption: function( key, value ) { if ( key === "culture" || key === "numberFormat" ) { var prevValue = this._parse( this.element.val() ); this.options[ key ] = value; this.element.val( this._format( prevValue ) ); return; } if ( key === "max" || key === "min" || key === "step" ) { if ( typeof value === "string" ) { value = this._parse( value ); } } if ( key === "icons" ) { this.buttons.first().find( ".ui-icon" ) .removeClass( this.options.icons.up ) .addClass( value.up ); this.buttons.last().find( ".ui-icon" ) .removeClass( this.options.icons.down ) .addClass( value.down ); } this._super( key, value ); if ( key === "disabled" ) { if ( value ) { this.element.prop( "disabled", true ); this.buttons.button( "disable" ); } else { this.element.prop( "disabled", false ); this.buttons.button( "enable" ); } } }, _setOptions: modifier(function( options ) { this._super( options ); this._value( this.element.val() ); }), _parse: function( val ) { if ( typeof val === "string" && val !== "" ) { val = window.Globalize && this.options.numberFormat ? Globalize.parseFloat( val, 10, this.options.culture ) : +val; } return val === "" || isNaN( val ) ? null : val; }, _format: function( value ) { if ( value === "" ) { return ""; } return window.Globalize && this.options.numberFormat ? Globalize.format( value, this.options.numberFormat, this.options.culture ) : value; }, _refresh: function() { this.element.attr({ "aria-valuemin": this.options.min, "aria-valuemax": this.options.max, // TODO: what should we do with values that can't be parsed? "aria-valuenow": this._parse( this.element.val() ) }); }, // update the value without triggering change _value: function( value, allowAny ) { var parsed; if ( value !== "" ) { parsed = this._parse( value ); if ( parsed !== null ) { if ( !allowAny ) { parsed = this._adjustValue( parsed ); } value = this._format( parsed ); } } this.element.val( value ); this._refresh(); }, _destroy: function() { this.element .removeClass( "ui-spinner-input" ) .prop( "disabled", false ) .removeAttr( "autocomplete" ) .removeAttr( "role" ) .removeAttr( "aria-valuemin" ) .removeAttr( "aria-valuemax" ) .removeAttr( "aria-valuenow" ); this.uiSpinner.replaceWith( this.element ); }, stepUp: modifier(function( steps ) { this._stepUp( steps ); }), _stepUp: function( steps ) { if ( this._start() ) { this._spin( (steps || 1) * this.options.step ); this._stop(); } }, stepDown: modifier(function( steps ) { this._stepDown( steps ); }), _stepDown: function( steps ) { if ( this._start() ) { this._spin( (steps || 1) * -this.options.step ); this._stop(); } }, pageUp: modifier(function( pages ) { this._stepUp( (pages || 1) * this.options.page ); }), pageDown: modifier(function( pages ) { this._stepDown( (pages || 1) * this.options.page ); }), value: function( newVal ) { if ( !arguments.length ) { return this._parse( this.element.val() ); } modifier( this._value ).call( this, newVal ); }, widget: function() { return this.uiSpinner; } }); }( jQuery ) ); (function( $, undefined ) { var tabId = 0, rhash = /#.*$/; function getNextTabId() { return ++tabId; } function isLocal( anchor ) { return anchor.hash.length > 1 && decodeURIComponent( anchor.href.replace( rhash, "" ) ) === decodeURIComponent( location.href.replace( rhash, "" ) ); } $.widget( "ui.tabs", { version: "1.10.3", delay: 300, options: { active: null, collapsible: false, event: "click", heightStyle: "content", hide: null, show: null, // callbacks activate: null, beforeActivate: null, beforeLoad: null, load: null }, _create: function() { var that = this, options = this.options; this.running = false; this.element .addClass( "ui-tabs ui-widget ui-widget-content ui-corner-all" ) .toggleClass( "ui-tabs-collapsible", options.collapsible ) // Prevent users from focusing disabled tabs via click .delegate( ".ui-tabs-nav > li", "mousedown" + this.eventNamespace, function( event ) { if ( $( this ).is( ".ui-state-disabled" ) ) { event.preventDefault(); } }) // support: IE <9 // Preventing the default action in mousedown doesn't prevent IE // from focusing the element, so if the anchor gets focused, blur. // We don't have to worry about focusing the previously focused // element since clicking on a non-focusable element should focus // the body anyway. .delegate( ".ui-tabs-anchor", "focus" + this.eventNamespace, function() { if ( $( this ).closest( "li" ).is( ".ui-state-disabled" ) ) { this.blur(); } }); this._processTabs(); options.active = this._initialActive(); // Take disabling tabs via class attribute from HTML // into account and update option properly. if ( $.isArray( options.disabled ) ) { options.disabled = $.unique( options.disabled.concat( $.map( this.tabs.filter( ".ui-state-disabled" ), function( li ) { return that.tabs.index( li ); }) ) ).sort(); } // check for length avoids error when initializing empty list if ( this.options.active !== false && this.anchors.length ) { this.active = this._findActive( options.active ); } else { this.active = $(); } this._refresh(); if ( this.active.length ) { this.load( options.active ); } }, _initialActive: function() { var active = this.options.active, collapsible = this.options.collapsible, locationHash = location.hash.substring( 1 ); if ( active === null ) { // check the fragment identifier in the URL if ( locationHash ) { this.tabs.each(function( i, tab ) { if ( $( tab ).attr( "aria-controls" ) === locationHash ) { active = i; return false; } }); } // check for a tab marked active via a class if ( active === null ) { active = this.tabs.index( this.tabs.filter( ".ui-tabs-active" ) ); } // no active tab, set to false if ( active === null || active === -1 ) { active = this.tabs.length ? 0 : false; } } // handle numbers: negative, out of range if ( active !== false ) { active = this.tabs.index( this.tabs.eq( active ) ); if ( active === -1 ) { active = collapsible ? false : 0; } } // don't allow collapsible: false and active: false if ( !collapsible && active === false && this.anchors.length ) { active = 0; } return active; }, _getCreateEventData: function() { return { tab: this.active, panel: !this.active.length ? $() : this._getPanelForTab( this.active ) }; }, _tabKeydown: function( event ) { /*jshint maxcomplexity:15*/ var focusedTab = $( this.document[0].activeElement ).closest( "li" ), selectedIndex = this.tabs.index( focusedTab ), goingForward = true; if ( this._handlePageNav( event ) ) { return; } switch ( event.keyCode ) { case $.ui.keyCode.RIGHT: case $.ui.keyCode.DOWN: selectedIndex++; break; case $.ui.keyCode.UP: case $.ui.keyCode.LEFT: goingForward = false; selectedIndex--; break; case $.ui.keyCode.END: selectedIndex = this.anchors.length - 1; break; case $.ui.keyCode.HOME: selectedIndex = 0; break; case $.ui.keyCode.SPACE: // Activate only, no collapsing event.preventDefault(); clearTimeout( this.activating ); this._activate( selectedIndex ); return; case $.ui.keyCode.ENTER: // Toggle (cancel delayed activation, allow collapsing) event.preventDefault(); clearTimeout( this.activating ); // Determine if we should collapse or activate this._activate( selectedIndex === this.options.active ? false : selectedIndex ); return; default: return; } // Focus the appropriate tab, based on which key was pressed event.preventDefault(); clearTimeout( this.activating ); selectedIndex = this._focusNextTab( selectedIndex, goingForward ); // Navigating with control key will prevent automatic activation if ( !event.ctrlKey ) { // Update aria-selected immediately so that AT think the tab is already selected. // Otherwise AT may confuse the user by stating that they need to activate the tab, // but the tab will already be activated by the time the announcement finishes. focusedTab.attr( "aria-selected", "false" ); this.tabs.eq( selectedIndex ).attr( "aria-selected", "true" ); this.activating = this._delay(function() { this.option( "active", selectedIndex ); }, this.delay ); } }, _panelKeydown: function( event ) { if ( this._handlePageNav( event ) ) { return; } // Ctrl+up moves focus to the current tab if ( event.ctrlKey && event.keyCode === $.ui.keyCode.UP ) { event.preventDefault(); this.active.focus(); } }, // Alt+page up/down moves focus to the previous/next tab (and activates) _handlePageNav: function( event ) { if ( event.altKey && event.keyCode === $.ui.keyCode.PAGE_UP ) { this._activate( this._focusNextTab( this.options.active - 1, false ) ); return true; } if ( event.altKey && event.keyCode === $.ui.keyCode.PAGE_DOWN ) { this._activate( this._focusNextTab( this.options.active + 1, true ) ); return true; } }, _findNextTab: function( index, goingForward ) { var lastTabIndex = this.tabs.length - 1; function constrain() { if ( index > lastTabIndex ) { index = 0; } if ( index < 0 ) { index = lastTabIndex; } return index; } while ( $.inArray( constrain(), this.options.disabled ) !== -1 ) { index = goingForward ? index + 1 : index - 1; } return index; }, _focusNextTab: function( index, goingForward ) { index = this._findNextTab( index, goingForward ); this.tabs.eq( index ).focus(); return index; }, _setOption: function( key, value ) { if ( key === "active" ) { // _activate() will handle invalid values and update this.options this._activate( value ); return; } if ( key === "disabled" ) { // don't use the widget factory's disabled handling this._setupDisabled( value ); return; } this._super( key, value); if ( key === "collapsible" ) { this.element.toggleClass( "ui-tabs-collapsible", value ); // Setting collapsible: false while collapsed; open first panel if ( !value && this.options.active === false ) { this._activate( 0 ); } } if ( key === "event" ) { this._setupEvents( value ); } if ( key === "heightStyle" ) { this._setupHeightStyle( value ); } }, _tabId: function( tab ) { return tab.attr( "aria-controls" ) || "ui-tabs-" + getNextTabId(); }, _sanitizeSelector: function( hash ) { return hash ? hash.replace( /[!"$%&'()*+,.\/:;<=>?@\[\]\^`{|}~]/g, "\\$&" ) : ""; }, refresh: function() { var options = this.options, lis = this.tablist.children( ":has(a[href])" ); // get disabled tabs from class attribute from HTML // this will get converted to a boolean if needed in _refresh() options.disabled = $.map( lis.filter( ".ui-state-disabled" ), function( tab ) { return lis.index( tab ); }); this._processTabs(); // was collapsed or no tabs if ( options.active === false || !this.anchors.length ) { options.active = false; this.active = $(); // was active, but active tab is gone } else if ( this.active.length && !$.contains( this.tablist[ 0 ], this.active[ 0 ] ) ) { // all remaining tabs are disabled if ( this.tabs.length === options.disabled.length ) { options.active = false; this.active = $(); // activate previous tab } else { this._activate( this._findNextTab( Math.max( 0, options.active - 1 ), false ) ); } // was active, active tab still exists } else { // make sure active index is correct options.active = this.tabs.index( this.active ); } this._refresh(); }, _refresh: function() { this._setupDisabled( this.options.disabled ); this._setupEvents( this.options.event ); this._setupHeightStyle( this.options.heightStyle ); this.tabs.not( this.active ).attr({ "aria-selected": "false", tabIndex: -1 }); this.panels.not( this._getPanelForTab( this.active ) ) .hide() .attr({ "aria-expanded": "false", "aria-hidden": "true" }); // Make sure one tab is in the tab order if ( !this.active.length ) { this.tabs.eq( 0 ).attr( "tabIndex", 0 ); } else { this.active .addClass( "ui-tabs-active ui-state-active" ) .attr({ "aria-selected": "true", tabIndex: 0 }); this._getPanelForTab( this.active ) .show() .attr({ "aria-expanded": "true", "aria-hidden": "false" }); } }, _processTabs: function() { var that = this; this.tablist = this._getList() .addClass( "ui-tabs-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all" ) .attr( "role", "tablist" ); this.tabs = this.tablist.find( "> li:has(a[href])" ) .addClass( "ui-state-default ui-corner-top" ) .attr({ role: "tab", tabIndex: -1 }); this.anchors = this.tabs.map(function() { return $( "a", this )[ 0 ]; }) .addClass( "ui-tabs-anchor" ) .attr({ role: "presentation", tabIndex: -1 }); this.panels = $(); this.anchors.each(function( i, anchor ) { var selector, panel, panelId, anchorId = $( anchor ).uniqueId().attr( "id" ), tab = $( anchor ).closest( "li" ), originalAriaControls = tab.attr( "aria-controls" ); // inline tab if ( isLocal( anchor ) ) { selector = anchor.hash; panel = that.element.find( that._sanitizeSelector( selector ) ); // remote tab } else { panelId = that._tabId( tab ); selector = "#" + panelId; panel = that.element.find( selector ); if ( !panel.length ) { panel = that._createPanel( panelId ); panel.insertAfter( that.panels[ i - 1 ] || that.tablist ); } panel.attr( "aria-live", "polite" ); } if ( panel.length) { that.panels = that.panels.add( panel ); } if ( originalAriaControls ) { tab.data( "ui-tabs-aria-controls", originalAriaControls ); } tab.attr({ "aria-controls": selector.substring( 1 ), "aria-labelledby": anchorId }); panel.attr( "aria-labelledby", anchorId ); }); this.panels .addClass( "ui-tabs-panel ui-widget-content ui-corner-bottom" ) .attr( "role", "tabpanel" ); }, // allow overriding how to find the list for rare usage scenarios (#7715) _getList: function() { return this.element.find( "ol,ul" ).eq( 0 ); }, _createPanel: function( id ) { return $( "<div>" ) .attr( "id", id ) .addClass( "ui-tabs-panel ui-widget-content ui-corner-bottom" ) .data( "ui-tabs-destroy", true ); }, _setupDisabled: function( disabled ) { if ( $.isArray( disabled ) ) { if ( !disabled.length ) { disabled = false; } else if ( disabled.length === this.anchors.length ) { disabled = true; } } // disable tabs for ( var i = 0, li; ( li = this.tabs[ i ] ); i++ ) { if ( disabled === true || $.inArray( i, disabled ) !== -1 ) { $( li ) .addClass( "ui-state-disabled" ) .attr( "aria-disabled", "true" ); } else { $( li ) .removeClass( "ui-state-disabled" ) .removeAttr( "aria-disabled" ); } } this.options.disabled = disabled; }, _setupEvents: function( event ) { var events = { click: function( event ) { event.preventDefault(); } }; if ( event ) { $.each( event.split(" "), function( index, eventName ) { events[ eventName ] = "_eventHandler"; }); } this._off( this.anchors.add( this.tabs ).add( this.panels ) ); this._on( this.anchors, events ); this._on( this.tabs, { keydown: "_tabKeydown" } ); this._on( this.panels, { keydown: "_panelKeydown" } ); this._focusable( this.tabs ); this._hoverable( this.tabs ); }, _setupHeightStyle: function( heightStyle ) { var maxHeight, parent = this.element.parent(); if ( heightStyle === "fill" ) { maxHeight = parent.height(); maxHeight -= this.element.outerHeight() - this.element.height(); this.element.siblings( ":visible" ).each(function() { var elem = $( this ), position = elem.css( "position" ); if ( position === "absolute" || position === "fixed" ) { return; } maxHeight -= elem.outerHeight( true ); }); this.element.children().not( this.panels ).each(function() { maxHeight -= $( this ).outerHeight( true ); }); this.panels.each(function() { $( this ).height( Math.max( 0, maxHeight - $( this ).innerHeight() + $( this ).height() ) ); }) .css( "overflow", "auto" ); } else if ( heightStyle === "auto" ) { maxHeight = 0; this.panels.each(function() { maxHeight = Math.max( maxHeight, $( this ).height( "" ).height() ); }).height( maxHeight ); } }, _eventHandler: function( event ) { var options = this.options, active = this.active, anchor = $( event.currentTarget ), tab = anchor.closest( "li" ), clickedIsActive = tab[ 0 ] === active[ 0 ], collapsing = clickedIsActive && options.collapsible, toShow = collapsing ? $() : this._getPanelForTab( tab ), toHide = !active.length ? $() : this._getPanelForTab( active ), eventData = { oldTab: active, oldPanel: toHide, newTab: collapsing ? $() : tab, newPanel: toShow }; event.preventDefault(); if ( tab.hasClass( "ui-state-disabled" ) || // tab is already loading tab.hasClass( "ui-tabs-loading" ) || // can't switch durning an animation this.running || // click on active header, but not collapsible ( clickedIsActive && !options.collapsible ) || // allow canceling activation ( this._trigger( "beforeActivate", event, eventData ) === false ) ) { return; } options.active = collapsing ? false : this.tabs.index( tab ); this.active = clickedIsActive ? $() : tab; if ( this.xhr ) { this.xhr.abort(); } if ( !toHide.length && !toShow.length ) { $.error( "jQuery UI Tabs: Mismatching fragment identifier." ); } if ( toShow.length ) { this.load( this.tabs.index( tab ), event ); } this._toggle( event, eventData ); }, // handles show/hide for selecting tabs _toggle: function( event, eventData ) { var that = this, toShow = eventData.newPanel, toHide = eventData.oldPanel; this.running = true; function complete() { that.running = false; that._trigger( "activate", event, eventData ); } function show() { eventData.newTab.closest( "li" ).addClass( "ui-tabs-active ui-state-active" ); if ( toShow.length && that.options.show ) { that._show( toShow, that.options.show, complete ); } else { toShow.show(); complete(); } } // start out by hiding, then showing, then completing if ( toHide.length && this.options.hide ) { this._hide( toHide, this.options.hide, function() { eventData.oldTab.closest( "li" ).removeClass( "ui-tabs-active ui-state-active" ); show(); }); } else { eventData.oldTab.closest( "li" ).removeClass( "ui-tabs-active ui-state-active" ); toHide.hide(); show(); } toHide.attr({ "aria-expanded": "false", "aria-hidden": "true" }); eventData.oldTab.attr( "aria-selected", "false" ); // If we're switching tabs, remove the old tab from the tab order. // If we're opening from collapsed state, remove the previous tab from the tab order. // If we're collapsing, then keep the collapsing tab in the tab order. if ( toShow.length && toHide.length ) { eventData.oldTab.attr( "tabIndex", -1 ); } else if ( toShow.length ) { this.tabs.filter(function() { return $( this ).attr( "tabIndex" ) === 0; }) .attr( "tabIndex", -1 ); } toShow.attr({ "aria-expanded": "true", "aria-hidden": "false" }); eventData.newTab.attr({ "aria-selected": "true", tabIndex: 0 }); }, _activate: function( index ) { var anchor, active = this._findActive( index ); // trying to activate the already active panel if ( active[ 0 ] === this.active[ 0 ] ) { return; } // trying to collapse, simulate a click on the current active header if ( !active.length ) { active = this.active; } anchor = active.find( ".ui-tabs-anchor" )[ 0 ]; this._eventHandler({ target: anchor, currentTarget: anchor, preventDefault: $.noop }); }, _findActive: function( index ) { return index === false ? $() : this.tabs.eq( index ); }, _getIndex: function( index ) { // meta-function to give users option to provide a href string instead of a numerical index. if ( typeof index === "string" ) { index = this.anchors.index( this.anchors.filter( "[href$='" + index + "']" ) ); } return index; }, _destroy: function() { if ( this.xhr ) { this.xhr.abort(); } this.element.removeClass( "ui-tabs ui-widget ui-widget-content ui-corner-all ui-tabs-collapsible" ); this.tablist .removeClass( "ui-tabs-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all" ) .removeAttr( "role" ); this.anchors .removeClass( "ui-tabs-anchor" ) .removeAttr( "role" ) .removeAttr( "tabIndex" ) .removeUniqueId(); this.tabs.add( this.panels ).each(function() { if ( $.data( this, "ui-tabs-destroy" ) ) { $( this ).remove(); } else { $( this ) .removeClass( "ui-state-default ui-state-active ui-state-disabled " + "ui-corner-top ui-corner-bottom ui-widget-content ui-tabs-active ui-tabs-panel" ) .removeAttr( "tabIndex" ) .removeAttr( "aria-live" ) .removeAttr( "aria-busy" ) .removeAttr( "aria-selected" ) .removeAttr( "aria-labelledby" ) .removeAttr( "aria-hidden" ) .removeAttr( "aria-expanded" ) .removeAttr( "role" ); } }); this.tabs.each(function() { var li = $( this ), prev = li.data( "ui-tabs-aria-controls" ); if ( prev ) { li .attr( "aria-controls", prev ) .removeData( "ui-tabs-aria-controls" ); } else { li.removeAttr( "aria-controls" ); } }); this.panels.show(); if ( this.options.heightStyle !== "content" ) { this.panels.css( "height", "" ); } }, enable: function( index ) { var disabled = this.options.disabled; if ( disabled === false ) { return; } if ( index === undefined ) { disabled = false; } else { index = this._getIndex( index ); if ( $.isArray( disabled ) ) { disabled = $.map( disabled, function( num ) { return num !== index ? num : null; }); } else { disabled = $.map( this.tabs, function( li, num ) { return num !== index ? num : null; }); } } this._setupDisabled( disabled ); }, disable: function( index ) { var disabled = this.options.disabled; if ( disabled === true ) { return; } if ( index === undefined ) { disabled = true; } else { index = this._getIndex( index ); if ( $.inArray( index, disabled ) !== -1 ) { return; } if ( $.isArray( disabled ) ) { disabled = $.merge( [ index ], disabled ).sort(); } else { disabled = [ index ]; } } this._setupDisabled( disabled ); }, load: function( index, event ) { index = this._getIndex( index ); var that = this, tab = this.tabs.eq( index ), anchor = tab.find( ".ui-tabs-anchor" ), panel = this._getPanelForTab( tab ), eventData = { tab: tab, panel: panel }; // not remote if ( isLocal( anchor[ 0 ] ) ) { return; } this.xhr = $.ajax( this._ajaxSettings( anchor, event, eventData ) ); // support: jQuery <1.8 // jQuery <1.8 returns false if the request is canceled in beforeSend, // but as of 1.8, $.ajax() always returns a jqXHR object. if ( this.xhr && this.xhr.statusText !== "canceled" ) { tab.addClass( "ui-tabs-loading" ); panel.attr( "aria-busy", "true" ); this.xhr .success(function( response ) { // support: jQuery <1.8 // http://bugs.jquery.com/ticket/11778 setTimeout(function() { panel.html( response ); that._trigger( "load", event, eventData ); }, 1 ); }) .complete(function( jqXHR, status ) { // support: jQuery <1.8 // http://bugs.jquery.com/ticket/11778 setTimeout(function() { if ( status === "abort" ) { that.panels.stop( false, true ); } tab.removeClass( "ui-tabs-loading" ); panel.removeAttr( "aria-busy" ); if ( jqXHR === that.xhr ) { delete that.xhr; } }, 1 ); }); } }, _ajaxSettings: function( anchor, event, eventData ) { var that = this; return { url: anchor.attr( "href" ), beforeSend: function( jqXHR, settings ) { return that._trigger( "beforeLoad", event, $.extend( { jqXHR : jqXHR, ajaxSettings: settings }, eventData ) ); } }; }, _getPanelForTab: function( tab ) { var id = $( tab ).attr( "aria-controls" ); return this.element.find( this._sanitizeSelector( "#" + id ) ); } }); })( jQuery ); (function( $ ) { var increments = 0; function addDescribedBy( elem, id ) { var describedby = (elem.attr( "aria-describedby" ) || "").split( /\s+/ ); describedby.push( id ); elem .data( "ui-tooltip-id", id ) .attr( "aria-describedby", $.trim( describedby.join( " " ) ) ); } function removeDescribedBy( elem ) { var id = elem.data( "ui-tooltip-id" ), describedby = (elem.attr( "aria-describedby" ) || "").split( /\s+/ ), index = $.inArray( id, describedby ); if ( index !== -1 ) { describedby.splice( index, 1 ); } elem.removeData( "ui-tooltip-id" ); describedby = $.trim( describedby.join( " " ) ); if ( describedby ) { elem.attr( "aria-describedby", describedby ); } else { elem.removeAttr( "aria-describedby" ); } } $.widget( "ui.tooltip", { version: "1.10.3", options: { content: function() { // support: IE<9, Opera in jQuery <1.7 // .text() can't accept undefined, so coerce to a string var title = $( this ).attr( "title" ) || ""; // Escape title, since we're going from an attribute to raw HTML return $( "<a>" ).text( title ).html(); }, hide: true, // Disabled elements have inconsistent behavior across browsers (#8661) items: "[title]:not([disabled])", position: { my: "left top+15", at: "left bottom", collision: "flipfit flip" }, show: true, tooltipClass: null, track: false, // callbacks close: null, open: null }, _create: function() { this._on({ mouseover: "open", focusin: "open" }); // IDs of generated tooltips, needed for destroy this.tooltips = {}; // IDs of parent tooltips where we removed the title attribute this.parents = {}; if ( this.options.disabled ) { this._disable(); } }, _setOption: function( key, value ) { var that = this; if ( key === "disabled" ) { this[ value ? "_disable" : "_enable" ](); this.options[ key ] = value; // disable element style changes return; } this._super( key, value ); if ( key === "content" ) { $.each( this.tooltips, function( id, element ) { that._updateContent( element ); }); } }, _disable: function() { var that = this; // close open tooltips $.each( this.tooltips, function( id, element ) { var event = $.Event( "blur" ); event.target = event.currentTarget = element[0]; that.close( event, true ); }); // remove title attributes to prevent native tooltips this.element.find( this.options.items ).addBack().each(function() { var element = $( this ); if ( element.is( "[title]" ) ) { element .data( "ui-tooltip-title", element.attr( "title" ) ) .attr( "title", "" ); } }); }, _enable: function() { // restore title attributes this.element.find( this.options.items ).addBack().each(function() { var element = $( this ); if ( element.data( "ui-tooltip-title" ) ) { element.attr( "title", element.data( "ui-tooltip-title" ) ); } }); }, open: function( event ) { var that = this, target = $( event ? event.target : this.element ) // we need closest here due to mouseover bubbling, // but always pointing at the same event target .closest( this.options.items ); // No element to show a tooltip for or the tooltip is already open if ( !target.length || target.data( "ui-tooltip-id" ) ) { return; } if ( target.attr( "title" ) ) { target.data( "ui-tooltip-title", target.attr( "title" ) ); } target.data( "ui-tooltip-open", true ); // kill parent tooltips, custom or native, for hover if ( event && event.type === "mouseover" ) { target.parents().each(function() { var parent = $( this ), blurEvent; if ( parent.data( "ui-tooltip-open" ) ) { blurEvent = $.Event( "blur" ); blurEvent.target = blurEvent.currentTarget = this; that.close( blurEvent, true ); } if ( parent.attr( "title" ) ) { parent.uniqueId(); that.parents[ this.id ] = { element: this, title: parent.attr( "title" ) }; parent.attr( "title", "" ); } }); } this._updateContent( target, event ); }, _updateContent: function( target, event ) { var content, contentOption = this.options.content, that = this, eventType = event ? event.type : null; if ( typeof contentOption === "string" ) { return this._open( event, target, contentOption ); } content = contentOption.call( target[0], function( response ) { // ignore async response if tooltip was closed already if ( !target.data( "ui-tooltip-open" ) ) { return; } // IE may instantly serve a cached response for ajax requests // delay this call to _open so the other call to _open runs first that._delay(function() { // jQuery creates a special event for focusin when it doesn't // exist natively. To improve performance, the native event // object is reused and the type is changed. Therefore, we can't // rely on the type being correct after the event finished // bubbling, so we set it back to the previous value. (#8740) if ( event ) { event.type = eventType; } this._open( event, target, response ); }); }); if ( content ) { this._open( event, target, content ); } }, _open: function( event, target, content ) { var tooltip, events, delayedShow, positionOption = $.extend( {}, this.options.position ); if ( !content ) { return; } // Content can be updated multiple times. If the tooltip already // exists, then just update the content and bail. tooltip = this._find( target ); if ( tooltip.length ) { tooltip.find( ".ui-tooltip-content" ).html( content ); return; } // if we have a title, clear it to prevent the native tooltip // we have to check first to avoid defining a title if none exists // (we don't want to cause an element to start matching [title]) // // We use removeAttr only for key events, to allow IE to export the correct // accessible attributes. For mouse events, set to empty string to avoid // native tooltip showing up (happens only when removing inside mouseover). if ( target.is( "[title]" ) ) { if ( event && event.type === "mouseover" ) { target.attr( "title", "" ); } else { target.removeAttr( "title" ); } } tooltip = this._tooltip( target ); addDescribedBy( target, tooltip.attr( "id" ) ); tooltip.find( ".ui-tooltip-content" ).html( content ); function position( event ) { positionOption.of = event; if ( tooltip.is( ":hidden" ) ) { return; } tooltip.position( positionOption ); } if ( this.options.track && event && /^mouse/.test( event.type ) ) { this._on( this.document, { mousemove: position }); // trigger once to override element-relative positioning position( event ); } else { tooltip.position( $.extend({ of: target }, this.options.position ) ); } tooltip.hide(); this._show( tooltip, this.options.show ); // Handle tracking tooltips that are shown with a delay (#8644). As soon // as the tooltip is visible, position the tooltip using the most recent // event. if ( this.options.show && this.options.show.delay ) { delayedShow = this.delayedShow = setInterval(function() { if ( tooltip.is( ":visible" ) ) { position( positionOption.of ); clearInterval( delayedShow ); } }, $.fx.interval ); } this._trigger( "open", event, { tooltip: tooltip } ); events = { keyup: function( event ) { if ( event.keyCode === $.ui.keyCode.ESCAPE ) { var fakeEvent = $.Event(event); fakeEvent.currentTarget = target[0]; this.close( fakeEvent, true ); } }, remove: function() { this._removeTooltip( tooltip ); } }; if ( !event || event.type === "mouseover" ) { events.mouseleave = "close"; } if ( !event || event.type === "focusin" ) { events.focusout = "close"; } this._on( true, target, events ); }, close: function( event ) { var that = this, target = $( event ? event.currentTarget : this.element ), tooltip = this._find( target ); // disabling closes the tooltip, so we need to track when we're closing // to avoid an infinite loop in case the tooltip becomes disabled on close if ( this.closing ) { return; } // Clear the interval for delayed tracking tooltips clearInterval( this.delayedShow ); // only set title if we had one before (see comment in _open()) if ( target.data( "ui-tooltip-title" ) ) { target.attr( "title", target.data( "ui-tooltip-title" ) ); } removeDescribedBy( target ); tooltip.stop( true ); this._hide( tooltip, this.options.hide, function() { that._removeTooltip( $( this ) ); }); target.removeData( "ui-tooltip-open" ); this._off( target, "mouseleave focusout keyup" ); // Remove 'remove' binding only on delegated targets if ( target[0] !== this.element[0] ) { this._off( target, "remove" ); } this._off( this.document, "mousemove" ); if ( event && event.type === "mouseleave" ) { $.each( this.parents, function( id, parent ) { $( parent.element ).attr( "title", parent.title ); delete that.parents[ id ]; }); } this.closing = true; this._trigger( "close", event, { tooltip: tooltip } ); this.closing = false; }, _tooltip: function( element ) { var id = "ui-tooltip-" + increments++, tooltip = $( "<div>" ) .attr({ id: id, role: "tooltip" }) .addClass( "ui-tooltip ui-widget ui-corner-all ui-widget-content " + ( this.options.tooltipClass || "" ) ); $( "<div>" ) .addClass( "ui-tooltip-content" ) .appendTo( tooltip ); tooltip.appendTo( this.document[0].body ); this.tooltips[ id ] = element; return tooltip; }, _find: function( target ) { var id = target.data( "ui-tooltip-id" ); return id ? $( "#" + id ) : $(); }, _removeTooltip: function( tooltip ) { tooltip.remove(); delete this.tooltips[ tooltip.attr( "id" ) ]; }, _destroy: function() { var that = this; // close open tooltips $.each( this.tooltips, function( id, element ) { // Delegate to close method to handle common cleanup var event = $.Event( "blur" ); event.target = event.currentTarget = element[0]; that.close( event, true ); // Remove immediately; destroying an open tooltip doesn't use the // hide animation $( "#" + id ).remove(); // Restore the title if ( element.data( "ui-tooltip-title" ) ) { element.attr( "title", element.data( "ui-tooltip-title" ) ); element.removeData( "ui-tooltip-title" ); } }); } }); }( jQuery ) ); (function($, undefined) { var dataSpace = "ui-effects-"; $.effects = { effect: {} }; /*! * jQuery Color Animations v2.1.2 * https://github.com/jquery/jquery-color * * Copyright 2013 jQuery Foundation and other contributors * Released under the MIT license. * http://jquery.org/license * * Date: Wed Jan 16 08:47:09 2013 -0600 */ (function( jQuery, undefined ) { var stepHooks = "backgroundColor borderBottomColor borderLeftColor borderRightColor borderTopColor color columnRuleColor outlineColor textDecorationColor textEmphasisColor", // plusequals test for += 100 -= 100 rplusequals = /^([\-+])=\s*(\d+\.?\d*)/, // a set of RE's that can match strings and generate color tuples. stringParsers = [{ re: /rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*(?:,\s*(\d?(?:\.\d+)?)\s*)?\)/, parse: function( execResult ) { return [ execResult[ 1 ], execResult[ 2 ], execResult[ 3 ], execResult[ 4 ] ]; } }, { re: /rgba?\(\s*(\d+(?:\.\d+)?)\%\s*,\s*(\d+(?:\.\d+)?)\%\s*,\s*(\d+(?:\.\d+)?)\%\s*(?:,\s*(\d?(?:\.\d+)?)\s*)?\)/, parse: function( execResult ) { return [ execResult[ 1 ] * 2.55, execResult[ 2 ] * 2.55, execResult[ 3 ] * 2.55, execResult[ 4 ] ]; } }, { // this regex ignores A-F because it's compared against an already lowercased string re: /#([a-f0-9]{2})([a-f0-9]{2})([a-f0-9]{2})/, parse: function( execResult ) { return [ parseInt( execResult[ 1 ], 16 ), parseInt( execResult[ 2 ], 16 ), parseInt( execResult[ 3 ], 16 ) ]; } }, { // this regex ignores A-F because it's compared against an already lowercased string re: /#([a-f0-9])([a-f0-9])([a-f0-9])/, parse: function( execResult ) { return [ parseInt( execResult[ 1 ] + execResult[ 1 ], 16 ), parseInt( execResult[ 2 ] + execResult[ 2 ], 16 ), parseInt( execResult[ 3 ] + execResult[ 3 ], 16 ) ]; } }, { re: /hsla?\(\s*(\d+(?:\.\d+)?)\s*,\s*(\d+(?:\.\d+)?)\%\s*,\s*(\d+(?:\.\d+)?)\%\s*(?:,\s*(\d?(?:\.\d+)?)\s*)?\)/, space: "hsla", parse: function( execResult ) { return [ execResult[ 1 ], execResult[ 2 ] / 100, execResult[ 3 ] / 100, execResult[ 4 ] ]; } }], // jQuery.Color( ) color = jQuery.Color = function( color, green, blue, alpha ) { return new jQuery.Color.fn.parse( color, green, blue, alpha ); }, spaces = { rgba: { props: { red: { idx: 0, type: "byte" }, green: { idx: 1, type: "byte" }, blue: { idx: 2, type: "byte" } } }, hsla: { props: { hue: { idx: 0, type: "degrees" }, saturation: { idx: 1, type: "percent" }, lightness: { idx: 2, type: "percent" } } } }, propTypes = { "byte": { floor: true, max: 255 }, "percent": { max: 1 }, "degrees": { mod: 360, floor: true } }, support = color.support = {}, // element for support tests supportElem = jQuery( "<p>" )[ 0 ], // colors = jQuery.Color.names colors, // local aliases of functions called often each = jQuery.each; // determine rgba support immediately supportElem.style.cssText = "background-color:rgba(1,1,1,.5)"; support.rgba = supportElem.style.backgroundColor.indexOf( "rgba" ) > -1; // define cache name and alpha properties // for rgba and hsla spaces each( spaces, function( spaceName, space ) { space.cache = "_" + spaceName; space.props.alpha = { idx: 3, type: "percent", def: 1 }; }); function clamp( value, prop, allowEmpty ) { var type = propTypes[ prop.type ] || {}; if ( value == null ) { return (allowEmpty || !prop.def) ? null : prop.def; } // ~~ is an short way of doing floor for positive numbers value = type.floor ? ~~value : parseFloat( value ); // IE will pass in empty strings as value for alpha, // which will hit this case if ( isNaN( value ) ) { return prop.def; } if ( type.mod ) { // we add mod before modding to make sure that negatives values // get converted properly: -10 -> 350 return (value + type.mod) % type.mod; } // for now all property types without mod have min and max return 0 > value ? 0 : type.max < value ? type.max : value; } function stringParse( string ) { var inst = color(), rgba = inst._rgba = []; string = string.toLowerCase(); each( stringParsers, function( i, parser ) { var parsed, match = parser.re.exec( string ), values = match && parser.parse( match ), spaceName = parser.space || "rgba"; if ( values ) { parsed = inst[ spaceName ]( values ); // if this was an rgba parse the assignment might happen twice // oh well.... inst[ spaces[ spaceName ].cache ] = parsed[ spaces[ spaceName ].cache ]; rgba = inst._rgba = parsed._rgba; // exit each( stringParsers ) here because we matched return false; } }); // Found a stringParser that handled it if ( rgba.length ) { // if this came from a parsed string, force "transparent" when alpha is 0 // chrome, (and maybe others) return "transparent" as rgba(0,0,0,0) if ( rgba.join() === "0,0,0,0" ) { jQuery.extend( rgba, colors.transparent ); } return inst; } // named colors return colors[ string ]; } color.fn = jQuery.extend( color.prototype, { parse: function( red, green, blue, alpha ) { if ( red === undefined ) { this._rgba = [ null, null, null, null ]; return this; } if ( red.jquery || red.nodeType ) { red = jQuery( red ).css( green ); green = undefined; } var inst = this, type = jQuery.type( red ), rgba = this._rgba = []; // more than 1 argument specified - assume ( red, green, blue, alpha ) if ( green !== undefined ) { red = [ red, green, blue, alpha ]; type = "array"; } if ( type === "string" ) { return this.parse( stringParse( red ) || colors._default ); } if ( type === "array" ) { each( spaces.rgba.props, function( key, prop ) { rgba[ prop.idx ] = clamp( red[ prop.idx ], prop ); }); return this; } if ( type === "object" ) { if ( red instanceof color ) { each( spaces, function( spaceName, space ) { if ( red[ space.cache ] ) { inst[ space.cache ] = red[ space.cache ].slice(); } }); } else { each( spaces, function( spaceName, space ) { var cache = space.cache; each( space.props, function( key, prop ) { // if the cache doesn't exist, and we know how to convert if ( !inst[ cache ] && space.to ) { // if the value was null, we don't need to copy it // if the key was alpha, we don't need to copy it either if ( key === "alpha" || red[ key ] == null ) { return; } inst[ cache ] = space.to( inst._rgba ); } // this is the only case where we allow nulls for ALL properties. // call clamp with alwaysAllowEmpty inst[ cache ][ prop.idx ] = clamp( red[ key ], prop, true ); }); // everything defined but alpha? if ( inst[ cache ] && jQuery.inArray( null, inst[ cache ].slice( 0, 3 ) ) < 0 ) { // use the default of 1 inst[ cache ][ 3 ] = 1; if ( space.from ) { inst._rgba = space.from( inst[ cache ] ); } } }); } return this; } }, is: function( compare ) { var is = color( compare ), same = true, inst = this; each( spaces, function( _, space ) { var localCache, isCache = is[ space.cache ]; if (isCache) { localCache = inst[ space.cache ] || space.to && space.to( inst._rgba ) || []; each( space.props, function( _, prop ) { if ( isCache[ prop.idx ] != null ) { same = ( isCache[ prop.idx ] === localCache[ prop.idx ] ); return same; } }); } return same; }); return same; }, _space: function() { var used = [], inst = this; each( spaces, function( spaceName, space ) { if ( inst[ space.cache ] ) { used.push( spaceName ); } }); return used.pop(); }, transition: function( other, distance ) { var end = color( other ), spaceName = end._space(), space = spaces[ spaceName ], startColor = this.alpha() === 0 ? color( "transparent" ) : this, start = startColor[ space.cache ] || space.to( startColor._rgba ), result = start.slice(); end = end[ space.cache ]; each( space.props, function( key, prop ) { var index = prop.idx, startValue = start[ index ], endValue = end[ index ], type = propTypes[ prop.type ] || {}; // if null, don't override start value if ( endValue === null ) { return; } // if null - use end if ( startValue === null ) { result[ index ] = endValue; } else { if ( type.mod ) { if ( endValue - startValue > type.mod / 2 ) { startValue += type.mod; } else if ( startValue - endValue > type.mod / 2 ) { startValue -= type.mod; } } result[ index ] = clamp( ( endValue - startValue ) * distance + startValue, prop ); } }); return this[ spaceName ]( result ); }, blend: function( opaque ) { // if we are already opaque - return ourself if ( this._rgba[ 3 ] === 1 ) { return this; } var rgb = this._rgba.slice(), a = rgb.pop(), blend = color( opaque )._rgba; return color( jQuery.map( rgb, function( v, i ) { return ( 1 - a ) * blend[ i ] + a * v; })); }, toRgbaString: function() { var prefix = "rgba(", rgba = jQuery.map( this._rgba, function( v, i ) { return v == null ? ( i > 2 ? 1 : 0 ) : v; }); if ( rgba[ 3 ] === 1 ) { rgba.pop(); prefix = "rgb("; } return prefix + rgba.join() + ")"; }, toHslaString: function() { var prefix = "hsla(", hsla = jQuery.map( this.hsla(), function( v, i ) { if ( v == null ) { v = i > 2 ? 1 : 0; } // catch 1 and 2 if ( i && i < 3 ) { v = Math.round( v * 100 ) + "%"; } return v; }); if ( hsla[ 3 ] === 1 ) { hsla.pop(); prefix = "hsl("; } return prefix + hsla.join() + ")"; }, toHexString: function( includeAlpha ) { var rgba = this._rgba.slice(), alpha = rgba.pop(); if ( includeAlpha ) { rgba.push( ~~( alpha * 255 ) ); } return "#" + jQuery.map( rgba, function( v ) { // default to 0 when nulls exist v = ( v || 0 ).toString( 16 ); return v.length === 1 ? "0" + v : v; }).join(""); }, toString: function() { return this._rgba[ 3 ] === 0 ? "transparent" : this.toRgbaString(); } }); color.fn.parse.prototype = color.fn; // hsla conversions adapted from: // https://code.google.com/p/maashaack/source/browse/packages/graphics/trunk/src/graphics/colors/HUE2RGB.as?r=5021 function hue2rgb( p, q, h ) { h = ( h + 1 ) % 1; if ( h * 6 < 1 ) { return p + (q - p) * h * 6; } if ( h * 2 < 1) { return q; } if ( h * 3 < 2 ) { return p + (q - p) * ((2/3) - h) * 6; } return p; } spaces.hsla.to = function ( rgba ) { if ( rgba[ 0 ] == null || rgba[ 1 ] == null || rgba[ 2 ] == null ) { return [ null, null, null, rgba[ 3 ] ]; } var r = rgba[ 0 ] / 255, g = rgba[ 1 ] / 255, b = rgba[ 2 ] / 255, a = rgba[ 3 ], max = Math.max( r, g, b ), min = Math.min( r, g, b ), diff = max - min, add = max + min, l = add * 0.5, h, s; if ( min === max ) { h = 0; } else if ( r === max ) { h = ( 60 * ( g - b ) / diff ) + 360; } else if ( g === max ) { h = ( 60 * ( b - r ) / diff ) + 120; } else { h = ( 60 * ( r - g ) / diff ) + 240; } // chroma (diff) == 0 means greyscale which, by definition, saturation = 0% // otherwise, saturation is based on the ratio of chroma (diff) to lightness (add) if ( diff === 0 ) { s = 0; } else if ( l <= 0.5 ) { s = diff / add; } else { s = diff / ( 2 - add ); } return [ Math.round(h) % 360, s, l, a == null ? 1 : a ]; }; spaces.hsla.from = function ( hsla ) { if ( hsla[ 0 ] == null || hsla[ 1 ] == null || hsla[ 2 ] == null ) { return [ null, null, null, hsla[ 3 ] ]; } var h = hsla[ 0 ] / 360, s = hsla[ 1 ], l = hsla[ 2 ], a = hsla[ 3 ], q = l <= 0.5 ? l * ( 1 + s ) : l + s - l * s, p = 2 * l - q; return [ Math.round( hue2rgb( p, q, h + ( 1 / 3 ) ) * 255 ), Math.round( hue2rgb( p, q, h ) * 255 ), Math.round( hue2rgb( p, q, h - ( 1 / 3 ) ) * 255 ), a ]; }; each( spaces, function( spaceName, space ) { var props = space.props, cache = space.cache, to = space.to, from = space.from; // makes rgba() and hsla() color.fn[ spaceName ] = function( value ) { // generate a cache for this space if it doesn't exist if ( to && !this[ cache ] ) { this[ cache ] = to( this._rgba ); } if ( value === undefined ) { return this[ cache ].slice(); } var ret, type = jQuery.type( value ), arr = ( type === "array" || type === "object" ) ? value : arguments, local = this[ cache ].slice(); each( props, function( key, prop ) { var val = arr[ type === "object" ? key : prop.idx ]; if ( val == null ) { val = local[ prop.idx ]; } local[ prop.idx ] = clamp( val, prop ); }); if ( from ) { ret = color( from( local ) ); ret[ cache ] = local; return ret; } else { return color( local ); } }; // makes red() green() blue() alpha() hue() saturation() lightness() each( props, function( key, prop ) { // alpha is included in more than one space if ( color.fn[ key ] ) { return; } color.fn[ key ] = function( value ) { var vtype = jQuery.type( value ), fn = ( key === "alpha" ? ( this._hsla ? "hsla" : "rgba" ) : spaceName ), local = this[ fn ](), cur = local[ prop.idx ], match; if ( vtype === "undefined" ) { return cur; } if ( vtype === "function" ) { value = value.call( this, cur ); vtype = jQuery.type( value ); } if ( value == null && prop.empty ) { return this; } if ( vtype === "string" ) { match = rplusequals.exec( value ); if ( match ) { value = cur + parseFloat( match[ 2 ] ) * ( match[ 1 ] === "+" ? 1 : -1 ); } } local[ prop.idx ] = value; return this[ fn ]( local ); }; }); }); // add cssHook and .fx.step function for each named hook. // accept a space separated string of properties color.hook = function( hook ) { var hooks = hook.split( " " ); each( hooks, function( i, hook ) { jQuery.cssHooks[ hook ] = { set: function( elem, value ) { var parsed, curElem, backgroundColor = ""; if ( value !== "transparent" && ( jQuery.type( value ) !== "string" || ( parsed = stringParse( value ) ) ) ) { value = color( parsed || value ); if ( !support.rgba && value._rgba[ 3 ] !== 1 ) { curElem = hook === "backgroundColor" ? elem.parentNode : elem; while ( (backgroundColor === "" || backgroundColor === "transparent") && curElem && curElem.style ) { try { backgroundColor = jQuery.css( curElem, "backgroundColor" ); curElem = curElem.parentNode; } catch ( e ) { } } value = value.blend( backgroundColor && backgroundColor !== "transparent" ? backgroundColor : "_default" ); } value = value.toRgbaString(); } try { elem.style[ hook ] = value; } catch( e ) { // wrapped to prevent IE from throwing errors on "invalid" values like 'auto' or 'inherit' } } }; jQuery.fx.step[ hook ] = function( fx ) { if ( !fx.colorInit ) { fx.start = color( fx.elem, hook ); fx.end = color( fx.end ); fx.colorInit = true; } jQuery.cssHooks[ hook ].set( fx.elem, fx.start.transition( fx.end, fx.pos ) ); }; }); }; color.hook( stepHooks ); jQuery.cssHooks.borderColor = { expand: function( value ) { var expanded = {}; each( [ "Top", "Right", "Bottom", "Left" ], function( i, part ) { expanded[ "border" + part + "Color" ] = value; }); return expanded; } }; // Basic color names only. // Usage of any of the other color names requires adding yourself or including // jquery.color.svg-names.js. colors = jQuery.Color.names = { // 4.1. Basic color keywords aqua: "#00ffff", black: "#000000", blue: "#0000ff", fuchsia: "#ff00ff", gray: "#808080", green: "#008000", lime: "#00ff00", maroon: "#800000", navy: "#000080", olive: "#808000", purple: "#800080", red: "#ff0000", silver: "#c0c0c0", teal: "#008080", white: "#ffffff", yellow: "#ffff00", // 4.2.3. "transparent" color keyword transparent: [ null, null, null, 0 ], _default: "#ffffff" }; })( jQuery ); /******************************************************************************/ /****************************** CLASS ANIMATIONS ******************************/ /******************************************************************************/ (function() { var classAnimationActions = [ "add", "remove", "toggle" ], shorthandStyles = { border: 1, borderBottom: 1, borderColor: 1, borderLeft: 1, borderRight: 1, borderTop: 1, borderWidth: 1, margin: 1, padding: 1 }; $.each([ "borderLeftStyle", "borderRightStyle", "borderBottomStyle", "borderTopStyle" ], function( _, prop ) { $.fx.step[ prop ] = function( fx ) { if ( fx.end !== "none" && !fx.setAttr || fx.pos === 1 && !fx.setAttr ) { jQuery.style( fx.elem, prop, fx.end ); fx.setAttr = true; } }; }); function getElementStyles( elem ) { var key, len, style = elem.ownerDocument.defaultView ? elem.ownerDocument.defaultView.getComputedStyle( elem, null ) : elem.currentStyle, styles = {}; if ( style && style.length && style[ 0 ] && style[ style[ 0 ] ] ) { len = style.length; while ( len-- ) { key = style[ len ]; if ( typeof style[ key ] === "string" ) { styles[ $.camelCase( key ) ] = style[ key ]; } } // support: Opera, IE <9 } else { for ( key in style ) { if ( typeof style[ key ] === "string" ) { styles[ key ] = style[ key ]; } } } return styles; } function styleDifference( oldStyle, newStyle ) { var diff = {}, name, value; for ( name in newStyle ) { value = newStyle[ name ]; if ( oldStyle[ name ] !== value ) { if ( !shorthandStyles[ name ] ) { if ( $.fx.step[ name ] || !isNaN( parseFloat( value ) ) ) { diff[ name ] = value; } } } } return diff; } // support: jQuery <1.8 if ( !$.fn.addBack ) { $.fn.addBack = function( selector ) { return this.add( selector == null ? this.prevObject : this.prevObject.filter( selector ) ); }; } $.effects.animateClass = function( value, duration, easing, callback ) { var o = $.speed( duration, easing, callback ); return this.queue( function() { var animated = $( this ), baseClass = animated.attr( "class" ) || "", applyClassChange, allAnimations = o.children ? animated.find( "*" ).addBack() : animated; // map the animated objects to store the original styles. allAnimations = allAnimations.map(function() { var el = $( this ); return { el: el, start: getElementStyles( this ) }; }); // apply class change applyClassChange = function() { $.each( classAnimationActions, function(i, action) { if ( value[ action ] ) { animated[ action + "Class" ]( value[ action ] ); } }); }; applyClassChange(); // map all animated objects again - calculate new styles and diff allAnimations = allAnimations.map(function() { this.end = getElementStyles( this.el[ 0 ] ); this.diff = styleDifference( this.start, this.end ); return this; }); // apply original class animated.attr( "class", baseClass ); // map all animated objects again - this time collecting a promise allAnimations = allAnimations.map(function() { var styleInfo = this, dfd = $.Deferred(), opts = $.extend({}, o, { queue: false, complete: function() { dfd.resolve( styleInfo ); } }); this.el.animate( this.diff, opts ); return dfd.promise(); }); // once all animations have completed: $.when.apply( $, allAnimations.get() ).done(function() { // set the final class applyClassChange(); // for each animated element, // clear all css properties that were animated $.each( arguments, function() { var el = this.el; $.each( this.diff, function(key) { el.css( key, "" ); }); }); // this is guarnteed to be there if you use jQuery.speed() // it also handles dequeuing the next anim... o.complete.call( animated[ 0 ] ); }); }); }; $.fn.extend({ addClass: (function( orig ) { return function( classNames, speed, easing, callback ) { return speed ? $.effects.animateClass.call( this, { add: classNames }, speed, easing, callback ) : orig.apply( this, arguments ); }; })( $.fn.addClass ), removeClass: (function( orig ) { return function( classNames, speed, easing, callback ) { return arguments.length > 1 ? $.effects.animateClass.call( this, { remove: classNames }, speed, easing, callback ) : orig.apply( this, arguments ); }; })( $.fn.removeClass ), toggleClass: (function( orig ) { return function( classNames, force, speed, easing, callback ) { if ( typeof force === "boolean" || force === undefined ) { if ( !speed ) { // without speed parameter return orig.apply( this, arguments ); } else { return $.effects.animateClass.call( this, (force ? { add: classNames } : { remove: classNames }), speed, easing, callback ); } } else { // without force parameter return $.effects.animateClass.call( this, { toggle: classNames }, force, speed, easing ); } }; })( $.fn.toggleClass ), switchClass: function( remove, add, speed, easing, callback) { return $.effects.animateClass.call( this, { add: add, remove: remove }, speed, easing, callback ); } }); })(); /******************************************************************************/ /*********************************** EFFECTS **********************************/ /******************************************************************************/ (function() { $.extend( $.effects, { version: "1.10.3", // Saves a set of properties in a data storage save: function( element, set ) { for( var i=0; i < set.length; i++ ) { if ( set[ i ] !== null ) { element.data( dataSpace + set[ i ], element[ 0 ].style[ set[ i ] ] ); } } }, // Restores a set of previously saved properties from a data storage restore: function( element, set ) { var val, i; for( i=0; i < set.length; i++ ) { if ( set[ i ] !== null ) { val = element.data( dataSpace + set[ i ] ); // support: jQuery 1.6.2 // http://bugs.jquery.com/ticket/9917 // jQuery 1.6.2 incorrectly returns undefined for any falsy value. // We can't differentiate between "" and 0 here, so we just assume // empty string since it's likely to be a more common value... if ( val === undefined ) { val = ""; } element.css( set[ i ], val ); } } }, setMode: function( el, mode ) { if (mode === "toggle") { mode = el.is( ":hidden" ) ? "show" : "hide"; } return mode; }, // Translates a [top,left] array into a baseline value // this should be a little more flexible in the future to handle a string & hash getBaseline: function( origin, original ) { var y, x; switch ( origin[ 0 ] ) { case "top": y = 0; break; case "middle": y = 0.5; break; case "bottom": y = 1; break; default: y = origin[ 0 ] / original.height; } switch ( origin[ 1 ] ) { case "left": x = 0; break; case "center": x = 0.5; break; case "right": x = 1; break; default: x = origin[ 1 ] / original.width; } return { x: x, y: y }; }, // Wraps the element around a wrapper that copies position properties createWrapper: function( element ) { // if the element is already wrapped, return it if ( element.parent().is( ".ui-effects-wrapper" )) { return element.parent(); } // wrap the element var props = { width: element.outerWidth(true), height: element.outerHeight(true), "float": element.css( "float" ) }, wrapper = $( "<div></div>" ) .addClass( "ui-effects-wrapper" ) .css({ fontSize: "100%", background: "transparent", border: "none", margin: 0, padding: 0 }), // Store the size in case width/height are defined in % - Fixes #5245 size = { width: element.width(), height: element.height() }, active = document.activeElement; // support: Firefox // Firefox incorrectly exposes anonymous content // https://bugzilla.mozilla.org/show_bug.cgi?id=561664 try { active.id; } catch( e ) { active = document.body; } element.wrap( wrapper ); // Fixes #7595 - Elements lose focus when wrapped. if ( element[ 0 ] === active || $.contains( element[ 0 ], active ) ) { $( active ).focus(); } wrapper = element.parent(); //Hotfix for jQuery 1.4 since some change in wrap() seems to actually lose the reference to the wrapped element // transfer positioning properties to the wrapper if ( element.css( "position" ) === "static" ) { wrapper.css({ position: "relative" }); element.css({ position: "relative" }); } else { $.extend( props, { position: element.css( "position" ), zIndex: element.css( "z-index" ) }); $.each([ "top", "left", "bottom", "right" ], function(i, pos) { props[ pos ] = element.css( pos ); if ( isNaN( parseInt( props[ pos ], 10 ) ) ) { props[ pos ] = "auto"; } }); element.css({ position: "relative", top: 0, left: 0, right: "auto", bottom: "auto" }); } element.css(size); return wrapper.css( props ).show(); }, removeWrapper: function( element ) { var active = document.activeElement; if ( element.parent().is( ".ui-effects-wrapper" ) ) { element.parent().replaceWith( element ); // Fixes #7595 - Elements lose focus when wrapped. if ( element[ 0 ] === active || $.contains( element[ 0 ], active ) ) { $( active ).focus(); } } return element; }, setTransition: function( element, list, factor, value ) { value = value || {}; $.each( list, function( i, x ) { var unit = element.cssUnit( x ); if ( unit[ 0 ] > 0 ) { value[ x ] = unit[ 0 ] * factor + unit[ 1 ]; } }); return value; } }); // return an effect options object for the given parameters: function _normalizeArguments( effect, options, speed, callback ) { // allow passing all options as the first parameter if ( $.isPlainObject( effect ) ) { options = effect; effect = effect.effect; } // convert to an object effect = { effect: effect }; // catch (effect, null, ...) if ( options == null ) { options = {}; } // catch (effect, callback) if ( $.isFunction( options ) ) { callback = options; speed = null; options = {}; } // catch (effect, speed, ?) if ( typeof options === "number" || $.fx.speeds[ options ] ) { callback = speed; speed = options; options = {}; } // catch (effect, options, callback) if ( $.isFunction( speed ) ) { callback = speed; speed = null; } // add options to effect if ( options ) { $.extend( effect, options ); } speed = speed || options.duration; effect.duration = $.fx.off ? 0 : typeof speed === "number" ? speed : speed in $.fx.speeds ? $.fx.speeds[ speed ] : $.fx.speeds._default; effect.complete = callback || options.complete; return effect; } function standardAnimationOption( option ) { // Valid standard speeds (nothing, number, named speed) if ( !option || typeof option === "number" || $.fx.speeds[ option ] ) { return true; } // Invalid strings - treat as "normal" speed if ( typeof option === "string" && !$.effects.effect[ option ] ) { return true; } // Complete callback if ( $.isFunction( option ) ) { return true; } // Options hash (but not naming an effect) if ( typeof option === "object" && !option.effect ) { return true; } // Didn't match any standard API return false; } $.fn.extend({ effect: function( /* effect, options, speed, callback */ ) { var args = _normalizeArguments.apply( this, arguments ), mode = args.mode, queue = args.queue, effectMethod = $.effects.effect[ args.effect ]; if ( $.fx.off || !effectMethod ) { // delegate to the original method (e.g., .show()) if possible if ( mode ) { return this[ mode ]( args.duration, args.complete ); } else { return this.each( function() { if ( args.complete ) { args.complete.call( this ); } }); } } function run( next ) { var elem = $( this ), complete = args.complete, mode = args.mode; function done() { if ( $.isFunction( complete ) ) { complete.call( elem[0] ); } if ( $.isFunction( next ) ) { next(); } } // If the element already has the correct final state, delegate to // the core methods so the internal tracking of "olddisplay" works. if ( elem.is( ":hidden" ) ? mode === "hide" : mode === "show" ) { elem[ mode ](); done(); } else { effectMethod.call( elem[0], args, done ); } } return queue === false ? this.each( run ) : this.queue( queue || "fx", run ); }, show: (function( orig ) { return function( option ) { if ( standardAnimationOption( option ) ) { return orig.apply( this, arguments ); } else { var args = _normalizeArguments.apply( this, arguments ); args.mode = "show"; return this.effect.call( this, args ); } }; })( $.fn.show ), hide: (function( orig ) { return function( option ) { if ( standardAnimationOption( option ) ) { return orig.apply( this, arguments ); } else { var args = _normalizeArguments.apply( this, arguments ); args.mode = "hide"; return this.effect.call( this, args ); } }; })( $.fn.hide ), toggle: (function( orig ) { return function( option ) { if ( standardAnimationOption( option ) || typeof option === "boolean" ) { return orig.apply( this, arguments ); } else { var args = _normalizeArguments.apply( this, arguments ); args.mode = "toggle"; return this.effect.call( this, args ); } }; })( $.fn.toggle ), // helper functions cssUnit: function(key) { var style = this.css( key ), val = []; $.each( [ "em", "px", "%", "pt" ], function( i, unit ) { if ( style.indexOf( unit ) > 0 ) { val = [ parseFloat( style ), unit ]; } }); return val; } }); })(); /******************************************************************************/ /*********************************** EASING ***********************************/ /******************************************************************************/ (function() { // based on easing equations from Robert Penner (http://www.robertpenner.com/easing) var baseEasings = {}; $.each( [ "Quad", "Cubic", "Quart", "Quint", "Expo" ], function( i, name ) { baseEasings[ name ] = function( p ) { return Math.pow( p, i + 2 ); }; }); $.extend( baseEasings, { Sine: function ( p ) { return 1 - Math.cos( p * Math.PI / 2 ); }, Circ: function ( p ) { return 1 - Math.sqrt( 1 - p * p ); }, Elastic: function( p ) { return p === 0 || p === 1 ? p : -Math.pow( 2, 8 * (p - 1) ) * Math.sin( ( (p - 1) * 80 - 7.5 ) * Math.PI / 15 ); }, Back: function( p ) { return p * p * ( 3 * p - 2 ); }, Bounce: function ( p ) { var pow2, bounce = 4; while ( p < ( ( pow2 = Math.pow( 2, --bounce ) ) - 1 ) / 11 ) {} return 1 / Math.pow( 4, 3 - bounce ) - 7.5625 * Math.pow( ( pow2 * 3 - 2 ) / 22 - p, 2 ); } }); $.each( baseEasings, function( name, easeIn ) { $.easing[ "easeIn" + name ] = easeIn; $.easing[ "easeOut" + name ] = function( p ) { return 1 - easeIn( 1 - p ); }; $.easing[ "easeInOut" + name ] = function( p ) { return p < 0.5 ? easeIn( p * 2 ) / 2 : 1 - easeIn( p * -2 + 2 ) / 2; }; }); })(); })(jQuery); (function( $, undefined ) { var rvertical = /up|down|vertical/, rpositivemotion = /up|left|vertical|horizontal/; $.effects.effect.blind = function( o, done ) { // Create element var el = $( this ), props = [ "position", "top", "bottom", "left", "right", "height", "width" ], mode = $.effects.setMode( el, o.mode || "hide" ), direction = o.direction || "up", vertical = rvertical.test( direction ), ref = vertical ? "height" : "width", ref2 = vertical ? "top" : "left", motion = rpositivemotion.test( direction ), animation = {}, show = mode === "show", wrapper, distance, margin; // if already wrapped, the wrapper's properties are my property. #6245 if ( el.parent().is( ".ui-effects-wrapper" ) ) { $.effects.save( el.parent(), props ); } else { $.effects.save( el, props ); } el.show(); wrapper = $.effects.createWrapper( el ).css({ overflow: "hidden" }); distance = wrapper[ ref ](); margin = parseFloat( wrapper.css( ref2 ) ) || 0; animation[ ref ] = show ? distance : 0; if ( !motion ) { el .css( vertical ? "bottom" : "right", 0 ) .css( vertical ? "top" : "left", "auto" ) .css({ position: "absolute" }); animation[ ref2 ] = show ? margin : distance + margin; } // start at 0 if we are showing if ( show ) { wrapper.css( ref, 0 ); if ( ! motion ) { wrapper.css( ref2, margin + distance ); } } // Animate wrapper.animate( animation, { duration: o.duration, easing: o.easing, queue: false, complete: function() { if ( mode === "hide" ) { el.hide(); } $.effects.restore( el, props ); $.effects.removeWrapper( el ); done(); } }); }; })(jQuery); (function( $, undefined ) { $.effects.effect.bounce = function( o, done ) { var el = $( this ), props = [ "position", "top", "bottom", "left", "right", "height", "width" ], // defaults: mode = $.effects.setMode( el, o.mode || "effect" ), hide = mode === "hide", show = mode === "show", direction = o.direction || "up", distance = o.distance, times = o.times || 5, // number of internal animations anims = times * 2 + ( show || hide ? 1 : 0 ), speed = o.duration / anims, easing = o.easing, // utility: ref = ( direction === "up" || direction === "down" ) ? "top" : "left", motion = ( direction === "up" || direction === "left" ), i, upAnim, downAnim, // we will need to re-assemble the queue to stack our animations in place queue = el.queue(), queuelen = queue.length; // Avoid touching opacity to prevent clearType and PNG issues in IE if ( show || hide ) { props.push( "opacity" ); } $.effects.save( el, props ); el.show(); $.effects.createWrapper( el ); // Create Wrapper // default distance for the BIGGEST bounce is the outer Distance / 3 if ( !distance ) { distance = el[ ref === "top" ? "outerHeight" : "outerWidth" ]() / 3; } if ( show ) { downAnim = { opacity: 1 }; downAnim[ ref ] = 0; // if we are showing, force opacity 0 and set the initial position // then do the "first" animation el.css( "opacity", 0 ) .css( ref, motion ? -distance * 2 : distance * 2 ) .animate( downAnim, speed, easing ); } // start at the smallest distance if we are hiding if ( hide ) { distance = distance / Math.pow( 2, times - 1 ); } downAnim = {}; downAnim[ ref ] = 0; // Bounces up/down/left/right then back to 0 -- times * 2 animations happen here for ( i = 0; i < times; i++ ) { upAnim = {}; upAnim[ ref ] = ( motion ? "-=" : "+=" ) + distance; el.animate( upAnim, speed, easing ) .animate( downAnim, speed, easing ); distance = hide ? distance * 2 : distance / 2; } // Last Bounce when Hiding if ( hide ) { upAnim = { opacity: 0 }; upAnim[ ref ] = ( motion ? "-=" : "+=" ) + distance; el.animate( upAnim, speed, easing ); } el.queue(function() { if ( hide ) { el.hide(); } $.effects.restore( el, props ); $.effects.removeWrapper( el ); done(); }); // inject all the animations we just queued to be first in line (after "inprogress") if ( queuelen > 1) { queue.splice.apply( queue, [ 1, 0 ].concat( queue.splice( queuelen, anims + 1 ) ) ); } el.dequeue(); }; })(jQuery); (function( $, undefined ) { $.effects.effect.clip = function( o, done ) { // Create element var el = $( this ), props = [ "position", "top", "bottom", "left", "right", "height", "width" ], mode = $.effects.setMode( el, o.mode || "hide" ), show = mode === "show", direction = o.direction || "vertical", vert = direction === "vertical", size = vert ? "height" : "width", position = vert ? "top" : "left", animation = {}, wrapper, animate, distance; // Save & Show $.effects.save( el, props ); el.show(); // Create Wrapper wrapper = $.effects.createWrapper( el ).css({ overflow: "hidden" }); animate = ( el[0].tagName === "IMG" ) ? wrapper : el; distance = animate[ size ](); // Shift if ( show ) { animate.css( size, 0 ); animate.css( position, distance / 2 ); } // Create Animation Object: animation[ size ] = show ? distance : 0; animation[ position ] = show ? 0 : distance / 2; // Animate animate.animate( animation, { queue: false, duration: o.duration, easing: o.easing, complete: function() { if ( !show ) { el.hide(); } $.effects.restore( el, props ); $.effects.removeWrapper( el ); done(); } }); }; })(jQuery); (function( $, undefined ) { $.effects.effect.drop = function( o, done ) { var el = $( this ), props = [ "position", "top", "bottom", "left", "right", "opacity", "height", "width" ], mode = $.effects.setMode( el, o.mode || "hide" ), show = mode === "show", direction = o.direction || "left", ref = ( direction === "up" || direction === "down" ) ? "top" : "left", motion = ( direction === "up" || direction === "left" ) ? "pos" : "neg", animation = { opacity: show ? 1 : 0 }, distance; // Adjust $.effects.save( el, props ); el.show(); $.effects.createWrapper( el ); distance = o.distance || el[ ref === "top" ? "outerHeight": "outerWidth" ]( true ) / 2; if ( show ) { el .css( "opacity", 0 ) .css( ref, motion === "pos" ? -distance : distance ); } // Animation animation[ ref ] = ( show ? ( motion === "pos" ? "+=" : "-=" ) : ( motion === "pos" ? "-=" : "+=" ) ) + distance; // Animate el.animate( animation, { queue: false, duration: o.duration, easing: o.easing, complete: function() { if ( mode === "hide" ) { el.hide(); } $.effects.restore( el, props ); $.effects.removeWrapper( el ); done(); } }); }; })(jQuery); (function( $, undefined ) { $.effects.effect.explode = function( o, done ) { var rows = o.pieces ? Math.round( Math.sqrt( o.pieces ) ) : 3, cells = rows, el = $( this ), mode = $.effects.setMode( el, o.mode || "hide" ), show = mode === "show", // show and then visibility:hidden the element before calculating offset offset = el.show().css( "visibility", "hidden" ).offset(), // width and height of a piece width = Math.ceil( el.outerWidth() / cells ), height = Math.ceil( el.outerHeight() / rows ), pieces = [], // loop i, j, left, top, mx, my; // children animate complete: function childComplete() { pieces.push( this ); if ( pieces.length === rows * cells ) { animComplete(); } } // clone the element for each row and cell. for( i = 0; i < rows ; i++ ) { // ===> top = offset.top + i * height; my = i - ( rows - 1 ) / 2 ; for( j = 0; j < cells ; j++ ) { // ||| left = offset.left + j * width; mx = j - ( cells - 1 ) / 2 ; // Create a clone of the now hidden main element that will be absolute positioned // within a wrapper div off the -left and -top equal to size of our pieces el .clone() .appendTo( "body" ) .wrap( "<div></div>" ) .css({ position: "absolute", visibility: "visible", left: -j * width, top: -i * height }) // select the wrapper - make it overflow: hidden and absolute positioned based on // where the original was located +left and +top equal to the size of pieces .parent() .addClass( "ui-effects-explode" ) .css({ position: "absolute", overflow: "hidden", width: width, height: height, left: left + ( show ? mx * width : 0 ), top: top + ( show ? my * height : 0 ), opacity: show ? 0 : 1 }).animate({ left: left + ( show ? 0 : mx * width ), top: top + ( show ? 0 : my * height ), opacity: show ? 1 : 0 }, o.duration || 500, o.easing, childComplete ); } } function animComplete() { el.css({ visibility: "visible" }); $( pieces ).remove(); if ( !show ) { el.hide(); } done(); } }; })(jQuery); (function( $, undefined ) { $.effects.effect.fade = function( o, done ) { var el = $( this ), mode = $.effects.setMode( el, o.mode || "toggle" ); el.animate({ opacity: mode }, { queue: false, duration: o.duration, easing: o.easing, complete: done }); }; })( jQuery ); (function( $, undefined ) { $.effects.effect.fold = function( o, done ) { // Create element var el = $( this ), props = [ "position", "top", "bottom", "left", "right", "height", "width" ], mode = $.effects.setMode( el, o.mode || "hide" ), show = mode === "show", hide = mode === "hide", size = o.size || 15, percent = /([0-9]+)%/.exec( size ), horizFirst = !!o.horizFirst, widthFirst = show !== horizFirst, ref = widthFirst ? [ "width", "height" ] : [ "height", "width" ], duration = o.duration / 2, wrapper, distance, animation1 = {}, animation2 = {}; $.effects.save( el, props ); el.show(); // Create Wrapper wrapper = $.effects.createWrapper( el ).css({ overflow: "hidden" }); distance = widthFirst ? [ wrapper.width(), wrapper.height() ] : [ wrapper.height(), wrapper.width() ]; if ( percent ) { size = parseInt( percent[ 1 ], 10 ) / 100 * distance[ hide ? 0 : 1 ]; } if ( show ) { wrapper.css( horizFirst ? { height: 0, width: size } : { height: size, width: 0 }); } // Animation animation1[ ref[ 0 ] ] = show ? distance[ 0 ] : size; animation2[ ref[ 1 ] ] = show ? distance[ 1 ] : 0; // Animate wrapper .animate( animation1, duration, o.easing ) .animate( animation2, duration, o.easing, function() { if ( hide ) { el.hide(); } $.effects.restore( el, props ); $.effects.removeWrapper( el ); done(); }); }; })(jQuery); (function( $, undefined ) { $.effects.effect.highlight = function( o, done ) { var elem = $( this ), props = [ "backgroundImage", "backgroundColor", "opacity" ], mode = $.effects.setMode( elem, o.mode || "show" ), animation = { backgroundColor: elem.css( "backgroundColor" ) }; if (mode === "hide") { animation.opacity = 0; } $.effects.save( elem, props ); elem .show() .css({ backgroundImage: "none", backgroundColor: o.color || "#ffff99" }) .animate( animation, { queue: false, duration: o.duration, easing: o.easing, complete: function() { if ( mode === "hide" ) { elem.hide(); } $.effects.restore( elem, props ); done(); } }); }; })(jQuery); (function( $, undefined ) { $.effects.effect.pulsate = function( o, done ) { var elem = $( this ), mode = $.effects.setMode( elem, o.mode || "show" ), show = mode === "show", hide = mode === "hide", showhide = ( show || mode === "hide" ), // showing or hiding leaves of the "last" animation anims = ( ( o.times || 5 ) * 2 ) + ( showhide ? 1 : 0 ), duration = o.duration / anims, animateTo = 0, queue = elem.queue(), queuelen = queue.length, i; if ( show || !elem.is(":visible")) { elem.css( "opacity", 0 ).show(); animateTo = 1; } // anims - 1 opacity "toggles" for ( i = 1; i < anims; i++ ) { elem.animate({ opacity: animateTo }, duration, o.easing ); animateTo = 1 - animateTo; } elem.animate({ opacity: animateTo }, duration, o.easing); elem.queue(function() { if ( hide ) { elem.hide(); } done(); }); // We just queued up "anims" animations, we need to put them next in the queue if ( queuelen > 1 ) { queue.splice.apply( queue, [ 1, 0 ].concat( queue.splice( queuelen, anims + 1 ) ) ); } elem.dequeue(); }; })(jQuery); (function( $, undefined ) { $.effects.effect.puff = function( o, done ) { var elem = $( this ), mode = $.effects.setMode( elem, o.mode || "hide" ), hide = mode === "hide", percent = parseInt( o.percent, 10 ) || 150, factor = percent / 100, original = { height: elem.height(), width: elem.width(), outerHeight: elem.outerHeight(), outerWidth: elem.outerWidth() }; $.extend( o, { effect: "scale", queue: false, fade: true, mode: mode, complete: done, percent: hide ? percent : 100, from: hide ? original : { height: original.height * factor, width: original.width * factor, outerHeight: original.outerHeight * factor, outerWidth: original.outerWidth * factor } }); elem.effect( o ); }; $.effects.effect.scale = function( o, done ) { // Create element var el = $( this ), options = $.extend( true, {}, o ), mode = $.effects.setMode( el, o.mode || "effect" ), percent = parseInt( o.percent, 10 ) || ( parseInt( o.percent, 10 ) === 0 ? 0 : ( mode === "hide" ? 0 : 100 ) ), direction = o.direction || "both", origin = o.origin, original = { height: el.height(), width: el.width(), outerHeight: el.outerHeight(), outerWidth: el.outerWidth() }, factor = { y: direction !== "horizontal" ? (percent / 100) : 1, x: direction !== "vertical" ? (percent / 100) : 1 }; // We are going to pass this effect to the size effect: options.effect = "size"; options.queue = false; options.complete = done; // Set default origin and restore for show/hide if ( mode !== "effect" ) { options.origin = origin || ["middle","center"]; options.restore = true; } options.from = o.from || ( mode === "show" ? { height: 0, width: 0, outerHeight: 0, outerWidth: 0 } : original ); options.to = { height: original.height * factor.y, width: original.width * factor.x, outerHeight: original.outerHeight * factor.y, outerWidth: original.outerWidth * factor.x }; // Fade option to support puff if ( options.fade ) { if ( mode === "show" ) { options.from.opacity = 0; options.to.opacity = 1; } if ( mode === "hide" ) { options.from.opacity = 1; options.to.opacity = 0; } } // Animate el.effect( options ); }; $.effects.effect.size = function( o, done ) { // Create element var original, baseline, factor, el = $( this ), props0 = [ "position", "top", "bottom", "left", "right", "width", "height", "overflow", "opacity" ], // Always restore props1 = [ "position", "top", "bottom", "left", "right", "overflow", "opacity" ], // Copy for children props2 = [ "width", "height", "overflow" ], cProps = [ "fontSize" ], vProps = [ "borderTopWidth", "borderBottomWidth", "paddingTop", "paddingBottom" ], hProps = [ "borderLeftWidth", "borderRightWidth", "paddingLeft", "paddingRight" ], // Set options mode = $.effects.setMode( el, o.mode || "effect" ), restore = o.restore || mode !== "effect", scale = o.scale || "both", origin = o.origin || [ "middle", "center" ], position = el.css( "position" ), props = restore ? props0 : props1, zero = { height: 0, width: 0, outerHeight: 0, outerWidth: 0 }; if ( mode === "show" ) { el.show(); } original = { height: el.height(), width: el.width(), outerHeight: el.outerHeight(), outerWidth: el.outerWidth() }; if ( o.mode === "toggle" && mode === "show" ) { el.from = o.to || zero; el.to = o.from || original; } else { el.from = o.from || ( mode === "show" ? zero : original ); el.to = o.to || ( mode === "hide" ? zero : original ); } // Set scaling factor factor = { from: { y: el.from.height / original.height, x: el.from.width / original.width }, to: { y: el.to.height / original.height, x: el.to.width / original.width } }; // Scale the css box if ( scale === "box" || scale === "both" ) { // Vertical props scaling if ( factor.from.y !== factor.to.y ) { props = props.concat( vProps ); el.from = $.effects.setTransition( el, vProps, factor.from.y, el.from ); el.to = $.effects.setTransition( el, vProps, factor.to.y, el.to ); } // Horizontal props scaling if ( factor.from.x !== factor.to.x ) { props = props.concat( hProps ); el.from = $.effects.setTransition( el, hProps, factor.from.x, el.from ); el.to = $.effects.setTransition( el, hProps, factor.to.x, el.to ); } } // Scale the content if ( scale === "content" || scale === "both" ) { // Vertical props scaling if ( factor.from.y !== factor.to.y ) { props = props.concat( cProps ).concat( props2 ); el.from = $.effects.setTransition( el, cProps, factor.from.y, el.from ); el.to = $.effects.setTransition( el, cProps, factor.to.y, el.to ); } } $.effects.save( el, props ); el.show(); $.effects.createWrapper( el ); el.css( "overflow", "hidden" ).css( el.from ); // Adjust if (origin) { // Calculate baseline shifts baseline = $.effects.getBaseline( origin, original ); el.from.top = ( original.outerHeight - el.outerHeight() ) * baseline.y; el.from.left = ( original.outerWidth - el.outerWidth() ) * baseline.x; el.to.top = ( original.outerHeight - el.to.outerHeight ) * baseline.y; el.to.left = ( original.outerWidth - el.to.outerWidth ) * baseline.x; } el.css( el.from ); // set top & left // Animate if ( scale === "content" || scale === "both" ) { // Scale the children // Add margins/font-size vProps = vProps.concat([ "marginTop", "marginBottom" ]).concat(cProps); hProps = hProps.concat([ "marginLeft", "marginRight" ]); props2 = props0.concat(vProps).concat(hProps); el.find( "*[width]" ).each( function(){ var child = $( this ), c_original = { height: child.height(), width: child.width(), outerHeight: child.outerHeight(), outerWidth: child.outerWidth() }; if (restore) { $.effects.save(child, props2); } child.from = { height: c_original.height * factor.from.y, width: c_original.width * factor.from.x, outerHeight: c_original.outerHeight * factor.from.y, outerWidth: c_original.outerWidth * factor.from.x }; child.to = { height: c_original.height * factor.to.y, width: c_original.width * factor.to.x, outerHeight: c_original.height * factor.to.y, outerWidth: c_original.width * factor.to.x }; // Vertical props scaling if ( factor.from.y !== factor.to.y ) { child.from = $.effects.setTransition( child, vProps, factor.from.y, child.from ); child.to = $.effects.setTransition( child, vProps, factor.to.y, child.to ); } // Horizontal props scaling if ( factor.from.x !== factor.to.x ) { child.from = $.effects.setTransition( child, hProps, factor.from.x, child.from ); child.to = $.effects.setTransition( child, hProps, factor.to.x, child.to ); } // Animate children child.css( child.from ); child.animate( child.to, o.duration, o.easing, function() { // Restore children if ( restore ) { $.effects.restore( child, props2 ); } }); }); } // Animate el.animate( el.to, { queue: false, duration: o.duration, easing: o.easing, complete: function() { if ( el.to.opacity === 0 ) { el.css( "opacity", el.from.opacity ); } if( mode === "hide" ) { el.hide(); } $.effects.restore( el, props ); if ( !restore ) { // we need to calculate our new positioning based on the scaling if ( position === "static" ) { el.css({ position: "relative", top: el.to.top, left: el.to.left }); } else { $.each([ "top", "left" ], function( idx, pos ) { el.css( pos, function( _, str ) { var val = parseInt( str, 10 ), toRef = idx ? el.to.left : el.to.top; // if original was "auto", recalculate the new value from wrapper if ( str === "auto" ) { return toRef + "px"; } return val + toRef + "px"; }); }); } } $.effects.removeWrapper( el ); done(); } }); }; })(jQuery); (function( $, undefined ) { $.effects.effect.shake = function( o, done ) { var el = $( this ), props = [ "position", "top", "bottom", "left", "right", "height", "width" ], mode = $.effects.setMode( el, o.mode || "effect" ), direction = o.direction || "left", distance = o.distance || 20, times = o.times || 3, anims = times * 2 + 1, speed = Math.round(o.duration/anims), ref = (direction === "up" || direction === "down") ? "top" : "left", positiveMotion = (direction === "up" || direction === "left"), animation = {}, animation1 = {}, animation2 = {}, i, // we will need to re-assemble the queue to stack our animations in place queue = el.queue(), queuelen = queue.length; $.effects.save( el, props ); el.show(); $.effects.createWrapper( el ); // Animation animation[ ref ] = ( positiveMotion ? "-=" : "+=" ) + distance; animation1[ ref ] = ( positiveMotion ? "+=" : "-=" ) + distance * 2; animation2[ ref ] = ( positiveMotion ? "-=" : "+=" ) + distance * 2; // Animate el.animate( animation, speed, o.easing ); // Shakes for ( i = 1; i < times; i++ ) { el.animate( animation1, speed, o.easing ).animate( animation2, speed, o.easing ); } el .animate( animation1, speed, o.easing ) .animate( animation, speed / 2, o.easing ) .queue(function() { if ( mode === "hide" ) { el.hide(); } $.effects.restore( el, props ); $.effects.removeWrapper( el ); done(); }); // inject all the animations we just queued to be first in line (after "inprogress") if ( queuelen > 1) { queue.splice.apply( queue, [ 1, 0 ].concat( queue.splice( queuelen, anims + 1 ) ) ); } el.dequeue(); }; })(jQuery); (function( $, undefined ) { $.effects.effect.slide = function( o, done ) { // Create element var el = $( this ), props = [ "position", "top", "bottom", "left", "right", "width", "height" ], mode = $.effects.setMode( el, o.mode || "show" ), show = mode === "show", direction = o.direction || "left", ref = (direction === "up" || direction === "down") ? "top" : "left", positiveMotion = (direction === "up" || direction === "left"), distance, animation = {}; // Adjust $.effects.save( el, props ); el.show(); distance = o.distance || el[ ref === "top" ? "outerHeight" : "outerWidth" ]( true ); $.effects.createWrapper( el ).css({ overflow: "hidden" }); if ( show ) { el.css( ref, positiveMotion ? (isNaN(distance) ? "-" + distance : -distance) : distance ); } // Animation animation[ ref ] = ( show ? ( positiveMotion ? "+=" : "-=") : ( positiveMotion ? "-=" : "+=")) + distance; // Animate el.animate( animation, { queue: false, duration: o.duration, easing: o.easing, complete: function() { if ( mode === "hide" ) { el.hide(); } $.effects.restore( el, props ); $.effects.removeWrapper( el ); done(); } }); }; })(jQuery); (function( $, undefined ) { $.effects.effect.transfer = function( o, done ) { var elem = $( this ), target = $( o.to ), targetFixed = target.css( "position" ) === "fixed", body = $("body"), fixTop = targetFixed ? body.scrollTop() : 0, fixLeft = targetFixed ? body.scrollLeft() : 0, endPosition = target.offset(), animation = { top: endPosition.top - fixTop , left: endPosition.left - fixLeft , height: target.innerHeight(), width: target.innerWidth() }, startPosition = elem.offset(), transfer = $( "<div class='ui-effects-transfer'></div>" ) .appendTo( document.body ) .addClass( o.className ) .css({ top: startPosition.top - fixTop , left: startPosition.left - fixLeft , height: elem.innerHeight(), width: elem.innerWidth(), position: targetFixed ? "fixed" : "absolute" }) .animate( animation, o.duration, o.easing, function() { transfer.remove(); done(); }); }; })(jQuery);
var browserify = require('../'); var test = require('tap').test; var path = require('path'); test('noParse array', function (t) { t.plan(2); var actual = []; var expected = [ 'noparse/a.js', 'noparse/b.js', 'noparse/dir1/1.js', 'noparse/node_modules/robot/main.js' ].map(function (x) {return path.resolve(x);}).sort(); var b = browserify({ entries: [ __dirname + '/noparse/a.js' ], noParse: [ __dirname + '/noparse/dir1/1.js', __dirname + '/noparse/node_modules/robot/main.js' ] }); b.on('dep', function(dep) { actual.push(dep.file); }); b.bundle(function (err, src) { actual.sort(); t.ifError(err); t.deepEqual(actual, expected); }); });
/* * * * Exporting module * * (c) 2010-2020 Torstein Honsi * * License: www.highcharts.com/license * * !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!! * * */ 'use strict'; import H from '../parts/Globals.js'; /** * Gets fired after a chart is printed through the context menu item or the * Chart.print method. * * @callback Highcharts.ExportingAfterPrintCallbackFunction * * @param {Highcharts.Chart} chart * The chart on which the event occured. * * @param {global.Event} event * The event that occured. */ /** * Gets fired before a chart is printed through the context menu item or the * Chart.print method. * * @callback Highcharts.ExportingBeforePrintCallbackFunction * * @param {Highcharts.Chart} chart * The chart on which the event occured. * * @param {global.Event} event * The event that occured. */ /** * Function to call if the offline-exporting module fails to export a chart on * the client side. * * @callback Highcharts.ExportingErrorCallbackFunction * * @param {Highcharts.ExportingOptions} options * The exporting options. * * @param {global.Error} err * The error from the module. */ /** * Definition for a menu item in the context menu. * * @interface Highcharts.ExportingMenuObject */ /** * The text for the menu item. * * @name Highcharts.ExportingMenuObject#text * @type {string|undefined} */ /** * If internationalization is required, the key to a language string. * * @name Highcharts.ExportingMenuObject#textKey * @type {string|undefined} */ /** * The click handler for the menu item. * * @name Highcharts.ExportingMenuObject#onclick * @type {Highcharts.EventCallbackFunction<Highcharts.Chart>|undefined} */ /** * Indicates a separator line instead of an item. * * @name Highcharts.ExportingMenuObject#separator * @type {boolean|undefined} */ /** * Possible MIME types for exporting. * * @typedef {"image/png"|"image/jpeg"|"application/pdf"|"image/svg+xml"} Highcharts.ExportingMimeTypeValue */ import U from '../parts/Utilities.js'; var addEvent = U.addEvent, css = U.css, createElement = U.createElement, discardElement = U.discardElement, extend = U.extend, find = U.find, fireEvent = U.fireEvent, isObject = U.isObject, merge = U.merge, objectEach = U.objectEach, pick = U.pick, removeEvent = U.removeEvent, uniqueKey = U.uniqueKey; import '../parts/Options.js'; import '../parts/Chart.js'; import chartNavigationMixin from '../mixins/navigation.js'; // create shortcuts var defaultOptions = H.defaultOptions, doc = H.doc, Chart = H.Chart, isTouchDevice = H.isTouchDevice, win = H.win, userAgent = win.navigator.userAgent, SVGRenderer = H.SVGRenderer, symbols = H.Renderer.prototype.symbols, isMSBrowser = /Edge\/|Trident\/|MSIE /.test(userAgent), isFirefoxBrowser = /firefox/i.test(userAgent); // Add language extend(defaultOptions.lang /** * @optionparent lang */ , { /** * Exporting module only. The text for the menu item to view the chart * in full screen. * * @since 8.0.1 * * @private */ viewFullscreen: 'View in full screen', /** * Exporting module only. The text for the menu item to exit the chart * from full screen. * * @since 8.0.1 * * @private */ exitFullscreen: 'Exit from full screen', /** * Exporting module only. The text for the menu item to print the chart. * * @since 3.0.1 * @requires modules/exporting * * @private */ printChart: 'Print chart', /** * Exporting module only. The text for the PNG download menu item. * * @since 2.0 * @requires modules/exporting * * @private */ downloadPNG: 'Download PNG image', /** * Exporting module only. The text for the JPEG download menu item. * * @since 2.0 * @requires modules/exporting * * @private */ downloadJPEG: 'Download JPEG image', /** * Exporting module only. The text for the PDF download menu item. * * @since 2.0 * @requires modules/exporting * * @private */ downloadPDF: 'Download PDF document', /** * Exporting module only. The text for the SVG download menu item. * * @since 2.0 * @requires modules/exporting * * @private */ downloadSVG: 'Download SVG vector image', /** * Exporting module menu. The tooltip title for the context menu holding * print and export menu items. * * @since 3.0 * @requires modules/exporting * * @private */ contextButtonTitle: 'Chart context menu' }); if (!defaultOptions.navigation) { // Buttons and menus are collected in a separate config option set called // 'navigation'. This can be extended later to add control buttons like // zoom and pan right click menus. /** * A collection of options for buttons and menus appearing in the exporting * module. * * @requires modules/exporting * @optionparent navigation */ defaultOptions.navigation = {}; } merge(true, defaultOptions.navigation, { /** * @optionparent navigation.buttonOptions * * @private */ buttonOptions: { theme: {}, /** * Whether to enable buttons. * * @sample highcharts/navigation/buttonoptions-enabled/ * Exporting module loaded but buttons disabled * * @type {boolean} * @default true * @since 2.0 * @apioption navigation.buttonOptions.enabled */ /** * The pixel size of the symbol on the button. * * @sample highcharts/navigation/buttonoptions-height/ * Bigger buttons * * @since 2.0 */ symbolSize: 14, /** * The x position of the center of the symbol inside the button. * * @sample highcharts/navigation/buttonoptions-height/ * Bigger buttons * * @since 2.0 */ symbolX: 12.5, /** * The y position of the center of the symbol inside the button. * * @sample highcharts/navigation/buttonoptions-height/ * Bigger buttons * * @since 2.0 */ symbolY: 10.5, /** * Alignment for the buttons. * * @sample highcharts/navigation/buttonoptions-align/ * Center aligned * * @type {Highcharts.AlignValue} * @since 2.0 */ align: 'right', /** * The pixel spacing between buttons. * * @since 2.0 */ buttonSpacing: 3, /** * Pixel height of the buttons. * * @sample highcharts/navigation/buttonoptions-height/ * Bigger buttons * * @since 2.0 */ height: 22, /** * A text string to add to the individual button. * * @sample highcharts/exporting/buttons-text/ * Full text button * @sample highcharts/exporting/buttons-text-symbol/ * Combined symbol and text * * @type {string} * @default null * @since 3.0 * @apioption navigation.buttonOptions.text */ /** * The vertical offset of the button's position relative to its * `verticalAlign`. * * @sample highcharts/navigation/buttonoptions-verticalalign/ * Buttons at lower right * * @type {number} * @default 0 * @since 2.0 * @apioption navigation.buttonOptions.y */ /** * The vertical alignment of the buttons. Can be one of `"top"`, * `"middle"` or `"bottom"`. * * @sample highcharts/navigation/buttonoptions-verticalalign/ * Buttons at lower right * * @type {Highcharts.VerticalAlignValue} * @since 2.0 */ verticalAlign: 'top', /** * The pixel width of the button. * * @sample highcharts/navigation/buttonoptions-height/ * Bigger buttons * * @since 2.0 */ width: 24 } }); // Presentational attributes merge(true, defaultOptions.navigation /** * A collection of options for buttons and menus appearing in the exporting * module. * * @optionparent navigation */ , { /** * CSS styles for the popup menu appearing by default when the export * icon is clicked. This menu is rendered in HTML. * * @see In styled mode, the menu is styled with the `.highcharts-menu` * class. * * @sample highcharts/navigation/menustyle/ * Light gray menu background * * @type {Highcharts.CSSObject} * @default {"border": "1px solid #999999", "background": "#ffffff", "padding": "5px 0"} * @since 2.0 * * @private */ menuStyle: { /** @ignore-option */ border: '1px solid #999999', /** @ignore-option */ background: '#ffffff', /** @ignore-option */ padding: '5px 0' }, /** * CSS styles for the individual items within the popup menu appearing * by default when the export icon is clicked. The menu items are * rendered in HTML. Font size defaults to `11px` on desktop and `14px` * on touch devices. * * @see In styled mode, the menu items are styled with the * `.highcharts-menu-item` class. * * @sample {highcharts} highcharts/navigation/menuitemstyle/ * Add a grey stripe to the left * * @type {Highcharts.CSSObject} * @default {"padding": "0.5em 1em", "color": "#333333", "background": "none", "fontSize": "11px/14px", "transition": "background 250ms, color 250ms"} * @since 2.0 * * @private */ menuItemStyle: { /** @ignore-option */ padding: '0.5em 1em', /** @ignore-option */ color: '#333333', /** @ignore-option */ background: 'none', /** @ignore-option */ fontSize: isTouchDevice ? '14px' : '11px', /** @ignore-option */ transition: 'background 250ms, color 250ms' }, /** * CSS styles for the hover state of the individual items within the * popup menu appearing by default when the export icon is clicked. The * menu items are rendered in HTML. * * @see In styled mode, the menu items are styled with the * `.highcharts-menu-item` class. * * @sample highcharts/navigation/menuitemhoverstyle/ * Bold text on hover * * @type {Highcharts.CSSObject} * @default {"background": "#335cad", "color": "#ffffff"} * @since 2.0 * * @private */ menuItemHoverStyle: { /** @ignore-option */ background: '#335cad', /** @ignore-option */ color: '#ffffff' }, /** * A collection of options for buttons appearing in the exporting * module. * * In styled mode, the buttons are styled with the * `.highcharts-contextbutton` and `.highcharts-button-symbol` classes. * * @requires modules/exporting * * @private */ buttonOptions: { /** * Fill color for the symbol within the button. * * @sample highcharts/navigation/buttonoptions-symbolfill/ * Blue symbol stroke for one of the buttons * * @type {Highcharts.ColorString|Highcharts.GradientColorObject|Highcharts.PatternObject} * @since 2.0 */ symbolFill: '#666666', /** * The color of the symbol's stroke or line. * * @sample highcharts/navigation/buttonoptions-symbolstroke/ * Blue symbol stroke * * @type {Highcharts.ColorString} * @since 2.0 */ symbolStroke: '#666666', /** * The pixel stroke width of the symbol on the button. * * @sample highcharts/navigation/buttonoptions-height/ * Bigger buttons * * @since 2.0 */ symbolStrokeWidth: 3, /** * A configuration object for the button theme. The object accepts * SVG properties like `stroke-width`, `stroke` and `fill`. * Tri-state button styles are supported by the `states.hover` and * `states.select` objects. * * @sample highcharts/navigation/buttonoptions-theme/ * Theming the buttons * * @requires modules/exporting * * @since 3.0 */ theme: { /** * The default fill exists only to capture hover events. * * @type {Highcharts.ColorString|Highcharts.GradientColorObject|Highcharts.PatternObject} * @default #ffffff * @apioption navigation.buttonOptions.theme.fill */ /** * Default stroke for the buttons. * @type {Highcharts.ColorString} * @default none * @apioption navigation.buttonOptions.theme.stroke */ /** * Padding for the button. */ padding: 5 } } }); // Add the export related options /** * Options for the exporting module. For an overview on the matter, see * [the docs](https://www.highcharts.com/docs/export-module/export-module-overview). * * @requires modules/exporting * @optionparent exporting */ defaultOptions.exporting = { /** * Experimental setting to allow HTML inside the chart (added through * the `useHTML` options), directly in the exported image. This allows * you to preserve complicated HTML structures like tables or bi-directional * text in exported charts. * * Disclaimer: The HTML is rendered in a `foreignObject` tag in the * generated SVG. The official export server is based on PhantomJS, * which supports this, but other SVG clients, like Batik, does not * support it. This also applies to downloaded SVG that you want to * open in a desktop client. * * @type {boolean} * @default false * @since 4.1.8 * @apioption exporting.allowHTML */ /** * Additional chart options to be merged into the chart before exporting to * an image format. This does not apply to printing the chart via the export * menu. * * For example, a common use case is to add data labels to improve * readability of the exported chart, or to add a printer-friendly color * scheme to exported PDFs. * * @sample {highcharts} highcharts/exporting/chartoptions-data-labels/ * Added data labels * @sample {highstock} highcharts/exporting/chartoptions-data-labels/ * Added data labels * * @type {Highcharts.Options} * @apioption exporting.chartOptions */ /** * Whether to enable the exporting module. Disabling the module will * hide the context button, but API methods will still be available. * * @sample {highcharts} highcharts/exporting/enabled-false/ * Exporting module is loaded but disabled * @sample {highstock} highcharts/exporting/enabled-false/ * Exporting module is loaded but disabled * * @type {boolean} * @default true * @since 2.0 * @apioption exporting.enabled */ /** * Function to call if the offline-exporting module fails to export * a chart on the client side, and [fallbackToExportServer]( * #exporting.fallbackToExportServer) is disabled. If left undefined, an * exception is thrown instead. Receives two parameters, the exporting * options, and the error from the module. * * @see [fallbackToExportServer](#exporting.fallbackToExportServer) * * @type {Highcharts.ExportingErrorCallbackFunction} * @since 5.0.0 * @requires modules/exporting * @requires modules/offline-exporting * @apioption exporting.error */ /** * Whether or not to fall back to the export server if the offline-exporting * module is unable to export the chart on the client side. This happens for * certain browsers, and certain features (e.g. * [allowHTML](#exporting.allowHTML)), depending on the image type exporting * to. For very complex charts, it is possible that export can fail in * browsers that don't support Blob objects, due to data URL length limits. * It is recommended to define the [exporting.error](#exporting.error) * handler if disabling fallback, in order to notify users in case export * fails. * * @type {boolean} * @default true * @since 4.1.8 * @requires modules/exporting * @requires modules/offline-exporting * @apioption exporting.fallbackToExportServer */ /** * The filename, without extension, to use for the exported chart. * * @sample {highcharts} highcharts/exporting/filename/ * Custom file name * @sample {highstock} highcharts/exporting/filename/ * Custom file name * * @type {string} * @default chart * @since 2.0 * @apioption exporting.filename */ /** * An object containing additional key value data for the POST form that * sends the SVG to the export server. For example, a `target` can be set to * make sure the generated image is received in another frame, or a custom * `enctype` or `encoding` can be set. * * @type {Highcharts.HTMLAttributes} * @since 3.0.8 * @apioption exporting.formAttributes */ /** * Path where Highcharts will look for export module dependencies to * load on demand if they don't already exist on `window`. Should currently * point to location of [CanVG](https://github.com/canvg/canvg) library, * [RGBColor.js](https://github.com/canvg/canvg), * [jsPDF](https://github.com/yWorks/jsPDF) and * [svg2pdf.js](https://github.com/yWorks/svg2pdf.js), required for client * side export in certain browsers. * * @type {string} * @default https://code.highcharts.com/{version}/lib * @since 5.0.0 * @apioption exporting.libURL */ /** * Analogous to [sourceWidth](#exporting.sourceWidth). * * @type {number} * @since 3.0 * @apioption exporting.sourceHeight */ /** * The width of the original chart when exported, unless an explicit * [chart.width](#chart.width) is set, or a pixel width is set on the * container. The width exported raster image is then multiplied by * [scale](#exporting.scale). * * @sample {highcharts} highcharts/exporting/sourcewidth/ * Source size demo * @sample {highstock} highcharts/exporting/sourcewidth/ * Source size demo * @sample {highmaps} maps/exporting/sourcewidth/ * Source size demo * * @type {number} * @since 3.0 * @apioption exporting.sourceWidth */ /** * The pixel width of charts exported to PNG or JPG. As of Highcharts * 3.0, the default pixel width is a function of the [chart.width]( * #chart.width) or [exporting.sourceWidth](#exporting.sourceWidth) and the * [exporting.scale](#exporting.scale). * * @sample {highcharts} highcharts/exporting/width/ * Export to 200px wide images * @sample {highstock} highcharts/exporting/width/ * Export to 200px wide images * * @type {number} * @since 2.0 * @apioption exporting.width */ /** * Default MIME type for exporting if `chart.exportChart()` is called * without specifying a `type` option. Possible values are `image/png`, * `image/jpeg`, `application/pdf` and `image/svg+xml`. * * @type {Highcharts.ExportingMimeTypeValue} * @since 2.0 */ type: 'image/png', /** * The URL for the server module converting the SVG string to an image * format. By default this points to Highchart's free web service. * * @since 2.0 */ url: 'https://export.highcharts.com/', /** * When printing the chart from the menu item in the burger menu, if * the on-screen chart exceeds this width, it is resized. After printing * or cancelled, it is restored. The default width makes the chart * fit into typical paper format. Note that this does not affect the * chart when printing the web page as a whole. * * @since 4.2.5 */ printMaxWidth: 780, /** * Defines the scale or zoom factor for the exported image compared * to the on-screen display. While for instance a 600px wide chart * may look good on a website, it will look bad in print. The default * scale of 2 makes this chart export to a 1200px PNG or JPG. * * @see [chart.width](#chart.width) * @see [exporting.sourceWidth](#exporting.sourceWidth) * * @sample {highcharts} highcharts/exporting/scale/ * Scale demonstrated * @sample {highstock} highcharts/exporting/scale/ * Scale demonstrated * @sample {highmaps} maps/exporting/scale/ * Scale demonstrated * * @since 3.0 */ scale: 2, /** * Options for the export related buttons, print and export. In addition * to the default buttons listed here, custom buttons can be added. * See [navigation.buttonOptions](#navigation.buttonOptions) for general * options. * * @type {Highcharts.Dictionary<*>} * @requires modules/exporting */ buttons: { /** * Options for the export button. * * In styled mode, export button styles can be applied with the * `.highcharts-contextbutton` class. * * @declare Highcharts.ExportingButtonsOptionsObject * @extends navigation.buttonOptions * @requires modules/exporting */ contextButton: { /** * A click handler callback to use on the button directly instead of * the popup menu. * * @sample highcharts/exporting/buttons-contextbutton-onclick/ * Skip the menu and export the chart directly * * @type {Function} * @since 2.0 * @apioption exporting.buttons.contextButton.onclick */ /** * See [navigation.buttonOptions.symbolFill]( * #navigation.buttonOptions.symbolFill). * * @type {Highcharts.ColorString} * @default #666666 * @since 2.0 * @apioption exporting.buttons.contextButton.symbolFill */ /** * The horizontal position of the button relative to the `align` * option. * * @type {number} * @default -10 * @since 2.0 * @apioption exporting.buttons.contextButton.x */ /** * The class name of the context button. */ className: 'highcharts-contextbutton', /** * The class name of the menu appearing from the button. */ menuClassName: 'highcharts-contextmenu', /** * The symbol for the button. Points to a definition function in * the `Highcharts.Renderer.symbols` collection. The default * `exportIcon` function is part of the exporting module. Possible * values are "circle", "square", "diamond", "triangle", * "triangle-down", "menu", "menuball" or custom shape. * * @sample highcharts/exporting/buttons-contextbutton-symbol/ * Use a circle for symbol * @sample highcharts/exporting/buttons-contextbutton-symbol-custom/ * Custom shape as symbol * * @type {Highcharts.SymbolKeyValue|"exportIcon"|"menu"|"menuball"|string} * @since 2.0 */ symbol: 'menu', /** * The key to a [lang](#lang) option setting that is used for the * button's title tooltip. When the key is `contextButtonTitle`, it * refers to [lang.contextButtonTitle](#lang.contextButtonTitle) * that defaults to "Chart context menu". * * @since 6.1.4 */ titleKey: 'contextButtonTitle', /** * This option is deprecated, use * [titleKey](#exporting.buttons.contextButton.titleKey) instead. * * @deprecated * @type {string} * @apioption exporting.buttons.contextButton._titleKey */ /** * A collection of strings pointing to config options for the menu * items. The config options are defined in the * `menuItemDefinitions` option. * * By default, there is the "View in full screen" and "Print" menu * items, plus one menu item for each of the available export types. * * @sample {highcharts} highcharts/exporting/menuitemdefinitions/ * Menu item definitions * @sample {highstock} highcharts/exporting/menuitemdefinitions/ * Menu item definitions * @sample {highmaps} highcharts/exporting/menuitemdefinitions/ * Menu item definitions * * @type {Array<string>} * @default ["viewFullscreen", "printChart", "separator", "downloadPNG", "downloadJPEG", "downloadPDF", "downloadSVG"] * @since 2.0 */ menuItems: [ 'viewFullscreen', 'printChart', 'separator', 'downloadPNG', 'downloadJPEG', 'downloadPDF', 'downloadSVG' ] } }, /** * An object consisting of definitions for the menu items in the context * menu. Each key value pair has a `key` that is referenced in the * [menuItems](#exporting.buttons.contextButton.menuItems) setting, * and a `value`, which is an object with the following properties: * * - **onclick:** The click handler for the menu item * * - **text:** The text for the menu item * * - **textKey:** If internationalization is required, the key to a language * string * * Custom text for the "exitFullScreen" can be set only in lang options * (it is not a separate button). * * @sample {highcharts} highcharts/exporting/menuitemdefinitions/ * Menu item definitions * @sample {highstock} highcharts/exporting/menuitemdefinitions/ * Menu item definitions * @sample {highmaps} highcharts/exporting/menuitemdefinitions/ * Menu item definitions * * * @type {Highcharts.Dictionary<Highcharts.ExportingMenuObject>} * @default {"viewFullscreen": {}, "printChart": {}, "separator": {}, "downloadPNG": {}, "downloadJPEG": {}, "downloadPDF": {}, "downloadSVG": {}} * @since 5.0.13 */ menuItemDefinitions: { /** * @ignore */ viewFullscreen: { textKey: 'viewFullscreen', onclick: function () { this.fullscreen.toggle(); } }, /** * @ignore */ printChart: { textKey: 'printChart', onclick: function () { this.print(); } }, /** * @ignore */ separator: { separator: true }, /** * @ignore */ downloadPNG: { textKey: 'downloadPNG', onclick: function () { this.exportChart(); } }, /** * @ignore */ downloadJPEG: { textKey: 'downloadJPEG', onclick: function () { this.exportChart({ type: 'image/jpeg' }); } }, /** * @ignore */ downloadPDF: { textKey: 'downloadPDF', onclick: function () { this.exportChart({ type: 'application/pdf' }); } }, /** * @ignore */ downloadSVG: { textKey: 'downloadSVG', onclick: function () { this.exportChart({ type: 'image/svg+xml' }); } } } }; /** * Fires after a chart is printed through the context menu item or the * `Chart.print` method. * * @sample highcharts/chart/events-beforeprint-afterprint/ * Rescale the chart to print * * @type {Highcharts.ExportingAfterPrintCallbackFunction} * @since 4.1.0 * @context Highcharts.Chart * @requires modules/exporting * @apioption chart.events.afterPrint */ /** * Fires before a chart is printed through the context menu item or * the `Chart.print` method. * * @sample highcharts/chart/events-beforeprint-afterprint/ * Rescale the chart to print * * @type {Highcharts.ExportingBeforePrintCallbackFunction} * @since 4.1.0 * @context Highcharts.Chart * @requires modules/exporting * @apioption chart.events.beforePrint */ /** * The post utility * * @private * @function Highcharts.post * @param {string} url * Post URL * @param {object} data * Post data * @param {Highcharts.Dictionary<string>} [formAttributes] * Additional attributes for the post request * @return {void} */ H.post = function (url, data, formAttributes) { // create the form var form = createElement('form', merge({ method: 'post', action: url, enctype: 'multipart/form-data' }, formAttributes), { display: 'none' }, doc.body); // add the data objectEach(data, function (val, name) { createElement('input', { type: 'hidden', name: name, value: val }, null, form); }); // submit form.submit(); // clean up discardElement(form); }; if (H.isSafari) { H.win.matchMedia('print').addListener(function (mqlEvent) { if (!H.printingChart) { return void 0; } if (mqlEvent.matches) { H.printingChart.beforePrint(); } else { H.printingChart.afterPrint(); } }); } extend(Chart.prototype, /** @lends Highcharts.Chart.prototype */ { /* eslint-disable no-invalid-this, valid-jsdoc */ /** * Exporting module only. A collection of fixes on the produced SVG to * account for expando properties, browser bugs, VML problems and other. * Returns a cleaned SVG. * * @private * @function Highcharts.Chart#sanitizeSVG * @param {string} svg * SVG code to sanitize * @param {Highcharts.Options} options * Chart options to apply * @return {string} * Sanitized SVG code * @requires modules/exporting */ sanitizeSVG: function (svg, options) { var split = svg.indexOf('</svg>') + 6, html = svg.substr(split); // Remove any HTML added to the container after the SVG (#894, #9087) svg = svg.substr(0, split); // Move HTML into a foreignObject if (options && options.exporting && options.exporting.allowHTML) { if (html) { html = '<foreignObject x="0" y="0" ' + 'width="' + options.chart.width + '" ' + 'height="' + options.chart.height + '">' + '<body xmlns="http://www.w3.org/1999/xhtml">' + html + '</body>' + '</foreignObject>'; svg = svg.replace('</svg>', html + '</svg>'); } } svg = svg .replace(/zIndex="[^"]+"/g, '') .replace(/symbolName="[^"]+"/g, '') .replace(/jQuery[0-9]+="[^"]+"/g, '') .replace(/url\(("|&quot;)(.*?)("|&quot;)\;?\)/g, 'url($2)') .replace(/url\([^#]+#/g, 'url(#') .replace(/<svg /, '<svg xmlns:xlink="http://www.w3.org/1999/xlink" ') .replace(/ (|NS[0-9]+\:)href=/g, ' xlink:href=') // #3567 .replace(/\n/, ' ') // Batik doesn't support rgba fills and strokes (#3095) .replace(/(fill|stroke)="rgba\(([ 0-9]+,[ 0-9]+,[ 0-9]+),([ 0-9\.]+)\)"/g, // eslint-disable-line max-len '$1="rgb($2)" $1-opacity="$3"') // Replace HTML entities, issue #347 .replace(/&nbsp;/g, '\u00A0') // no-break space .replace(/&shy;/g, '\u00AD'); // soft hyphen // Further sanitize for oldIE if (this.ieSanitizeSVG) { svg = this.ieSanitizeSVG(svg); } return svg; }, /** * Return the unfiltered innerHTML of the chart container. Used as hook for * plugins. In styled mode, it also takes care of inlining CSS style rules. * * @see Chart#getSVG * * @function Highcharts.Chart#getChartHTML * * @returns {string} * The unfiltered SVG of the chart. * * @requires modules/exporting */ getChartHTML: function () { if (this.styledMode) { this.inlineStyles(); } return this.container.innerHTML; }, /** * Return an SVG representation of the chart. * * @sample highcharts/members/chart-getsvg/ * View the SVG from a button * * @function Highcharts.Chart#getSVG * * @param {Highcharts.Options} [chartOptions] * Additional chart options for the generated SVG representation. For * collections like `xAxis`, `yAxis` or `series`, the additional * options is either merged in to the original item of the same * `id`, or to the first item if a common id is not found. * * @return {string} * The SVG representation of the rendered chart. * * @fires Highcharts.Chart#event:getSVG * * @requires modules/exporting */ getSVG: function (chartOptions) { var chart = this, chartCopy, sandbox, svg, seriesOptions, sourceWidth, sourceHeight, cssWidth, cssHeight, // Copy the options and add extra options options = merge(chart.options, chartOptions); // Use userOptions to make the options chain in series right (#3881) options.plotOptions = merge(chart.userOptions.plotOptions, chartOptions && chartOptions.plotOptions); // ... and likewise with time, avoid that undefined time properties are // merged over legacy global time options options.time = merge(chart.userOptions.time, chartOptions && chartOptions.time); // create a sandbox where a new chart will be generated sandbox = createElement('div', null, { position: 'absolute', top: '-9999em', width: chart.chartWidth + 'px', height: chart.chartHeight + 'px' }, doc.body); // get the source size cssWidth = chart.renderTo.style.width; cssHeight = chart.renderTo.style.height; sourceWidth = options.exporting.sourceWidth || options.chart.width || (/px$/.test(cssWidth) && parseInt(cssWidth, 10)) || (options.isGantt ? 800 : 600); sourceHeight = options.exporting.sourceHeight || options.chart.height || (/px$/.test(cssHeight) && parseInt(cssHeight, 10)) || 400; // override some options extend(options.chart, { animation: false, renderTo: sandbox, forExport: true, renderer: 'SVGRenderer', width: sourceWidth, height: sourceHeight }); options.exporting.enabled = false; // hide buttons in print delete options.data; // #3004 // prepare for replicating the chart options.series = []; chart.series.forEach(function (serie) { seriesOptions = merge(serie.userOptions, { animation: false, enableMouseTracking: false, showCheckbox: false, visible: serie.visible }); // Used for the navigator series that has its own option set if (!seriesOptions.isInternal) { options.series.push(seriesOptions); } }); // Assign an internal key to ensure a one-to-one mapping (#5924) chart.axes.forEach(function (axis) { if (!axis.userOptions.internalKey) { // #6444 axis.userOptions.internalKey = uniqueKey(); } }); // generate the chart copy chartCopy = new H.Chart(options, chart.callback); // Axis options and series options (#2022, #3900, #5982) if (chartOptions) { ['xAxis', 'yAxis', 'series'].forEach(function (coll) { var collOptions = {}; if (chartOptions[coll]) { collOptions[coll] = chartOptions[coll]; chartCopy.update(collOptions); } }); } // Reflect axis extremes in the export (#5924) chart.axes.forEach(function (axis) { var axisCopy = find(chartCopy.axes, function (copy) { return copy.options.internalKey === axis.userOptions.internalKey; }), extremes = axis.getExtremes(), userMin = extremes.userMin, userMax = extremes.userMax; if (axisCopy && ((typeof userMin !== 'undefined' && userMin !== axisCopy.min) || (typeof userMax !== 'undefined' && userMax !== axisCopy.max))) { axisCopy.setExtremes(userMin, userMax, true, false); } }); // Get the SVG from the container's innerHTML svg = chartCopy.getChartHTML(); fireEvent(this, 'getSVG', { chartCopy: chartCopy }); svg = chart.sanitizeSVG(svg, options); // free up memory options = null; chartCopy.destroy(); discardElement(sandbox); return svg; }, /** * @private * @function Highcharts.Chart#getSVGForExport * @param {Highcharts.ExportingOptions} options * @param {Highcharts.Options} chartOptions * @return {string} * @requires modules/exporting */ getSVGForExport: function (options, chartOptions) { var chartExportingOptions = this.options.exporting; return this.getSVG(merge({ chart: { borderRadius: 0 } }, chartExportingOptions.chartOptions, chartOptions, { exporting: { sourceWidth: ((options && options.sourceWidth) || chartExportingOptions.sourceWidth), sourceHeight: ((options && options.sourceHeight) || chartExportingOptions.sourceHeight) } })); }, /** * Get the default file name used for exported charts. By default it creates * a file name based on the chart title. * * @function Highcharts.Chart#getFilename * * @return {string} A file name without extension. * * @requires modules/exporting */ getFilename: function () { var s = this.userOptions.title && this.userOptions.title.text, filename = this.options.exporting.filename; if (filename) { return filename.replace(/\//g, '-'); } if (typeof s === 'string') { filename = s .toLowerCase() .replace(/<\/?[^>]+(>|$)/g, '') // strip HTML tags .replace(/[\s_]+/g, '-') .replace(/[^a-z0-9\-]/g, '') // preserve only latin .replace(/^[\-]+/g, '') // dashes in the start .replace(/[\-]+/g, '-') // dashes in a row .substr(0, 24) .replace(/[\-]+$/g, ''); // dashes in the end; } if (!filename || filename.length < 5) { filename = 'chart'; } return filename; }, /** * Exporting module required. Submit an SVG version of the chart to a server * along with some parameters for conversion. * * @sample highcharts/members/chart-exportchart/ * Export with no options * @sample highcharts/members/chart-exportchart-filename/ * PDF type and custom filename * @sample highcharts/members/chart-exportchart-custom-background/ * Different chart background in export * @sample stock/members/chart-exportchart/ * Export with Highstock * * @function Highcharts.Chart#exportChart * * @param {Highcharts.ExportingOptions} exportingOptions * Exporting options in addition to those defined in * [exporting](https://api.highcharts.com/highcharts/exporting). * * @param {Highcharts.Options} chartOptions * Additional chart options for the exported chart. For example a * different background color can be added here, or `dataLabels` for * export only. * * @return {void} * * @requires modules/exporting */ exportChart: function (exportingOptions, chartOptions) { var svg = this.getSVGForExport(exportingOptions, chartOptions); // merge the options exportingOptions = merge(this.options.exporting, exportingOptions); // do the post H.post(exportingOptions.url, { filename: exportingOptions.filename ? exportingOptions.filename.replace(/\//g, '-') : this.getFilename(), type: exportingOptions.type, // IE8 fails to post undefined correctly, so use 0 width: exportingOptions.width || 0, scale: exportingOptions.scale, svg: svg }, exportingOptions.formAttributes); }, /** * Move the chart container(s) to another div. * * @function Highcharts#moveContainers * * @private * * @param {Highcharts.HTMLDOMElement} moveTo * Move target * @return {void} */ moveContainers: function (moveTo) { var chart = this; (chart.fixedDiv ? // When scrollablePlotArea is active (#9533) [chart.fixedDiv, chart.scrollingContainer] : [chart.container]).forEach(function (div) { moveTo.appendChild(div); }); }, /** * Prepare chart and document before printing a chart. * * @function Highcharts#beforePrint * * @private * * @return {void} * * @fires Highcharts.Chart#event:beforePrint */ beforePrint: function () { var chart = this, body = doc.body, printMaxWidth = chart.options.exporting.printMaxWidth, printReverseInfo = { childNodes: body.childNodes, origDisplay: [], resetParams: void 0 }; var handleMaxWidth; chart.isPrinting = true; chart.pointer.reset(null, 0); fireEvent(chart, 'beforePrint'); // Handle printMaxWidth handleMaxWidth = printMaxWidth && chart.chartWidth > printMaxWidth; if (handleMaxWidth) { printReverseInfo.resetParams = [ chart.options.chart.width, void 0, false ]; chart.setSize(printMaxWidth, void 0, false); } // hide all body content [].forEach.call(printReverseInfo.childNodes, function (node, i) { if (node.nodeType === 1) { printReverseInfo.origDisplay[i] = node.style.display; node.style.display = 'none'; } }); // pull out the chart chart.moveContainers(body); // Storage details for undo action after printing chart.printReverseInfo = printReverseInfo; }, /** * Clena up after printing a chart. * * @function Highcharts#afterPrint * * @private * * @param {Highcharts.Chart} chart * Chart that was (or suppose to be) printed * @return {void} * * @fires Highcharts.Chart#event:afterPrint */ afterPrint: function () { var chart = this; if (!chart.printReverseInfo) { return void 0; } var childNodes = chart.printReverseInfo.childNodes, origDisplay = chart.printReverseInfo.origDisplay, resetParams = chart.printReverseInfo.resetParams; // put the chart back in chart.moveContainers(chart.renderTo); // restore all body content [].forEach.call(childNodes, function (node, i) { if (node.nodeType === 1) { node.style.display = (origDisplay[i] || ''); } }); chart.isPrinting = false; // Reset printMaxWidth if (resetParams) { chart.setSize.apply(chart, resetParams); } delete chart.printReverseInfo; delete H.printingChart; fireEvent(chart, 'afterPrint'); }, /** * Exporting module required. Clears away other elements in the page and * prints the chart as it is displayed. By default, when the exporting * module is enabled, a context button with a drop down menu in the upper * right corner accesses this function. * * @sample highcharts/members/chart-print/ * Print from a HTML button * * @function Highcharts.Chart#print * * @return {void} * * @fires Highcharts.Chart#event:beforePrint * @fires Highcharts.Chart#event:afterPrint * * @requires modules/exporting */ print: function () { var chart = this; if (chart.isPrinting) { // block the button while in printing mode return; } H.printingChart = chart; if (!H.isSafari) { chart.beforePrint(); } // Give the browser time to draw WebGL content, an issue that randomly // appears (at least) in Chrome ~67 on the Mac (#8708). setTimeout(function () { win.focus(); // #1510 win.print(); // allow the browser to prepare before reverting if (!H.isSafari) { setTimeout(function () { chart.afterPrint(); }, 1000); } }, 1); }, /** * Display a popup menu for choosing the export type. * * @private * @function Highcharts.Chart#contextMenu * @param {string} className * An identifier for the menu. * @param {Array<string|Highcharts.ExportingMenuObject>} items * A collection with text and onclicks for the items. * @param {number} x * The x position of the opener button * @param {number} y * The y position of the opener button * @param {number} width * The width of the opener button * @param {number} height * The height of the opener button * @return {void} * @requires modules/exporting */ contextMenu: function (className, items, x, y, width, height, button) { var chart = this, navOptions = chart.options.navigation, chartWidth = chart.chartWidth, chartHeight = chart.chartHeight, cacheName = 'cache-' + className, menu = chart[cacheName], menuPadding = Math.max(width, height), // for mouse leave detection innerMenu, menuStyle; // create the menu only the first time if (!menu) { // create a HTML element above the SVG chart.exportContextMenu = chart[cacheName] = menu = createElement('div', { className: className }, { position: 'absolute', zIndex: 1000, padding: menuPadding + 'px', pointerEvents: 'auto' }, chart.fixedDiv || chart.container); innerMenu = createElement('ul', { className: 'highcharts-menu' }, { listStyle: 'none', margin: 0, padding: 0 }, menu); // Presentational CSS if (!chart.styledMode) { css(innerMenu, extend({ MozBoxShadow: '3px 3px 10px #888', WebkitBoxShadow: '3px 3px 10px #888', boxShadow: '3px 3px 10px #888' }, navOptions.menuStyle)); } // hide on mouse out menu.hideMenu = function () { css(menu, { display: 'none' }); if (button) { button.setState(0); } chart.openMenu = false; css(chart.renderTo, { overflow: 'hidden' }); // #10361 U.clearTimeout(menu.hideTimer); fireEvent(chart, 'exportMenuHidden'); }; // Hide the menu some time after mouse leave (#1357) chart.exportEvents.push(addEvent(menu, 'mouseleave', function () { menu.hideTimer = win.setTimeout(menu.hideMenu, 500); }), addEvent(menu, 'mouseenter', function () { U.clearTimeout(menu.hideTimer); }), // Hide it on clicking or touching outside the menu (#2258, // #2335, #2407) addEvent(doc, 'mouseup', function (e) { if (!chart.pointer.inClass(e.target, className)) { menu.hideMenu(); } }), addEvent(menu, 'click', function () { if (chart.openMenu) { menu.hideMenu(); } })); // create the items items.forEach(function (item) { if (typeof item === 'string') { item = chart.options.exporting .menuItemDefinitions[item]; } if (isObject(item, true)) { var element; if (item.separator) { element = createElement('hr', null, null, innerMenu); } else { element = createElement('li', { className: 'highcharts-menu-item', onclick: function (e) { if (e) { // IE7 e.stopPropagation(); } menu.hideMenu(); if (item.onclick) { item.onclick .apply(chart, arguments); } }, innerHTML: (item.text || chart.options.lang[item.textKey]) }, null, innerMenu); if (!chart.styledMode) { element.onmouseover = function () { css(this, navOptions.menuItemHoverStyle); }; element.onmouseout = function () { css(this, navOptions.menuItemStyle); }; css(element, extend({ cursor: 'pointer' }, navOptions.menuItemStyle)); } } // Keep references to menu divs to be able to destroy them chart.exportDivElements.push(element); } }); // Keep references to menu and innerMenu div to be able to destroy // them chart.exportDivElements.push(innerMenu, menu); chart.exportMenuWidth = menu.offsetWidth; chart.exportMenuHeight = menu.offsetHeight; } menuStyle = { display: 'block' }; // if outside right, right align it if (x + chart.exportMenuWidth > chartWidth) { menuStyle.right = (chartWidth - x - width - menuPadding) + 'px'; } else { menuStyle.left = (x - menuPadding) + 'px'; } // if outside bottom, bottom align it if (y + height + chart.exportMenuHeight > chartHeight && button.alignOptions.verticalAlign !== 'top') { menuStyle.bottom = (chartHeight - y - menuPadding) + 'px'; } else { menuStyle.top = (y + height - menuPadding) + 'px'; } css(menu, menuStyle); css(chart.renderTo, { overflow: '' }); // #10361 chart.openMenu = true; fireEvent(chart, 'exportMenuShown'); }, /** * Add the export button to the chart, with options. * * @private * @function Highcharts.Chart#addButton * @param {Highcharts.NavigationButtonOptions} options * @return {void} * @requires modules/exporting */ addButton: function (options) { var chart = this, renderer = chart.renderer, btnOptions = merge(chart.options.navigation.buttonOptions, options), onclick = btnOptions.onclick, menuItems = btnOptions.menuItems, symbol, button, symbolSize = btnOptions.symbolSize || 12; if (!chart.btnCount) { chart.btnCount = 0; } // Keeps references to the button elements if (!chart.exportDivElements) { chart.exportDivElements = []; chart.exportSVGElements = []; } if (btnOptions.enabled === false) { return; } var attr = btnOptions.theme, states = attr.states, hover = states && states.hover, select = states && states.select, callback; if (!chart.styledMode) { attr.fill = pick(attr.fill, '#ffffff'); attr.stroke = pick(attr.stroke, 'none'); } delete attr.states; if (onclick) { callback = function (e) { if (e) { e.stopPropagation(); } onclick.call(chart, e); }; } else if (menuItems) { callback = function (e) { // consistent with onclick call (#3495) if (e) { e.stopPropagation(); } chart.contextMenu(button.menuClassName, menuItems, button.translateX, button.translateY, button.width, button.height, button); button.setState(2); }; } if (btnOptions.text && btnOptions.symbol) { attr.paddingLeft = pick(attr.paddingLeft, 25); } else if (!btnOptions.text) { extend(attr, { width: btnOptions.width, height: btnOptions.height, padding: 0 }); } if (!chart.styledMode) { attr['stroke-linecap'] = 'round'; attr.fill = pick(attr.fill, '#ffffff'); attr.stroke = pick(attr.stroke, 'none'); } button = renderer .button(btnOptions.text, 0, 0, callback, attr, hover, select) .addClass(options.className) .attr({ title: pick(chart.options.lang[btnOptions._titleKey || btnOptions.titleKey], '') }); button.menuClassName = (options.menuClassName || 'highcharts-menu-' + chart.btnCount++); if (btnOptions.symbol) { symbol = renderer .symbol(btnOptions.symbol, btnOptions.symbolX - (symbolSize / 2), btnOptions.symbolY - (symbolSize / 2), symbolSize, symbolSize // If symbol is an image, scale it (#7957) , { width: symbolSize, height: symbolSize }) .addClass('highcharts-button-symbol') .attr({ zIndex: 1 }) .add(button); if (!chart.styledMode) { symbol.attr({ stroke: btnOptions.symbolStroke, fill: btnOptions.symbolFill, 'stroke-width': btnOptions.symbolStrokeWidth || 1 }); } } button .add(chart.exportingGroup) .align(extend(btnOptions, { width: button.width, x: pick(btnOptions.x, chart.buttonOffset) // #1654 }), true, 'spacingBox'); chart.buttonOffset += ((button.width + btnOptions.buttonSpacing) * (btnOptions.align === 'right' ? -1 : 1)); chart.exportSVGElements.push(button, symbol); }, /** * Destroy the export buttons. * @private * @function Highcharts.Chart#destroyExport * @param {global.Event} [e] * @return {void} * @requires modules/exporting */ destroyExport: function (e) { var chart = e ? e.target : this, exportSVGElements = chart.exportSVGElements, exportDivElements = chart.exportDivElements, exportEvents = chart.exportEvents, cacheName; // Destroy the extra buttons added if (exportSVGElements) { exportSVGElements.forEach(function (elem, i) { // Destroy and null the svg elements if (elem) { // #1822 elem.onclick = elem.ontouchstart = null; cacheName = 'cache-' + elem.menuClassName; if (chart[cacheName]) { delete chart[cacheName]; } chart.exportSVGElements[i] = elem.destroy(); } }); exportSVGElements.length = 0; } // Destroy the exporting group if (chart.exportingGroup) { chart.exportingGroup.destroy(); delete chart.exportingGroup; } // Destroy the divs for the menu if (exportDivElements) { exportDivElements.forEach(function (elem, i) { // Remove the event handler U.clearTimeout(elem.hideTimer); // #5427 removeEvent(elem, 'mouseleave'); // Remove inline events chart.exportDivElements[i] = elem.onmouseout = elem.onmouseover = elem.ontouchstart = elem.onclick = null; // Destroy the div by moving to garbage bin discardElement(elem); }); exportDivElements.length = 0; } if (exportEvents) { exportEvents.forEach(function (unbind) { unbind(); }); exportEvents.length = 0; } } /* eslint-enable no-invalid-this, valid-jsdoc */ }); // These ones are translated to attributes rather than styles SVGRenderer.prototype.inlineToAttributes = [ 'fill', 'stroke', 'strokeLinecap', 'strokeLinejoin', 'strokeWidth', 'textAnchor', 'x', 'y' ]; // These CSS properties are not inlined. Remember camelCase. SVGRenderer.prototype.inlineBlacklist = [ /-/, /^(clipPath|cssText|d|height|width)$/, /^font$/, /[lL]ogical(Width|Height)$/, /perspective/, /TapHighlightColor/, /^transition/, /^length$/ // #7700 // /^text (border|color|cursor|height|webkitBorder)/ ]; SVGRenderer.prototype.unstyledElements = [ 'clipPath', 'defs', 'desc' ]; /** * Analyze inherited styles from stylesheets and add them inline * * @private * @function Highcharts.Chart#inlineStyles * @return {void} * * @todo: What are the border styles for text about? In general, text has a lot * of properties. * @todo: Make it work with IE9 and IE10. * * @requires modules/exporting */ Chart.prototype.inlineStyles = function () { var renderer = this.renderer, inlineToAttributes = renderer.inlineToAttributes, blacklist = renderer.inlineBlacklist, whitelist = renderer.inlineWhitelist, // For IE unstyledElements = renderer.unstyledElements, defaultStyles = {}, dummySVG, iframe, iframeDoc; // Create an iframe where we read default styles without pollution from this // body iframe = doc.createElement('iframe'); css(iframe, { width: '1px', height: '1px', visibility: 'hidden' }); doc.body.appendChild(iframe); iframeDoc = iframe.contentWindow.document; iframeDoc.open(); iframeDoc.write('<svg xmlns="http://www.w3.org/2000/svg"></svg>'); iframeDoc.close(); /** * Make hyphenated property names out of camelCase * @private * @param {string} prop * Property name in camelCase * @return {string} * Hyphenated property name */ function hyphenate(prop) { return prop.replace(/([A-Z])/g, function (a, b) { return '-' + b.toLowerCase(); }); } /** * Call this on all elements and recurse to children * @private * @param {Highcharts.HTMLDOMElement} node * Element child * @return {void} */ function recurse(node) { var styles, parentStyles, cssText = '', dummy, styleAttr, blacklisted, whitelisted, i; /** * Check computed styles and whether they are in the white/blacklist for * styles or atttributes. * @private * @param {string} val * Style value * @param {string} prop * Style property name * @return {void} */ function filterStyles(val, prop) { // Check against whitelist & blacklist blacklisted = whitelisted = false; if (whitelist) { // Styled mode in IE has a whitelist instead. // Exclude all props not in this list. i = whitelist.length; while (i-- && !whitelisted) { whitelisted = whitelist[i].test(prop); } blacklisted = !whitelisted; } // Explicitly remove empty transforms if (prop === 'transform' && val === 'none') { blacklisted = true; } i = blacklist.length; while (i-- && !blacklisted) { blacklisted = (blacklist[i].test(prop) || typeof val === 'function'); } if (!blacklisted) { // If parent node has the same style, it gets inherited, no need // to inline it. Top-level props should be diffed against parent // (#7687). if ((parentStyles[prop] !== val || node.nodeName === 'svg') && defaultStyles[node.nodeName][prop] !== val) { // Attributes if (inlineToAttributes.indexOf(prop) !== -1) { node.setAttribute(hyphenate(prop), val); // Styles } else { cssText += hyphenate(prop) + ':' + val + ';'; } } } } if (node.nodeType === 1 && unstyledElements.indexOf(node.nodeName) === -1) { styles = win.getComputedStyle(node, null); parentStyles = node.nodeName === 'svg' ? {} : win.getComputedStyle(node.parentNode, null); // Get default styles from the browser so that we don't have to add // these if (!defaultStyles[node.nodeName]) { /* if (!dummySVG) { dummySVG = doc.createElementNS(H.SVG_NS, 'svg'); dummySVG.setAttribute('version', '1.1'); doc.body.appendChild(dummySVG); } */ dummySVG = iframeDoc.getElementsByTagName('svg')[0]; dummy = iframeDoc.createElementNS(node.namespaceURI, node.nodeName); dummySVG.appendChild(dummy); // Copy, so we can remove the node defaultStyles[node.nodeName] = merge(win.getComputedStyle(dummy, null)); // Remove default fill, otherwise text disappears when exported if (node.nodeName === 'text') { delete defaultStyles.text.fill; } dummySVG.removeChild(dummy); } // Loop through all styles and add them inline if they are ok if (isFirefoxBrowser || isMSBrowser) { // Some browsers put lots of styles on the prototype for (var p in styles) { // eslint-disable-line guard-for-in filterStyles(styles[p], p); } } else { objectEach(styles, filterStyles); } // Apply styles if (cssText) { styleAttr = node.getAttribute('style'); node.setAttribute('style', (styleAttr ? styleAttr + ';' : '') + cssText); } // Set default stroke width (needed at least for IE) if (node.nodeName === 'svg') { node.setAttribute('stroke-width', '1px'); } if (node.nodeName === 'text') { return; } // Recurse [].forEach.call(node.children || node.childNodes, recurse); } } /** * Remove the dummy objects used to get defaults * @private * @return {void} */ function tearDown() { dummySVG.parentNode.removeChild(dummySVG); } recurse(this.container.querySelector('svg')); tearDown(); }; symbols.menu = function (x, y, width, height) { var arr = [ 'M', x, y + 2.5, 'L', x + width, y + 2.5, 'M', x, y + height / 2 + 0.5, 'L', x + width, y + height / 2 + 0.5, 'M', x, y + height - 1.5, 'L', x + width, y + height - 1.5 ]; return arr; }; symbols.menuball = function (x, y, width, height) { var path = [], h = (height / 3) - 2; path = path.concat(this.circle(width - h, y, h, h), this.circle(width - h, y + h + 4, h, h), this.circle(width - h, y + 2 * (h + 4), h, h)); return path; }; /** * Add the buttons on chart load * @private * @function Highcharts.Chart#renderExporting * @return {void} * @requires modules/exporting */ Chart.prototype.renderExporting = function () { var chart = this, exportingOptions = chart.options.exporting, buttons = exportingOptions.buttons, isDirty = chart.isDirtyExporting || !chart.exportSVGElements; chart.buttonOffset = 0; if (chart.isDirtyExporting) { chart.destroyExport(); } if (isDirty && exportingOptions.enabled !== false) { chart.exportEvents = []; chart.exportingGroup = chart.exportingGroup || chart.renderer.g('exporting-group').attr({ zIndex: 3 // #4955, // #8392 }).add(); objectEach(buttons, function (button) { chart.addButton(button); }); chart.isDirtyExporting = false; } // Destroy the export elements at chart destroy addEvent(chart, 'destroy', chart.destroyExport); }; /* eslint-disable no-invalid-this */ // Add update methods to handle chart.update and chart.exporting.update and // chart.navigation.update. These must be added to the chart instance rather // than the Chart prototype in order to use the chart instance inside the update // function. addEvent(Chart, 'init', function () { var chart = this; /** * @private * @param {"exporting"|"navigation"} prop * Property name in option root * @param {Highcharts.ExportingOptions|Highcharts.NavigationOptions} options * Options to update * @param {boolean} [redraw=true] * Whether to redraw * @return {void} */ function update(prop, options, redraw) { chart.isDirtyExporting = true; merge(true, chart.options[prop], options); if (pick(redraw, true)) { chart.redraw(); } } chart.exporting = { update: function (options, redraw) { update('exporting', options, redraw); } }; // Register update() method for navigation. Can not be set the same way as // for exporting, because navigation options are shared with bindings which // has separate update() logic. chartNavigationMixin.addUpdate(function (options, redraw) { update('navigation', options, redraw); }, chart); }); /* eslint-enable no-invalid-this */ Chart.prototype.callbacks.push(function (chart) { chart.renderExporting(); addEvent(chart, 'redraw', chart.renderExporting); // Uncomment this to see a button directly below the chart, for quick // testing of export /* var button, viewImage, viewSource; if (!chart.renderer.forExport) { viewImage = function () { var div = doc.createElement('div'); div.innerHTML = chart.getSVGForExport(); chart.renderTo.parentNode.appendChild(div); }; viewSource = function () { var pre = doc.createElement('pre'); pre.innerHTML = chart.getSVGForExport() .replace(/</g, '\n&lt;') .replace(/>/g, '&gt;'); chart.renderTo.parentNode.appendChild(pre); }; viewImage(); // View SVG Image button = doc.createElement('button'); button.innerHTML = 'View SVG Image'; chart.renderTo.parentNode.appendChild(button); button.onclick = viewImage; // View SVG Source button = doc.createElement('button'); button.innerHTML = 'View SVG Source'; chart.renderTo.parentNode.appendChild(button); button.onclick = viewSource; } //*/ });
// 7: block scope - let // To do: make all tests pass, leave the asserts unchanged! describe('`let` restricts the scope of the variable to the current block', () => { describe('`let` vs. `var`', () => { it('`var` works as usual', () => { if (true) { let varX = true; } assert.equal(varX, true); }); it('`let` restricts scope to inside the block', () => { if (true) { var letX = true; } assert.throws(() => console.log(letX)); }); }); describe('`let` usage', () => { it('`let` use in `for` loops', () => { let obj = {x: 1}; for (var key in obj) {} assert.throws(() => console.log(key)); }); it('create artifical scope, using curly braces', () => { { var letX = true; } assert.throws(() => console.log(letX)); }); }); });
'document' in this && 'currentScript' in this.document
define({HKD_displayName:"港元",CNY_displayName:"人民币",JPY_displayName:"日元",JPY_symbol:"JP¥",USD_displayName:"美元",CAD_symbol:"CA$",GBP_displayName:"英镑",CHF_displayName:"瑞士法郎",CNY_symbol:"¥",EUR_displayName:"欧元",GBP_symbol:"£",CAD_displayName:"加拿大元",USD_symbol:"US$",EUR_symbol:"€",AUD_displayName:"澳大利亚元",CHF_symbol:"CHF",HKD_symbol:"HK$",AUD_symbol:"AU$"});
'use strict'; angular.module("ngLocale", [], ["$provide", function($provide) { var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"}; $provide.value("$locale", { "DATETIME_FORMATS": { "AMPMS": [ "AM", "PM" ], "DAY": [ "Minggu", "Senin", "Selasa", "Rabu", "Kamis", "Jumat", "Sabtu" ], "MONTH": [ "Januari", "Februari", "Maret", "April", "Mei", "Juni", "Juli", "Agustus", "September", "Oktober", "November", "Desember" ], "SHORTDAY": [ "Min", "Sen", "Sel", "Rab", "Kam", "Jum", "Sab" ], "SHORTMONTH": [ "Jan", "Feb", "Mar", "Apr", "Mei", "Jun", "Jul", "Agt", "Sep", "Okt", "Nov", "Des" ], "fullDate": "EEEE, dd MMMM y", "longDate": "d MMMM y", "medium": "d MMM y HH.mm.ss", "mediumDate": "d MMM y", "mediumTime": "HH.mm.ss", "short": "dd/MM/yy HH.mm", "shortDate": "dd/MM/yy", "shortTime": "HH.mm" }, "NUMBER_FORMATS": { "CURRENCY_SYM": "Rp", "DECIMAL_SEP": ",", "GROUP_SEP": ".", "PATTERNS": [ { "gSize": 3, "lgSize": 3, "maxFrac": 3, "minFrac": 0, "minInt": 1, "negPre": "-", "negSuf": "", "posPre": "", "posSuf": "" }, { "gSize": 3, "lgSize": 3, "maxFrac": 2, "minFrac": 2, "minInt": 1, "negPre": "\u00a4-", "negSuf": "", "posPre": "\u00a4", "posSuf": "" } ] }, "id": "in", "pluralCat": function(n, opt_precision) { return PLURAL_CATEGORY.OTHER;} }); }]);
// Copyright 2009 the Sputnik authors. All rights reserved. // This code is governed by the BSD license found in the LICENSE file. /** * @name: S15.3.5.3_A2_T2; * @section: 15.3.5.3, 11.8.6; * @assertion: Assume F is a Function object. When the [[HasInstance]] method of F is called with value V and V is an object, the following steps are taken: * i) Call the [[Get]] method of F with property name "prototype". * ii) Let O be Result(i). * iii) O is not an object, throw a TypeError exception; * @description: F.prototype is undefined, and V is empty object; */ FACTORY = new Function; FACTORY.prototype = undefined; obj={}; //CHECK#1 try { obj instanceof FACTORY; $FAIL('#1: O is not an object, throw a TypeError exception'); } catch (e) { if (!(e instanceof TypeError)) { $ERROR('#1.1: O is not an object, throw a TypeError exception'); } }
/************************************************************* * * MathJax/jax/output/HTML-CSS/fonts/Latin-Modern/Marks/Regular/Main.js * * Copyright (c) 2013-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.OutputJax['HTML-CSS'].FONTDATA.FONTS['LatinModernMathJax_Marks'] = { directory: 'Marks/Regular', family: 'LatinModernMathJax_Marks', testString: '\u00A0\u02DB\u02DD\u0305\u0309\u030F\u0311\u0323\u0326\u032C\u032D\u032E\u032F\u0330\u0331', 0x20: [0,0,332,0,0], 0xA0: [0,0,332,0,0], 0x2DB: [5,211,500,135,364], 0x2DD: [697,-511,500,128,420], 0x305: [670,-630,0,-460,-68], 0x309: [729,-520,0,-361,-167], 0x30F: [732,-546,0,-434,-142], 0x311: [742,-605,0,-451,-77], 0x323: [-94,200,0,-318,-211], 0x326: [-66,290,0,-308,-220], 0x32C: [-96,243,0,-446,-82], 0x32D: [-108,255,0,-446,-82], 0x32E: [-96,233,0,-451,-77], 0x32F: [-118,255,0,-451,-77], 0x330: [-118,310,0,-449,-79], 0x331: [-131,162,0,-444,-83], 0x332: [-103,143,0,-460,-68], 0x333: [-103,293,0,-460,-68], 0x33F: [820,-630,0,-460,-68], 0x2000: [0,0,500,0,0], 0x2001: [0,0,1000,0,0], 0x2007: [0,0,500,0,0], 0x2008: [0,0,250,0,0], 0x200B: [0,0,0,0,0], 0x200C: [0,0,0,0,0], 0x200D: [0,0,0,0,0], 0x2010: [245,-187,333,11,276], 0x2012: [342,-302,680,56,624], 0x2015: [270,-230,1152,56,1096], 0x2017: [-103,293,504,56,448], 0x201A: [104,195,278,79,199], 0x201E: [104,195,472,86,400], 0x2022: [445,-55,500,55,445], 0x202F: [0,0,200,0,0], 0x2030: [750,56,1140,53,1087], 0x2031: [750,56,1457,56,1417], 0x2036: [748,-430,511,60,451], 0x2037: [748,-430,711,60,651], 0x2039: [483,0,389,111,277], 0x203A: [483,0,389,112,278], 0x203B: [492,-8,778,147,630], 0x203D: [756,0,472,43,402], 0x2052: [751,-1,500,56,444], 0x205F: [0,0,222,0,0], 0x2060: [0,0,0,0,0], 0x2061: [640,240,960,40,920], 0x2062: [0,0,0,0,0], 0x2063: [0,0,0,0,0], 0x2064: [0,0,0,0,0], 0x20D0: [711,-601,0,-475,-53], 0x20D1: [711,-601,0,-475,-53], 0x20D2: [750,250,0,-284,-244], 0x20D3: [520,20,0,-284,-244], 0x20D4: [751,-589,0,-473,-55], 0x20D5: [751,-589,0,-473,-55], 0x20D6: [711,-521,0,-472,-56], 0x20D8: [400,-100,0,-414,-114], 0x20DB: [696,-604,0,-530,2], 0x20DC: [696,-604,0,-640,112], 0x20DD: [772,272,0,-786,258], 0x20DE: [750,250,0,-764,236], 0x20DF: [1028,528,0,-1042,514], 0x20E1: [711,-521,0,-499,-29], 0x20E4: [831,311,0,-924,396], 0x20E5: [750,250,0,-458,-69], 0x20E6: [750,250,0,-352,-176], 0x20E8: [-96,188,0,-530,2], 0x20E9: [726,-552,0,-444,-84], 0x20EA: [510,10,0,-706,178], 0x20EB: [750,250,0,-531,3], 0x20EC: [-171,281,0,-475,-53], 0x20ED: [-171,281,0,-475,-53], 0x20EE: [-91,281,0,-472,-56], 0x20EF: [-91,281,0,-472,-56], 0x20F0: [827,-518,0,-401,-126], 0x2E18: [500,256,472,56,415], 0x3016: [770,270,458,56,402], 0x3017: [770,270,458,57,402] }; MathJax.Callback.Queue( ["initFont",MathJax.OutputJax["HTML-CSS"],"LatinModernMathJax_Marks"], ["loadComplete",MathJax.Ajax,MathJax.OutputJax["HTML-CSS"].fontDir+"/Marks/Regular/Main.js"] );
/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ var acorn = require("acorn-dynamic-import").default; var Tapable = require("tapable"); var BasicEvaluatedExpression = require("./BasicEvaluatedExpression"); function Parser(options) { Tapable.call(this); this.options = options; this.initializeEvaluating(); } module.exports = Parser; // Syntax: https://developer.mozilla.org/en/SpiderMonkey/Parser_API Parser.prototype = Object.create(Tapable.prototype); Parser.prototype.constructor = Parser; Parser.prototype.initializeEvaluating = function() { function joinRanges(startRange, endRange) { if(!endRange) return startRange; if(!startRange) return endRange; return [startRange[0], endRange[1]]; } this.plugin("evaluate Literal", function(expr) { switch(typeof expr.value) { case "number": return new BasicEvaluatedExpression().setNumber(expr.value).setRange(expr.range); case "string": return new BasicEvaluatedExpression().setString(expr.value).setRange(expr.range); case "boolean": return new BasicEvaluatedExpression().setBoolean(expr.value).setRange(expr.range); } if(expr.value === null) return new BasicEvaluatedExpression().setNull().setRange(expr.range); if(expr.value instanceof RegExp) return new BasicEvaluatedExpression().setRegExp(expr.value).setRange(expr.range); }); this.plugin("evaluate LogicalExpression", function(expr) { var left; var leftAsBool; var right; if(expr.operator === "&&") { left = this.evaluateExpression(expr.left); leftAsBool = left && left.asBool(); if(leftAsBool === false) return left.setRange(expr.range); if(leftAsBool !== true) return; right = this.evaluateExpression(expr.right); return right.setRange(expr.range); } else if(expr.operator === "||") { left = this.evaluateExpression(expr.left); leftAsBool = left && left.asBool(); if(leftAsBool === true) return left.setRange(expr.range); if(leftAsBool !== false) return; right = this.evaluateExpression(expr.right); return right.setRange(expr.range); } }); this.plugin("evaluate BinaryExpression", function(expr) { var left; var right; var res; if(expr.operator === "+") { left = this.evaluateExpression(expr.left); right = this.evaluateExpression(expr.right); if(!left || !right) return; res = new BasicEvaluatedExpression(); if(left.isString()) { if(right.isString()) { res.setString(left.string + right.string); } else if(right.isNumber()) { res.setString(left.string + right.number); } else if(right.isWrapped() && right.prefix && right.prefix.isString()) { res.setWrapped( new BasicEvaluatedExpression() .setString(left.string + right.prefix.string) .setRange(joinRanges(left.range, right.prefix.range)), right.postfix); } else { res.setWrapped(left, null); } } else if(left.isNumber()) { if(right.isString()) { res.setString(left.number + right.string); } else if(right.isNumber()) { res.setNumber(left.number + right.number); } } else if(left.isWrapped()) { if(left.postfix && left.postfix.isString() && right.isString()) { res.setWrapped(left.prefix, new BasicEvaluatedExpression() .setString(left.postfix.string + right.string) .setRange(joinRanges(left.postfix.range, right.range)) ); } else if(left.postfix && left.postfix.isString() && right.isNumber()) { res.setWrapped(left.prefix, new BasicEvaluatedExpression() .setString(left.postfix.string + right.number) .setRange(joinRanges(left.postfix.range, right.range)) ); } else if(right.isString()) { res.setWrapped(left.prefix, right); } else if(right.isNumber()) { res.setWrapped(left.prefix, new BasicEvaluatedExpression() .setString(right.number + "") .setRange(right.range)); } else { res.setWrapped(left.prefix, new BasicEvaluatedExpression()); } } else { if(right.isString()) { res.setWrapped(null, right); } } res.setRange(expr.range); return res; } else if(expr.operator === "-") { left = this.evaluateExpression(expr.left); right = this.evaluateExpression(expr.right); if(!left || !right) return; if(!left.isNumber() || !right.isNumber()) return; res = new BasicEvaluatedExpression(); res.setNumber(left.number - right.number); res.setRange(expr.range); return res; } else if(expr.operator === "*") { left = this.evaluateExpression(expr.left); right = this.evaluateExpression(expr.right); if(!left || !right) return; if(!left.isNumber() || !right.isNumber()) return; res = new BasicEvaluatedExpression(); res.setNumber(left.number * right.number); res.setRange(expr.range); return res; } else if(expr.operator === "/") { left = this.evaluateExpression(expr.left); right = this.evaluateExpression(expr.right); if(!left || !right) return; if(!left.isNumber() || !right.isNumber()) return; res = new BasicEvaluatedExpression(); res.setNumber(left.number / right.number); res.setRange(expr.range); return res; } else if(expr.operator === "==" || expr.operator === "===") { left = this.evaluateExpression(expr.left); right = this.evaluateExpression(expr.right); if(!left || !right) return; res = new BasicEvaluatedExpression(); res.setRange(expr.range); if(left.isString() && right.isString()) { return res.setBoolean(left.string === right.string); } else if(left.isNumber() && right.isNumber()) { return res.setBoolean(left.number === right.number); } else if(left.isBoolean() && right.isBoolean()) { return res.setBoolean(left.bool === right.bool); } } else if(expr.operator === "!=" || expr.operator === "!==") { left = this.evaluateExpression(expr.left); right = this.evaluateExpression(expr.right); if(!left || !right) return; res = new BasicEvaluatedExpression(); res.setRange(expr.range); if(left.isString() && right.isString()) { return res.setBoolean(left.string !== right.string); } else if(left.isNumber() && right.isNumber()) { return res.setBoolean(left.number !== right.number); } else if(left.isBoolean() && right.isBoolean()) { return res.setBoolean(left.bool !== right.bool); } } }); this.plugin("evaluate UnaryExpression", function(expr) { if(expr.operator === "typeof") { var res; if(expr.argument.type === "Identifier") { var name = this.scope.renames["$" + expr.argument.name] || expr.argument.name; if(this.scope.definitions.indexOf(name) === -1) { res = this.applyPluginsBailResult1("evaluate typeof " + name, expr); if(res !== undefined) return res; } } if(expr.argument.type === "MemberExpression") { var expression = expr.argument; var exprName = []; while(expression.type === "MemberExpression" && !expression.computed) { exprName.unshift(this.scope.renames["$" + expression.property.name] || expression.property.name); expression = expression.object; } if(expression.type === "Identifier") { exprName.unshift(this.scope.renames["$" + expression.name] || expression.name); if(this.scope.definitions.indexOf(name) === -1) { exprName = exprName.join("."); res = this.applyPluginsBailResult1("evaluate typeof " + exprName, expr); if(res !== undefined) return res; } } } if(expr.argument.type === "FunctionExpression") { return new BasicEvaluatedExpression().setString("function").setRange(expr.range); } var arg = this.evaluateExpression(expr.argument); if(arg.isString() || arg.isWrapped()) return new BasicEvaluatedExpression().setString("string").setRange(expr.range); else if(arg.isNumber()) return new BasicEvaluatedExpression().setString("number").setRange(expr.range); else if(arg.isBoolean()) return new BasicEvaluatedExpression().setString("boolean").setRange(expr.range); else if(arg.isArray() || arg.isConstArray() || arg.isRegExp()) return new BasicEvaluatedExpression().setString("object").setRange(expr.range); } else if(expr.operator === "!") { var argument = this.evaluateExpression(expr.argument); if(!argument) return; if(argument.isBoolean()) { return new BasicEvaluatedExpression().setBoolean(!argument.bool).setRange(expr.range); } else if(argument.isString()) { return new BasicEvaluatedExpression().setBoolean(!argument.string).setRange(expr.range); } else if(argument.isNumber()) { return new BasicEvaluatedExpression().setBoolean(!argument.number).setRange(expr.range); } } }); this.plugin("evaluate typeof undefined", function(expr) { return new BasicEvaluatedExpression().setString("undefined").setRange(expr.range); }); this.plugin("evaluate Identifier", function(expr) { var name = this.scope.renames["$" + expr.name] || expr.name; if(this.scope.definitions.indexOf(expr.name) === -1) { var result = this.applyPluginsBailResult1("evaluate Identifier " + name, expr); if(result) return result; return new BasicEvaluatedExpression().setIdentifier(name).setRange(expr.range); } else { return this.applyPluginsBailResult1("evaluate defined Identifier " + name, expr); } }); this.plugin("evaluate MemberExpression", function(expression) { var expr = expression; var exprName = []; while(expr.type === "MemberExpression" && expr.property.type === (expr.computed ? "Literal" : "Identifier") ) { exprName.unshift(expr.property.name || expr.property.value); expr = expr.object; } if(expr.type === "Identifier") { var name = this.scope.renames["$" + expr.name] || expr.name; if(this.scope.definitions.indexOf(name) === -1) { exprName.unshift(name); exprName = exprName.join("."); if(this.scope.definitions.indexOf(expr.name) === -1) { var result = this.applyPluginsBailResult1("evaluate Identifier " + exprName, expression); if(result) return result; return new BasicEvaluatedExpression().setIdentifier(exprName).setRange(expression.range); } else { return this.applyPluginsBailResult1("evaluate defined Identifier " + exprName, expression); } } } }); this.plugin("evaluate CallExpression", function(expr) { if(expr.callee.type !== "MemberExpression") return; if(expr.callee.property.type !== (expr.callee.computed ? "Literal" : "Identifier")) return; var param = this.evaluateExpression(expr.callee.object); if(!param) return; var property = expr.callee.property.name || expr.callee.property.value; return this.applyPluginsBailResult("evaluate CallExpression ." + property, expr, param); }); this.plugin("evaluate CallExpression .replace", function(expr, param) { if(!param.isString()) return; if(expr.arguments.length !== 2) return; var arg1 = this.evaluateExpression(expr.arguments[0]); var arg2 = this.evaluateExpression(expr.arguments[1]); if(!arg1.isString() && !arg1.isRegExp()) return; arg1 = arg1.regExp || arg1.string; if(!arg2.isString()) return; arg2 = arg2.string; return new BasicEvaluatedExpression().setString(param.string.replace(arg1, arg2)).setRange(expr.range); }); ["substr", "substring"].forEach(function(fn) { this.plugin("evaluate CallExpression ." + fn, function(expr, param) { if(!param.isString()) return; var arg1; var result, str = param.string; switch(expr.arguments.length) { case 1: arg1 = this.evaluateExpression(expr.arguments[0]); if(!arg1.isNumber()) return; result = str[fn](arg1.number); break; case 2: arg1 = this.evaluateExpression(expr.arguments[0]); var arg2 = this.evaluateExpression(expr.arguments[1]); if(!arg1.isNumber()) return; if(!arg2.isNumber()) return; result = str[fn](arg1.number, arg2.number); break; default: return; } return new BasicEvaluatedExpression().setString(result).setRange(expr.range); }); /** * @param {string} kind "cooked" | "raw" * @param {any[]} quasis quasis * @param {any[]} expressions expressions * @return {BasicEvaluatedExpression[]} Simplified template */ function getSimplifiedTemplateResult(kind, quasis, expressions) { var i = 0; var parts = []; for(i = 0; i < quasis.length; i++) { parts.push(new BasicEvaluatedExpression().setString(quasis[i].value[kind]).setRange(quasis[i].range)); if(i > 0) { var prevExpr = parts[parts.length - 2], lastExpr = parts[parts.length - 1]; var expr = this.evaluateExpression(expressions[i - 1]); if(!(expr.isString() || expr.isNumber())) continue; prevExpr.setString(prevExpr.string + (expr.isString() ? expr.string : expr.number) + lastExpr.string); prevExpr.setRange([prevExpr.range[0], lastExpr.range[1]]); parts.pop(); } } return parts; } this.plugin("evaluate TemplateLiteral", function(node) { var parts = getSimplifiedTemplateResult.call(this, "cooked", node.quasis, node.expressions); if(parts.length === 1) { return parts[0].setRange(node.range); } return new BasicEvaluatedExpression().setTemplateString(parts).setRange(node.range); }); this.plugin("evaluate TaggedTemplateExpression", function(node) { if(this.evaluateExpression(node.tag).identifier !== "String.raw") return; var parts = getSimplifiedTemplateResult.call(this, "raw", node.quasi.quasis, node.quasi.expressions); return new BasicEvaluatedExpression().setTemplateString(parts).setRange(node.range); }); }, this); this.plugin("evaluate CallExpression .split", function(expr, param) { if(!param.isString()) return; if(expr.arguments.length !== 1) return; var result; var arg = this.evaluateExpression(expr.arguments[0]); if(arg.isString()) { result = param.string.split(arg.string); } else if(arg.isRegExp()) { result = param.string.split(arg.regExp); } else return; return new BasicEvaluatedExpression().setArray(result).setRange(expr.range); }); this.plugin("evaluate ConditionalExpression", function(expr) { var condition = this.evaluateExpression(expr.test); var conditionValue = condition.asBool(); var res; if(conditionValue === undefined) { var consequent = this.evaluateExpression(expr.consequent); var alternate = this.evaluateExpression(expr.alternate); if(!consequent || !alternate) return; res = new BasicEvaluatedExpression(); if(consequent.isConditional()) res.setOptions(consequent.options); else res.setOptions([consequent]); if(alternate.isConditional()) res.addOptions(alternate.options); else res.addOptions([alternate]); } else { res = this.evaluateExpression(conditionValue ? expr.consequent : expr.alternate); } res.setRange(expr.range); return res; }); this.plugin("evaluate ArrayExpression", function(expr) { var items = expr.elements.map(function(element) { return element !== null && this.evaluateExpression(element); }, this); if(!items.every(Boolean)) return; return new BasicEvaluatedExpression().setItems(items).setRange(expr.range); }); }; Parser.prototype.getRenameIdentifier = function getRenameIdentifier(expr) { var result = this.evaluateExpression(expr); if(!result) return; if(result.isIdentifier()) return result.identifier; return; }; Parser.prototype.walkClass = function walkClass(classy) { if(classy.superClass) this.walkExpression(classy.superClass); if(classy.body && classy.body.type === "ClassBody") { classy.body.body.forEach(function(methodDefinition) { if(methodDefinition.type === "MethodDefinition") this.walkMethodDefinition(methodDefinition); }, this); } }; Parser.prototype.walkMethodDefinition = function walkMethodDefinition(methodDefinition) { if(methodDefinition.computed && methodDefinition.key) this.walkExpression(methodDefinition.key); if(methodDefinition.value) this.walkExpression(methodDefinition.value); }; Parser.prototype.walkStatements = function walkStatements(statements) { for(var indexA = 0, lenA = statements.length; indexA < lenA; indexA++) { var statementA = statements[indexA]; if(this.isHoistedStatement(statementA)) this.walkStatement(statementA); } for(var indexB = 0, lenB = statements.length; indexB < lenB; indexB++) { var statementB = statements[indexB]; if(!this.isHoistedStatement(statementB)) this.walkStatement(statementB); } }; Parser.prototype.isHoistedStatement = function isHoistedStatement(statement) { switch(statement.type) { case "ImportDeclaration": case "ExportAllDeclaration": case "ExportNamedDeclaration": return true; } return false; }; Parser.prototype.walkStatement = function walkStatement(statement) { if(this.applyPluginsBailResult1("statement", statement) !== undefined) return; if(this["walk" + statement.type]) this["walk" + statement.type](statement); }; // Real Statements Parser.prototype.walkBlockStatement = function walkBlockStatement(statement) { this.walkStatements(statement.body); }; Parser.prototype.walkExpressionStatement = function walkExpressionStatement(statement) { this.walkExpression(statement.expression); }; Parser.prototype.walkIfStatement = function walkIfStatement(statement) { var result = this.applyPluginsBailResult1("statement if", statement); if(result === undefined) { this.walkExpression(statement.test); this.walkStatement(statement.consequent); if(statement.alternate) this.walkStatement(statement.alternate); } else { if(result) this.walkStatement(statement.consequent); else if(statement.alternate) this.walkStatement(statement.alternate); } }; Parser.prototype.walkLabeledStatement = function walkLabeledStatement(statement) { var result = this.applyPluginsBailResult1("label " + statement.label.name, statement); if(result !== true) this.walkStatement(statement.body); }; Parser.prototype.walkWithStatement = function walkWithStatement(statement) { this.walkExpression(statement.object); this.walkStatement(statement.body); }; Parser.prototype.walkSwitchStatement = function walkSwitchStatement(statement) { this.walkExpression(statement.discriminant); this.walkSwitchCases(statement.cases); }; Parser.prototype.walkReturnStatement = Parser.prototype.walkThrowStatement = function walkArgumentStatement(statement) { if(statement.argument) this.walkExpression(statement.argument); }; Parser.prototype.walkTryStatement = function walkTryStatement(statement) { if(this.scope.inTry) { this.walkStatement(statement.block); } else { this.scope.inTry = true; this.walkStatement(statement.block); this.scope.inTry = false; } if(statement.handler) this.walkCatchClause(statement.handler); if(statement.finalizer) this.walkStatement(statement.finalizer); }; Parser.prototype.walkWhileStatement = Parser.prototype.walkDoWhileStatement = function walkLoopStatement(statement) { this.walkExpression(statement.test); this.walkStatement(statement.body); }; Parser.prototype.walkForStatement = function walkForStatement(statement) { if(statement.init) { if(statement.init.type === "VariableDeclaration") this.walkStatement(statement.init); else this.walkExpression(statement.init); } if(statement.test) this.walkExpression(statement.test); if(statement.update) this.walkExpression(statement.update); this.walkStatement(statement.body); }; Parser.prototype.walkForInStatement = function walkForInStatement(statement) { if(statement.left.type === "VariableDeclaration") this.walkStatement(statement.left); else this.walkExpression(statement.left); this.walkExpression(statement.right); this.walkStatement(statement.body); }; Parser.prototype.walkForOfStatement = function walkForOfStatement(statement) { if(statement.left.type === "VariableDeclaration") this.walkStatement(statement.left); else this.walkExpression(statement.left); this.walkExpression(statement.right); this.walkStatement(statement.body); }; // Declarations Parser.prototype.walkFunctionDeclaration = function walkFunctionDeclaration(statement) { this.scope.renames["$" + statement.id.name] = undefined; this.scope.definitions.push(statement.id.name); this.inScope(statement.params, function() { if(statement.body.type === "BlockStatement") this.walkStatement(statement.body); else this.walkExpression(statement.body); }.bind(this)); }; Parser.prototype.walkImportDeclaration = function walkImportDeclaration(statement) { var source = statement.source.value; this.applyPluginsBailResult("import", statement, source); statement.specifiers.forEach(function(specifier) { var name = specifier.local.name; this.scope.renames["$" + name] = undefined; this.scope.definitions.push(name); switch(specifier.type) { case "ImportDefaultSpecifier": this.applyPluginsBailResult("import specifier", statement, source, "default", name); break; case "ImportSpecifier": this.applyPluginsBailResult("import specifier", statement, source, specifier.imported.name, name); break; case "ImportNamespaceSpecifier": this.applyPluginsBailResult("import specifier", statement, source, null, name); break; } }, this); }; Parser.prototype.walkExportNamedDeclaration = function walkExportNamedDeclaration(statement) { if(statement.source) { var source = statement.source.value; this.applyPluginsBailResult("export import", statement, source); } else { this.applyPluginsBailResult1("export", statement); } if(statement.declaration) { if(/Expression$/.test(statement.declaration.type)) { throw new Error("Doesn't occur?"); } else { if(!this.applyPluginsBailResult("export declaration", statement, statement.declaration)) { var pos = this.scope.definitions.length; this.walkStatement(statement.declaration); var newDefs = this.scope.definitions.slice(pos); for(var index = newDefs.length - 1; index >= 0; index--) { var def = newDefs[index]; this.applyPluginsBailResult("export specifier", statement, def, def, index); } } } } if(statement.specifiers) { for(var specifierIndex = 0; specifierIndex < statement.specifiers.length; specifierIndex++) { var specifier = statement.specifiers[specifierIndex]; switch(specifier.type) { case "ExportSpecifier": var name = specifier.exported.name; if(source) this.applyPluginsBailResult("export import specifier", statement, source, specifier.local.name, name, specifierIndex); else this.applyPluginsBailResult("export specifier", statement, specifier.local.name, name, specifierIndex); break; } } } }; Parser.prototype.walkExportDefaultDeclaration = function walkExportDefaultDeclaration(statement) { this.applyPluginsBailResult1("export", statement); if(/Declaration$/.test(statement.declaration.type)) { if(!this.applyPluginsBailResult("export declaration", statement, statement.declaration)) { var pos = this.scope.definitions.length; this.walkStatement(statement.declaration); var newDefs = this.scope.definitions.slice(pos); for(var index = 0, len = newDefs.length; index < len; index++) { var def = newDefs[index]; this.applyPluginsBailResult("export specifier", statement, def, "default"); } } } else { this.walkExpression(statement.declaration); if(!this.applyPluginsBailResult("export expression", statement, statement.declaration)) { this.applyPluginsBailResult("export specifier", statement, statement.declaration, "default"); } } }; Parser.prototype.walkExportAllDeclaration = function walkExportAllDeclaration(statement) { var source = statement.source.value; this.applyPluginsBailResult("export import", statement, source); this.applyPluginsBailResult("export import specifier", statement, source, null, null, 0); }; Parser.prototype.walkVariableDeclaration = function walkVariableDeclaration(statement) { if(statement.declarations) this.walkVariableDeclarators(statement.declarations); }; Parser.prototype.walkClassDeclaration = function walkClassDeclaration(statement) { this.scope.renames["$" + statement.id.name] = undefined; this.scope.definitions.push(statement.id.name); this.walkClass(statement); }; Parser.prototype.walkSwitchCases = function walkSwitchCases(switchCases) { for(var index = 0, len = switchCases.length; index < len; index++) { var switchCase = switchCases[index]; if(switchCase.test) { this.walkExpression(switchCase.test); } this.walkStatements(switchCase.consequent); } }; Parser.prototype.walkCatchClause = function walkCatchClause(catchClause) { if(catchClause.guard) this.walkExpression(catchClause.guard); this.inScope([catchClause.param], function() { this.walkStatement(catchClause.body); }.bind(this)); }; Parser.prototype.walkVariableDeclarators = function walkVariableDeclarators(declarators) { var _this = this; declarators.forEach(function(declarator) { switch(declarator.type) { case "VariableDeclarator": var renameIdentifier = declarator.init && _this.getRenameIdentifier(declarator.init); if(renameIdentifier && declarator.id.type === "Identifier" && _this.applyPluginsBailResult1("can-rename " + renameIdentifier, declarator.init)) { // renaming with "var a = b;" if(!_this.applyPluginsBailResult1("rename " + renameIdentifier, declarator.init)) { _this.scope.renames["$" + declarator.id.name] = _this.scope.renames["$" + renameIdentifier] || renameIdentifier; var idx = _this.scope.definitions.indexOf(declarator.id.name); if(idx >= 0) _this.scope.definitions.splice(idx, 1); } } else { _this.walkPattern(declarator.id); _this.enterPattern(declarator.id, function(name, decl) { if(!_this.applyPluginsBailResult1("var " + name, decl)) { _this.scope.renames["$" + name] = undefined; _this.scope.definitions.push(name); } }); if(declarator.init) _this.walkExpression(declarator.init); } break; } }); }; Parser.prototype.walkPattern = function walkPattern(pattern) { if(pattern.type === "Identifier") return; if(this["walk" + pattern.type]) this["walk" + pattern.type](pattern); }; Parser.prototype.walkObjectPattern = function walkObjectPattern(pattern) { for(var i = 0, len = pattern.properties.length; i < len; i++) { var prop = pattern.properties[i]; if(prop) { if(prop.computed) this.walkExpression(prop.key); if(prop.value) this.walkPattern(prop.value); } } }; Parser.prototype.walkArrayPattern = function walkArrayPattern(pattern) { for(var i = 0, len = pattern.elements.length; i < len; i++) { var element = pattern.elements[i]; if(element) this.walkPattern(element); } }; Parser.prototype.walkRestElement = function walkRestElement(pattern) { this.walkPattern(pattern.argument); }; Parser.prototype.walkExpressions = function walkExpressions(expressions) { for(var expressionsIndex = 0, len = expressions.length; expressionsIndex < len; expressionsIndex++) { var expression = expressions[expressionsIndex]; if(expression) this.walkExpression(expression); } }; Parser.prototype.walkExpression = function walkExpression(expression) { if(this["walk" + expression.type]) return this["walk" + expression.type](expression); }; Parser.prototype.walkAwaitExpression = function walkAwaitExpression(expression) { var argument = expression.argument; if(this["walk" + argument.type]) return this["walk" + argument.type](argument); }; Parser.prototype.walkArrayExpression = function walkArrayExpression(expression) { if(expression.elements) this.walkExpressions(expression.elements); }; Parser.prototype.walkSpreadElement = function walkSpreadElement(expression) { if(expression.argument) this.walkExpression(expression.argument); }; Parser.prototype.walkObjectExpression = function walkObjectExpression(expression) { for(var propIndex = 0, len = expression.properties.length; propIndex < len; propIndex++) { var prop = expression.properties[propIndex]; if(prop.computed) this.walkExpression(prop.key); if(prop.shorthand) this.scope.inShorthand = true; this.walkExpression(prop.value); if(prop.shorthand) this.scope.inShorthand = false; } }; Parser.prototype.walkFunctionExpression = function walkFunctionExpression(expression) { this.inScope(expression.params, function() { if(expression.body.type === "BlockStatement") this.walkStatement(expression.body); else this.walkExpression(expression.body); }.bind(this)); }; Parser.prototype.walkArrowFunctionExpression = function walkArrowFunctionExpression(expression) { this.inScope(expression.params, function() { if(expression.body.type === "BlockStatement") this.walkStatement(expression.body); else this.walkExpression(expression.body); }.bind(this)); }; Parser.prototype.walkSequenceExpression = function walkSequenceExpression(expression) { if(expression.expressions) this.walkExpressions(expression.expressions); }; Parser.prototype.walkUpdateExpression = function walkUpdateExpression(expression) { this.walkExpression(expression.argument); }; Parser.prototype.walkUnaryExpression = function walkUnaryExpression(expression) { if(expression.operator === "typeof") { var expr = expression.argument; var exprName = []; while(expr.type === "MemberExpression" && expr.property.type === (expr.computed ? "Literal" : "Identifier") ) { exprName.unshift(expr.property.name || expr.property.value); expr = expr.object; } if(expr.type === "Identifier" && this.scope.definitions.indexOf(expr.name) === -1) { exprName.unshift(this.scope.renames["$" + expr.name] || expr.name); exprName = exprName.join("."); var result = this.applyPluginsBailResult1("typeof " + exprName, expression); if(result === true) return; } } this.walkExpression(expression.argument); }; Parser.prototype.walkBinaryExpression = Parser.prototype.walkLogicalExpression = function walkLeftRightExpression(expression) { this.walkExpression(expression.left); this.walkExpression(expression.right); }; Parser.prototype.walkAssignmentExpression = function walkAssignmentExpression(expression) { var renameIdentifier = this.getRenameIdentifier(expression.right); if(expression.left.type === "Identifier" && renameIdentifier && this.applyPluginsBailResult1("can-rename " + renameIdentifier, expression.right)) { // renaming "a = b;" if(!this.applyPluginsBailResult1("rename " + renameIdentifier, expression.right)) { this.scope.renames["$" + expression.left.name] = renameIdentifier; var idx = this.scope.definitions.indexOf(expression.left.name); if(idx >= 0) this.scope.definitions.splice(idx, 1); } } else if(expression.left.type === "Identifier") { if(!this.applyPluginsBailResult1("assigned " + expression.left.name, expression)) { this.walkExpression(expression.right); } this.scope.renames["$" + expression.left.name] = undefined; if(!this.applyPluginsBailResult1("assign " + expression.left.name, expression)) { this.walkExpression(expression.left); } } else { this.walkExpression(expression.right); this.scope.renames["$" + expression.left.name] = undefined; this.walkExpression(expression.left); } }; Parser.prototype.walkConditionalExpression = function walkConditionalExpression(expression) { var result = this.applyPluginsBailResult1("expression ?:", expression); if(result === undefined) { this.walkExpression(expression.test); this.walkExpression(expression.consequent); if(expression.alternate) this.walkExpression(expression.alternate); } else { if(result) this.walkExpression(expression.consequent); else if(expression.alternate) this.walkExpression(expression.alternate); } }; Parser.prototype.walkNewExpression = function walkNewExpression(expression) { this.walkExpression(expression.callee); if(expression.arguments) this.walkExpressions(expression.arguments); }; Parser.prototype.walkYieldExpression = function walkYieldExpression(expression) { if(expression.argument) this.walkExpression(expression.argument); }; Parser.prototype.walkTemplateLiteral = function walkTemplateLiteral(expression) { if(expression.expressions) this.walkExpressions(expression.expressions); }; Parser.prototype.walkTaggedTemplateExpression = function walkTaggedTemplateExpression(expression) { if(expression.tag) this.walkExpression(expression.tag); if(expression.quasi && expression.quasi.expressions) this.walkExpressions(expression.quasi.expressions); }; Parser.prototype.walkClassExpression = function walkClassExpression(expression) { this.walkClass(expression); }; Parser.prototype.walkCallExpression = function walkCallExpression(expression) { var result; function walkIIFE(functionExpression, options) { var params = functionExpression.params; var args = options.map(function(arg) { var renameIdentifier = this.getRenameIdentifier(arg); if(renameIdentifier && this.applyPluginsBailResult1("can-rename " + renameIdentifier, arg)) { if(!this.applyPluginsBailResult1("rename " + renameIdentifier, arg)) return renameIdentifier; } this.walkExpression(arg); }, this); this.inScope(params.filter(function(identifier, idx) { return !args[idx]; }), function() { for(var i = 0; i < args.length; i++) { var param = args[i]; if(!param) continue; if(!params[i] || params[i].type !== "Identifier") continue; this.scope.renames["$" + params[i].name] = param; } if(functionExpression.body.type === "BlockStatement") this.walkStatement(functionExpression.body); else this.walkExpression(functionExpression.body); }.bind(this)); } if(expression.callee.type === "MemberExpression" && expression.callee.object.type === "FunctionExpression" && !expression.callee.computed && (["call", "bind"]).indexOf(expression.callee.property.name) >= 0 && expression.arguments && expression.arguments.length > 1 ) { // (function(...) { }.call/bind(?, ...)) walkIIFE.call(this, expression.callee.object, expression.arguments.slice(1)); this.walkExpression(expression.arguments[0]); } else if(expression.callee.type === "FunctionExpression" && expression.arguments) { // (function(...) { }(...)) walkIIFE.call(this, expression.callee, expression.arguments); } else if(expression.callee.type === "Import") { result = this.applyPluginsBailResult1("import-call", expression); if(result === true) return; if(expression.arguments) this.walkExpressions(expression.arguments); } else { var callee = this.evaluateExpression(expression.callee); if(callee.isIdentifier()) { result = this.applyPluginsBailResult1("call " + callee.identifier, expression); if(result === true) return; } if(expression.callee) this.walkExpression(expression.callee); if(expression.arguments) this.walkExpressions(expression.arguments); } }; Parser.prototype.walkMemberExpression = function walkMemberExpression(expression) { var expr = expression; var exprName = []; while(expr.type === "MemberExpression" && expr.property.type === (expr.computed ? "Literal" : "Identifier") ) { exprName.unshift(expr.property.name || expr.property.value); expr = expr.object; } if(expr.type === "Identifier" && this.scope.definitions.indexOf(expr.name) === -1) { exprName.unshift(this.scope.renames["$" + expr.name] || expr.name); var result = this.applyPluginsBailResult1("expression " + exprName.join("."), expression); if(result === true) return; exprName[exprName.length - 1] = "*"; result = this.applyPluginsBailResult1("expression " + exprName.join("."), expression); if(result === true) return; } this.walkExpression(expression.object); if(expression.computed === true) this.walkExpression(expression.property); }; Parser.prototype.walkIdentifier = function walkIdentifier(expression) { if(this.scope.definitions.indexOf(expression.name) === -1) { var result = this.applyPluginsBailResult1("expression " + (this.scope.renames["$" + expression.name] || expression.name), expression); if(result === true) return; } }; Parser.prototype.inScope = function inScope(params, fn) { var oldScope = this.scope; var _this = this; this.scope = { inTry: false, inShorthand: false, definitions: oldScope.definitions.slice(), renames: Object.create(oldScope.renames) }; for(var paramIndex = 0, len = params.length; paramIndex < len; paramIndex++) { var param = params[paramIndex]; if(typeof param !== "string") { _this.enterPattern(param, function(param) { _this.scope.renames["$" + param] = undefined; _this.scope.definitions.push(param); }); } else { _this.scope.renames["$" + param] = undefined; _this.scope.definitions.push(param); } } fn(); _this.scope = oldScope; }; Parser.prototype.enterPattern = function enterPattern(pattern, onIdent) { if(pattern && this["enter" + pattern.type]) this["enter" + pattern.type](pattern, onIdent); }; Parser.prototype.enterIdentifier = function enterIdentifier(pattern, onIdent) { onIdent(pattern.name, pattern); }; Parser.prototype.enterObjectPattern = function enterObjectPattern(pattern, onIdent) { for(var propIndex = 0, len = pattern.properties.length; propIndex < len; propIndex++) { var prop = pattern.properties[propIndex]; this.enterPattern(prop.value, onIdent); } }; Parser.prototype.enterArrayPattern = function enterArrayPattern(pattern, onIdent) { for(var elementIndex = 0, len = pattern.elements.length; elementIndex < len; elementIndex++) { var element = pattern.elements[elementIndex]; this.enterPattern(element, onIdent); } }; Parser.prototype.enterRestElement = function enterRestElement(pattern, onIdent) { this.enterPattern(pattern.argument, onIdent); }; Parser.prototype.enterAssignmentPattern = function enterAssignmentPattern(pattern, onIdent) { this.enterPattern(pattern.left, onIdent); this.walkExpression(pattern.right); }; Parser.prototype.evaluateExpression = function evaluateExpression(expression) { try { var result = this.applyPluginsBailResult1("evaluate " + expression.type, expression); if(result !== undefined) return result; } catch(e) { console.warn(e); // ignore error } return new BasicEvaluatedExpression().setRange(expression.range); }; Parser.prototype.parseString = function parseString(expression) { switch(expression.type) { case "BinaryExpression": if(expression.operator === "+") return this.parseString(expression.left) + this.parseString(expression.right); break; case "Literal": return expression.value + ""; } throw new Error(expression.type + " is not supported as parameter for require"); }; Parser.prototype.parseCalculatedString = function parseCalculatedString(expression) { switch(expression.type) { case "BinaryExpression": if(expression.operator === "+") { var left = this.parseCalculatedString(expression.left); var right = this.parseCalculatedString(expression.right); if(left.code) { return { range: left.range, value: left.value, code: true }; } else if(right.code) { return { range: [left.range[0], right.range ? right.range[1] : left.range[1]], value: left.value + right.value, code: true }; } else { return { range: [left.range[0], right.range[1]], value: left.value + right.value }; } } break; case "ConditionalExpression": var consequent = this.parseCalculatedString(expression.consequent); var alternate = this.parseCalculatedString(expression.alternate); var items = []; if(consequent.conditional) Array.prototype.push.apply(items, consequent.conditional); else if(!consequent.code) items.push(consequent); else break; if(alternate.conditional) Array.prototype.push.apply(items, alternate.conditional); else if(!alternate.code) items.push(alternate); else break; return { value: "", code: true, conditional: items }; case "Literal": return { range: expression.range, value: expression.value + "" }; } return { value: "", code: true }; }; ["parseString", "parseCalculatedString"].forEach(function(fn) { Parser.prototype[fn + "Array"] = function parseXXXArray(expression) { switch(expression.type) { case "ArrayExpression": var arr = []; if(expression.elements) expression.elements.forEach(function(expr) { arr.push(this[fn](expr)); }, this); return arr; } return [this[fn](expression)]; }; }); var POSSIBLE_AST_OPTIONS = [{ ranges: true, locations: true, ecmaVersion: 2017, sourceType: "module", plugins: { dynamicImport: true } }, { ranges: true, locations: true, ecmaVersion: 2017, sourceType: "script", plugins: { dynamicImport: true } }]; Parser.prototype.parse = function parse(source, initialState) { var ast, comments = []; for(var i = 0, len = POSSIBLE_AST_OPTIONS.length; i < len; i++) { if(!ast) { try { comments.length = 0; POSSIBLE_AST_OPTIONS[i].onComment = comments; ast = acorn.parse(source, POSSIBLE_AST_OPTIONS[i]); } catch(e) { // ignore the error } } } if(!ast) { // for the error ast = acorn.parse(source, { ranges: true, locations: true, ecmaVersion: 2017, sourceType: "module", plugins: { dynamicImport: true }, onComment: comments }); } if(!ast || typeof ast !== "object") throw new Error("Source couldn't be parsed"); var oldScope = this.scope; var oldState = this.state; this.scope = { inTry: false, definitions: [], renames: {} }; var state = this.state = initialState || {}; if(this.applyPluginsBailResult("program", ast, comments) === undefined) this.walkStatements(ast.body); this.scope = oldScope; this.state = oldState; return state; }; Parser.prototype.evaluate = function evaluate(source) { var ast = acorn.parse("(" + source + ")", { ranges: true, locations: true, ecmaVersion: 2017, sourceType: "module", plugins: { dynamicImport: true } }); if(!ast || typeof ast !== "object" || ast.type !== "Program") throw new Error("evaluate: Source couldn't be parsed"); if(ast.body.length !== 1 || ast.body[0].type !== "ExpressionStatement") throw new Error("evaluate: Source is not a expression"); return this.evaluateExpression(ast.body[0].expression); };
import './css/site.css' import 'core-js/es6/promise' import 'core-js/es6/array' import { app } from './app' app.$mount('#app')
define('lodash/collection/find', ['exports', 'lodash/internal/baseEach', 'lodash/internal/createFind'], function (exports, _lodashInternalBaseEach, _lodashInternalCreateFind) { 'use strict'; /** * Iterates over elements of `collection`, returning the first element * `predicate` returns truthy for. The predicate is bound to `thisArg` and * invoked with three arguments: (value, index|key, collection). * * If a property name is provided for `predicate` the created `_.property` * style callback returns the property value of the given element. * * If a value is also provided for `thisArg` the created `_.matchesProperty` * style callback returns `true` for elements that have a matching property * value, else `false`. * * If an object is provided for `predicate` the created `_.matches` style * callback returns `true` for elements that have the properties of the given * object, else `false`. * * @static * @memberOf _ * @alias detect * @category Collection * @param {Array|Object|string} collection The collection to search. * @param {Function|Object|string} [predicate=_.identity] The function invoked * per iteration. * @param {*} [thisArg] The `this` binding of `predicate`. * @returns {*} Returns the matched element, else `undefined`. * @example * * var users = [ * { 'user': 'barney', 'age': 36, 'active': true }, * { 'user': 'fred', 'age': 40, 'active': false }, * { 'user': 'pebbles', 'age': 1, 'active': true } * ]; * * _.result(_.find(users, function(chr) { * return chr.age < 40; * }), 'user'); * // => 'barney' * * // using the `_.matches` callback shorthand * _.result(_.find(users, { 'age': 1, 'active': true }), 'user'); * // => 'pebbles' * * // using the `_.matchesProperty` callback shorthand * _.result(_.find(users, 'active', false), 'user'); * // => 'fred' * * // using the `_.property` callback shorthand * _.result(_.find(users, 'active'), 'user'); * // => 'barney' */ var find = (0, _lodashInternalCreateFind['default'])(_lodashInternalBaseEach['default']); exports['default'] = find; });
/* * Copyright (C) 2013 Google Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /** * @constructor * @implements {WebInspector.TextFilterUI.SuggestionBuilder} * @param {!Array.<string>} keys */ WebInspector.FilterSuggestionBuilder = function(keys) { this._keys = keys; this._valueSets = {}; this._valueLists = {}; } WebInspector.FilterSuggestionBuilder.prototype = { /** * @param {!HTMLInputElement} input * @return {?Array.<string>} */ buildSuggestions: function(input) { var text = input.value; var end = input.selectionEnd; if (end != text.length) return null; var start = input.selectionStart; text = text.substring(0, start); var prefixIndex = text.lastIndexOf(" ") + 1; var prefix = text.substring(prefixIndex); if (!prefix) return []; var valueDelimiterIndex = prefix.indexOf(":"); var suggestions = []; if (valueDelimiterIndex === -1) { for (var j = 0; j < this._keys.length; ++j) { if (this._keys[j].startsWith(prefix)) suggestions.push(this._keys[j] + ":"); } } else { var key = prefix.substring(0, valueDelimiterIndex); var value = prefix.substring(valueDelimiterIndex + 1); var items = this._values(key); for (var i = 0; i < items.length; ++i) { if (items[i].startsWith(value) && (items[i] !== value)) suggestions.push(key + ":" + items[i]); } } return suggestions; }, /** * @param {!HTMLInputElement} input * @param {string} suggestion * @param {boolean} isIntermediate */ applySuggestion: function(input, suggestion, isIntermediate) { var text = input.value; var start = input.selectionStart; text = text.substring(0, start); var prefixIndex = text.lastIndexOf(" ") + 1; text = text.substring(0, prefixIndex) + suggestion; input.value = text; if (!isIntermediate) start = text.length; input.setSelectionRange(start, text.length); }, /** * @param {!HTMLInputElement} input */ unapplySuggestion: function(input) { var start = input.selectionStart; var end = input.selectionEnd; var text = input.value; if (start !== end && end === text.length) input.value = text.substring(0, start); }, /** * @param {string} key * @return {!Array.<string>} */ _values: function(key) { var result = this._valueLists[key]; if (!result) return []; result.sort(); return result; }, /** * @param {string} key * @param {?string=} value */ addItem: function(key, value) { if (!value) return; var set = this._valueSets[key]; var list = this._valueLists[key]; if (!set) { set = {}; this._valueSets[key] = set; list = []; this._valueLists[key] = list; } if (set[value]) return; set[value] = true; list.push(value); }, /** * @param {string} query * @return {{text: !Array.<string>, filters: !Object.<string, string>}} */ parseQuery: function(query) { var filters = {}; var text = []; var i = 0; var j = 0; var part; while (true) { var colonIndex = query.indexOf(":", i); if (colonIndex == -1) { part = query.substring(j); if (part) text.push(part); break; } var spaceIndex = query.lastIndexOf(" ", colonIndex); var key = query.substring(spaceIndex + 1, colonIndex); if (this._keys.indexOf(key) == -1) { i = colonIndex + 1; continue; } part = spaceIndex > j ? query.substring(j, spaceIndex) : ""; if (part) text.push(part); var nextSpace = query.indexOf(" ", colonIndex + 1); if (nextSpace == -1) { filters[key] = query.substring(colonIndex + 1); break; } filters[key] = query.substring(colonIndex + 1, nextSpace); i = nextSpace + 1; j = i; } return {text: text, filters: filters}; } };
if (window.midgardCreate === undefined) { window.midgardCreate = {}; } if (window.midgardCreate.locale === undefined) { window.midgardCreate.locale = {}; } window.midgardCreate.locale.nl = { // Session-state buttons for the main toolbar 'Save': 'Opslaan', 'Saving': 'Bezig met opslaan', 'Cancel': 'Annuleren', 'Edit': 'Bewerken', // Storage status messages 'localModification': 'Items "<%= label %>" op de pagina heeft lokale wijzigingen', 'localModifications': '<%= number %> items op de pagina hebben lokale wijzigingen', 'Restore': 'Herstellen', 'Ignore': 'Negeren', 'saveSuccess': 'Item "<%= label %>" succesvol opgeslagen', 'saveSuccessMultiple': '<%= number %> items succesvol opgeslagen', 'saveError': 'Fout opgetreden bij het opslaan<br /><%= error %>', // Tagging 'Item tags': 'Item tags', 'Suggested tags': 'Tag suggesties', 'Tags': 'Tags', 'add a tag': 'tag toevoegen', // Collection widgets 'Add': 'Toevoegen', 'Choose type to add': 'Kies type om toe te voegen' };
/* =========================================================== * ua.js * Ukrainian translation for Trumbowyg * http://alex-d.github.com/Trumbowyg * =========================================================== * Author : Igor Buksha */ jQuery.trumbowyg.langs.ua = { viewHTML:"Подивитись HTML", formatting:"Форматування", p:"Звичайний", blockquote:"Витяг", code:"Код", header:"Заголовок", bold:"Напівжирний", italic:"Курсив", strikethrough:"Закреслений", underline:"Підкреслений", strong:"Напівжирний", em:"Курсив", del:"Закреслений", unorderedList:"Звичайний список", orderedList:"Нумерований список", insertImage:"Вставити зображення", insertVideo:"Вставити відео", link:"Посилання", createLink:"Вставити посилання", unlink:"Видалити посилання", justifyLeft:"По лівому краю", justifyCenter:"В центрі", justifyRight:"По правому краю", justifyFull:"По ширині", horizontalRule:"Горизонтальна лінія", fullscreen:"На весь екран", close:"Закрити", submit:"Вставити", reset:"Скасувати", required:"Обов'язкове", description:"Опис", title:"Підказка", text:"Текст" };
'use strict'; exports.__esModule = true; var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _react = require('react'); var _react2 = _interopRequireDefault(_react); var _LinkContainer = require('./LinkContainer'); var _LinkContainer2 = _interopRequireDefault(_LinkContainer); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } // Don't use a stateless function, to allow users to set a ref. /* eslint-disable react/prefer-stateless-function */ var IndexLinkContainer = function (_React$Component) { _inherits(IndexLinkContainer, _React$Component); function IndexLinkContainer() { _classCallCheck(this, IndexLinkContainer); return _possibleConstructorReturn(this, _React$Component.apply(this, arguments)); } IndexLinkContainer.prototype.render = function render() { return _react2.default.createElement(_LinkContainer2.default, _extends({}, this.props, { exact: true })); }; return IndexLinkContainer; }(_react2.default.Component); /* eslint-enable react/prefer-stateless-function */ exports.default = IndexLinkContainer; module.exports = exports['default'];
/*! UIkit 3.0.0-rc.18 | http://www.getuikit.com | (c) 2014 - 2018 YOOtheme | MIT License */ (function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory(require('uikit-util')) : typeof define === 'function' && define.amd ? define('uikitslideshow', ['uikit-util'], factory) : (global.UIkitSlideshow = factory(global.UIkit.util)); }(this, (function (uikitUtil) { 'use strict'; var Class = { connected: function() { !uikitUtil.hasClass(this.$el, this.$name) && uikitUtil.addClass(this.$el, this.$name); } }; var Animations = { slide: { show: function(dir) { return [ {transform: translate(dir * -100)}, {transform: translate()} ]; }, percent: function(current) { return translated(current); }, translate: function(percent, dir) { return [ {transform: translate(dir * -100 * percent)}, {transform: translate(dir * 100 * (1 - percent))} ]; } } }; function translated(el) { return Math.abs(uikitUtil.css(el, 'transform').split(',')[4] / el.offsetWidth) || 0; } function translate(value, unit) { if ( value === void 0 ) value = 0; if ( unit === void 0 ) unit = '%'; return ("translateX(" + value + (value ? unit : '') + ")"); // currently not translate3d to support IE, translate3d within translate3d does not work while transitioning } function scale3d(value) { return ("scale3d(" + value + ", " + value + ", 1)"); } function Transitioner(prev, next, dir, ref) { var animation = ref.animation; var easing = ref.easing; var percent = animation.percent; var translate = animation.translate; var show = animation.show; if ( show === void 0 ) show = uikitUtil.noop; var props = show(dir); var deferred = new uikitUtil.Deferred(); return { dir: dir, show: function(duration, percent, linear) { var this$1 = this; if ( percent === void 0 ) percent = 0; var timing = linear ? 'linear' : easing; duration -= Math.round(duration * uikitUtil.clamp(percent, -1, 1)); this.translate(percent); triggerUpdate(next, 'itemin', {percent: percent, duration: duration, timing: timing, dir: dir}); triggerUpdate(prev, 'itemout', {percent: 1 - percent, duration: duration, timing: timing, dir: dir}); uikitUtil.Promise.all([ uikitUtil.Transition.start(next, props[1], duration, timing), uikitUtil.Transition.start(prev, props[0], duration, timing) ]).then(function () { this$1.reset(); deferred.resolve(); }, uikitUtil.noop); return deferred.promise; }, stop: function() { return uikitUtil.Transition.stop([next, prev]); }, cancel: function() { uikitUtil.Transition.cancel([next, prev]); }, reset: function() { for (var prop in props[0]) { uikitUtil.css([next, prev], prop, ''); } }, forward: function(duration, percent) { if ( percent === void 0 ) percent = this.percent(); uikitUtil.Transition.cancel([next, prev]); return this.show(duration, percent, true); }, translate: function(percent) { this.reset(); var props = translate(percent, dir); uikitUtil.css(next, props[1]); uikitUtil.css(prev, props[0]); triggerUpdate(next, 'itemtranslatein', {percent: percent, dir: dir}); triggerUpdate(prev, 'itemtranslateout', {percent: 1 - percent, dir: dir}); }, percent: function() { return percent(prev || next, next, dir); }, getDistance: function() { return prev.offsetWidth; } }; } function triggerUpdate(el, type, data) { uikitUtil.trigger(el, uikitUtil.createEvent(type, false, false, data)); } var SliderAutoplay = { props: { autoplay: Boolean, autoplayInterval: Number, pauseOnHover: Boolean }, data: { autoplay: false, autoplayInterval: 7000, pauseOnHover: true }, connected: function() { this.startAutoplay(); }, disconnected: function() { this.stopAutoplay(); }, events: [ { name: 'visibilitychange', el: document, handler: function() { if (document.hidden) { this.stopAutoplay(); } else { this.startAutoplay(); } } }, { name: uikitUtil.pointerDown, handler: 'stopAutoplay' }, { name: 'mouseenter', filter: function() { return this.autoplay; }, handler: function() { this.isHovering = true; } }, { name: 'mouseleave', filter: function() { return this.autoplay; }, handler: function() { this.isHovering = false; } } ], methods: { startAutoplay: function() { var this$1 = this; this.stopAutoplay(); if (this.autoplay) { this.interval = setInterval( function () { return !(this$1.isHovering && this$1.pauseOnHover) && !this$1.stack.length && this$1.show('next'); }, this.autoplayInterval ); } }, stopAutoplay: function() { if (this.interval) { clearInterval(this.interval); } } } }; var SliderDrag = { data: { threshold: 10, preventCatch: false }, created: function() { var this$1 = this; ['start', 'move', 'end'].forEach(function (key) { var fn = this$1[key]; this$1[key] = function (e) { var pos = uikitUtil.getPos(e).x * (uikitUtil.isRtl ? -1 : 1); this$1.prevPos = pos !== this$1.pos ? this$1.pos : this$1.prevPos; this$1.pos = pos; fn(e); }; }); }, events: [ { name: uikitUtil.pointerDown, delegate: function() { return this.slidesSelector; }, handler: function(e) { if (!uikitUtil.isTouch(e) && hasTextNodesOnly(e.target) || e.button > 0 || this.length < 2 || this.preventCatch ) { return; } this.start(e); } }, { // Workaround for iOS 11 bug: https://bugs.webkit.org/show_bug.cgi?id=184250 name: 'touchmove', passive: false, handler: 'move', delegate: function() { return this.slidesSelector; } }, { name: 'dragstart', handler: function(e) { e.preventDefault(); } } ], methods: { start: function() { var this$1 = this; this.drag = this.pos; if (this._transitioner) { this.percent = this._transitioner.percent(); this.drag += this._transitioner.getDistance() * this.percent * this.dir; this._transitioner.cancel(); this._transitioner.translate(this.percent); this.dragging = true; this.stack = []; } else { this.prevIndex = this.index; } // See above workaround notice var off = uikitUtil.on(document, uikitUtil.pointerMove.replace(' touchmove', ''), this.move, {passive: false}); this.unbindMove = function () { off(); this$1.unbindMove = null; }; uikitUtil.on(window, 'scroll', this.unbindMove); uikitUtil.on(document, uikitUtil.pointerUp, this.end, true); }, move: function(e) { var this$1 = this; // See above workaround notice if (!this.unbindMove) { return; } var distance = this.pos - this.drag; if (distance === 0 || this.prevPos === this.pos || !this.dragging && Math.abs(distance) < this.threshold) { return; } e.cancelable && e.preventDefault(); this.dragging = true; this.dir = (distance < 0 ? 1 : -1); var ref = this; var slides = ref.slides; var ref$1 = this; var prevIndex = ref$1.prevIndex; var dis = Math.abs(distance); var nextIndex = this.getIndex(prevIndex + this.dir, prevIndex); var width = this._getDistance(prevIndex, nextIndex) || slides[prevIndex].offsetWidth; while (nextIndex !== prevIndex && dis > width) { this$1.drag -= width * this$1.dir; prevIndex = nextIndex; dis -= width; nextIndex = this$1.getIndex(prevIndex + this$1.dir, prevIndex); width = this$1._getDistance(prevIndex, nextIndex) || slides[prevIndex].offsetWidth; } this.percent = dis / width; var prev = slides[prevIndex]; var next = slides[nextIndex]; var changed = this.index !== nextIndex; var edge = prevIndex === nextIndex; var itemShown; [this.index, this.prevIndex].filter(function (i) { return !uikitUtil.includes([nextIndex, prevIndex], i); }).forEach(function (i) { uikitUtil.trigger(slides[i], 'itemhidden', [this$1]); if (edge) { itemShown = true; this$1.prevIndex = prevIndex; } }); if (this.index === prevIndex && this.prevIndex !== prevIndex || itemShown) { uikitUtil.trigger(slides[this.index], 'itemshown', [this]); } if (changed) { this.prevIndex = prevIndex; this.index = nextIndex; !edge && uikitUtil.trigger(prev, 'beforeitemhide', [this]); uikitUtil.trigger(next, 'beforeitemshow', [this]); } this._transitioner = this._translate(Math.abs(this.percent), prev, !edge && next); if (changed) { !edge && uikitUtil.trigger(prev, 'itemhide', [this]); uikitUtil.trigger(next, 'itemshow', [this]); } }, end: function() { uikitUtil.off(window, 'scroll', this.unbindMove); this.unbindMove && this.unbindMove(); uikitUtil.off(document, uikitUtil.pointerUp, this.end, true); if (this.dragging) { this.dragging = null; if (this.index === this.prevIndex) { this.percent = 1 - this.percent; this.dir *= -1; this._show(false, this.index, true); this._transitioner = null; } else { var dirChange = (uikitUtil.isRtl ? this.dir * (uikitUtil.isRtl ? 1 : -1) : this.dir) < 0 === this.prevPos > this.pos; this.index = dirChange ? this.index : this.prevIndex; if (dirChange) { this.percent = 1 - this.percent; } this.show(this.dir > 0 && !dirChange || this.dir < 0 && dirChange ? 'next' : 'previous', true); } uikitUtil.preventClick(); } this.drag = this.percent = null; } } }; function hasTextNodesOnly(el) { return !el.children.length && el.childNodes.length; } var SliderNav = { data: { selNav: false }, computed: { nav: function(ref, $el) { var selNav = ref.selNav; return uikitUtil.$(selNav, $el); }, navItemSelector: function(ref) { var attrItem = ref.attrItem; return ("[" + attrItem + "],[data-" + attrItem + "]"); }, navItems: function(_, $el) { return uikitUtil.$$(this.navItemSelector, $el); } }, update: { write: function() { var this$1 = this; if (this.nav && this.length !== this.nav.children.length) { uikitUtil.html(this.nav, this.slides.map(function (_, i) { return ("<li " + (this$1.attrItem) + "=\"" + i + "\"><a href=\"#\"></a></li>"); }).join('')); } uikitUtil.toggleClass(uikitUtil.$$(this.navItemSelector, this.$el).concat(this.nav), 'uk-hidden', !this.maxIndex); this.updateNav(); }, events: ['load', 'resize'] }, events: [ { name: 'click', delegate: function() { return this.navItemSelector; }, handler: function(e) { e.preventDefault(); e.current.blur(); this.show(uikitUtil.data(e.current, this.attrItem)); } }, { name: 'itemshow', handler: 'updateNav' } ], methods: { updateNav: function() { var this$1 = this; var i = this.getValidIndex(); this.navItems.forEach(function (el) { var cmd = uikitUtil.data(el, this$1.attrItem); uikitUtil.toggleClass(el, this$1.clsActive, uikitUtil.toNumber(cmd) === i); uikitUtil.toggleClass(el, 'uk-invisible', this$1.finite && (cmd === 'previous' && i === 0 || cmd === 'next' && i >= this$1.maxIndex)); }); } } }; var Slider = { mixins: [SliderAutoplay, SliderDrag, SliderNav], props: { clsActivated: Boolean, easing: String, index: Number, finite: Boolean, velocity: Number }, data: function () { return ({ easing: 'ease', finite: false, velocity: 1, index: 0, stack: [], percent: 0, clsActive: 'uk-active', clsActivated: false, Transitioner: false, transitionOptions: {} }); }, computed: { duration: function(ref, $el) { var velocity = ref.velocity; return speedUp($el.offsetWidth / velocity); }, length: function() { return this.slides.length; }, list: function(ref, $el) { var selList = ref.selList; return uikitUtil.$(selList, $el); }, maxIndex: function() { return this.length - 1; }, slidesSelector: function(ref) { var selList = ref.selList; return (selList + " > *"); }, slides: function() { return uikitUtil.toNodes(this.list.children); } }, events: { itemshown: function() { this.$update(this.list); } }, methods: { show: function(index, force) { var this$1 = this; if ( force === void 0 ) force = false; if (this.dragging || !this.length) { return; } var ref = this; var stack = ref.stack; var queueIndex = force ? 0 : stack.length; var reset = function () { stack.splice(queueIndex, 1); if (stack.length) { this$1.show(stack.shift(), true); } }; stack[force ? 'unshift' : 'push'](index); if (!force && stack.length > 1) { if (stack.length === 2) { this._transitioner.forward(Math.min(this.duration, 200)); } return; } var prevIndex = this.index; var prev = uikitUtil.hasClass(this.slides, this.clsActive) && this.slides[prevIndex]; var nextIndex = this.getIndex(index, this.index); var next = this.slides[nextIndex]; if (prev === next) { reset(); return; } this.dir = getDirection(index, prevIndex); this.prevIndex = prevIndex; this.index = nextIndex; prev && uikitUtil.trigger(prev, 'beforeitemhide', [this]); if (!uikitUtil.trigger(next, 'beforeitemshow', [this, prev])) { this.index = this.prevIndex; reset(); return; } var promise = this._show(prev, next, force).then(function () { prev && uikitUtil.trigger(prev, 'itemhidden', [this$1]); uikitUtil.trigger(next, 'itemshown', [this$1]); return new uikitUtil.Promise(function (resolve) { uikitUtil.fastdom.write(function () { stack.shift(); if (stack.length) { this$1.show(stack.shift(), true); } else { this$1._transitioner = null; } resolve(); }); }); }); prev && uikitUtil.trigger(prev, 'itemhide', [this]); uikitUtil.trigger(next, 'itemshow', [this]); return promise; }, getIndex: function(index, prev) { if ( index === void 0 ) index = this.index; if ( prev === void 0 ) prev = this.index; return uikitUtil.clamp(uikitUtil.getIndex(index, this.slides, prev, this.finite), 0, this.maxIndex); }, getValidIndex: function(index, prevIndex) { if ( index === void 0 ) index = this.index; if ( prevIndex === void 0 ) prevIndex = this.prevIndex; return this.getIndex(index, prevIndex); }, _show: function(prev, next, force) { this._transitioner = this._getTransitioner( prev, next, this.dir, uikitUtil.assign({ easing: force ? next.offsetWidth < 600 ? 'cubic-bezier(0.25, 0.46, 0.45, 0.94)' /* easeOutQuad */ : 'cubic-bezier(0.165, 0.84, 0.44, 1)' /* easeOutQuart */ : this.easing }, this.transitionOptions) ); if (!force && !prev) { this._transitioner.translate(1); return uikitUtil.Promise.resolve(); } var ref = this.stack; var length = ref.length; return this._transitioner[length > 1 ? 'forward' : 'show'](length > 1 ? Math.min(this.duration, 75 + 75 / (length - 1)) : this.duration, this.percent); }, _getDistance: function(prev, next) { return new this._getTransitioner(prev, prev !== next && next).getDistance(); }, _translate: function(percent, prev, next) { if ( prev === void 0 ) prev = this.prevIndex; if ( next === void 0 ) next = this.index; var transitioner = this._getTransitioner(prev !== next ? prev : false, next); transitioner.translate(percent); return transitioner; }, _getTransitioner: function(prev, next, dir, options) { if ( prev === void 0 ) prev = this.prevIndex; if ( next === void 0 ) next = this.index; if ( dir === void 0 ) dir = this.dir || 1; if ( options === void 0 ) options = this.transitionOptions; return new this.Transitioner( uikitUtil.isNumber(prev) ? this.slides[prev] : prev, uikitUtil.isNumber(next) ? this.slides[next] : next, dir * (uikitUtil.isRtl ? -1 : 1), options ); } } }; function getDirection(index, prevIndex) { return index === 'next' ? 1 : index === 'previous' ? -1 : index < prevIndex ? -1 : 1; } function speedUp(x) { return .5 * x + 300; // parabola through (400,500; 600,600; 1800,1200) } var Slideshow = { mixins: [Slider], props: { animation: String }, data: { animation: 'slide', clsActivated: 'uk-transition-active', Animations: Animations, Transitioner: Transitioner }, computed: { animation: function(ref) { var animation = ref.animation; var Animations$$1 = ref.Animations; return uikitUtil.assign(animation in Animations$$1 ? Animations$$1[animation] : Animations$$1.slide, {name: animation}); }, transitionOptions: function() { return {animation: this.animation}; } }, events: { 'itemshow itemhide itemshown itemhidden': function(ref) { var target = ref.target; this.$update(target); }, itemshow: function() { uikitUtil.isNumber(this.prevIndex) && uikitUtil.fastdom.flush(); // iOS 10+ will honor the video.play only if called from a gesture handler }, beforeitemshow: function(ref) { var target = ref.target; uikitUtil.addClass(target, this.clsActive); }, itemshown: function(ref) { var target = ref.target; uikitUtil.addClass(target, this.clsActivated); }, itemhidden: function(ref) { var target = ref.target; uikitUtil.removeClass(target, this.clsActive, this.clsActivated); } } }; var Animations$1 = uikitUtil.assign({}, Animations, { fade: { show: function() { return [ {opacity: 0, zIndex: 0}, {zIndex: -1} ]; }, percent: function(current) { return 1 - uikitUtil.css(current, 'opacity'); }, translate: function(percent) { return [ {opacity: 1 - percent, zIndex: 0}, {zIndex: -1} ]; } }, scale: { show: function() { return [ {opacity: 0, transform: scale3d(1 + .5), zIndex: 0}, {zIndex: -1} ]; }, percent: function(current) { return 1 - uikitUtil.css(current, 'opacity'); }, translate: function(percent) { return [ {opacity: 1 - percent, transform: scale3d(1 + .5 * percent), zIndex: 0}, {zIndex: -1} ]; } }, pull: { show: function(dir) { return dir < 0 ? [ {transform: translate(30), zIndex: -1}, {transform: translate(), zIndex: 0} ] : [ {transform: translate(-100), zIndex: 0}, {transform: translate(), zIndex: -1} ]; }, percent: function(current, next, dir) { return dir < 0 ? 1 - translated(next) : translated(current); }, translate: function(percent, dir) { return dir < 0 ? [ {transform: translate(30 * percent), zIndex: -1}, {transform: translate(-100 * (1 - percent)), zIndex: 0} ] : [ {transform: translate(-percent * 100), zIndex: 0}, {transform: translate(30 * (1 - percent)), zIndex: -1} ]; } }, push: { show: function(dir) { return dir < 0 ? [ {transform: translate(100), zIndex: 0}, {transform: translate(), zIndex: -1} ] : [ {transform: translate(-30), zIndex: -1}, {transform: translate(), zIndex: 0} ]; }, percent: function(current, next, dir) { return dir > 0 ? 1 - translated(next) : translated(current); }, translate: function(percent, dir) { return dir < 0 ? [ {transform: translate(percent * 100), zIndex: 0}, {transform: translate(-30 * (1 - percent)), zIndex: -1} ] : [ {transform: translate(-30 * percent), zIndex: -1}, {transform: translate(100 * (1 - percent)), zIndex: 0} ]; } } }); var SliderReactive = { update: { write: function() { if (this.stack.length || this.dragging) { return; } var index = this.getValidIndex(); delete this.index; uikitUtil.removeClass(this.slides, this.clsActive, this.clsActivated); this.show(index); }, events: ['load', 'resize'] } }; var Component = { mixins: [Class, Slideshow, SliderReactive], props: { ratio: String, minHeight: Boolean, maxHeight: Boolean, }, data: { ratio: '16:9', minHeight: false, maxHeight: false, selList: '.uk-slideshow-items', attrItem: 'uk-slideshow-item', selNav: '.uk-slideshow-nav', Animations: Animations$1 }, update: { read: function() { var ref = this.ratio.split(':').map(Number); var width = ref[0]; var height = ref[1]; height = height * this.list.offsetWidth / width; if (this.minHeight) { height = Math.max(this.minHeight, height); } if (this.maxHeight) { height = Math.min(this.maxHeight, height); } return {height: height - uikitUtil.boxModelAdjust(this.list, 'content-box')}; }, write: function(ref) { var height = ref.height; uikitUtil.css(this.list, 'minHeight', height); }, events: ['load', 'resize'] } }; /* global UIkit, 'slideshow' */ if (typeof window !== 'undefined' && window.UIkit) { window.UIkit.component('slideshow', Component); } return Component; })));
/* * Planck.js v0.2.0 * * Copyright (c) 2016-2018 Ali Shakiba http://shakiba.me/planck.js * Copyright (c) 2006-2013 Erin Catto http://www.gphysics.com * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages * arising from the use of this software. * * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software. If you use this software * in a product, an acknowledgment in the product documentation would be * appreciated but is not required. * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software. * 3. This notice may not be removed or altered from any source distribution. */ /* * Stage.js * * @copyright 2017 Ali Shakiba http://shakiba.me/stage.js * @license The MIT License */ !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.planck=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 planck = require("../lib/"); var Stage = require("stage-js/platform/web"); module.exports = planck; planck.testbed = function(opts, callback) { if (typeof opts === "function") { callback = opts; opts = null; } Stage(function(stage, canvas) { stage.on(Stage.Mouse.START, function() { window.focus(); document.activeElement && document.activeElement.blur(); canvas.focus(); }); stage.MAX_ELAPSE = 1e3 / 30; var Vec2 = planck.Vec2; var testbed = {}; var paused = false; stage.on("resume", function() { paused = false; testbed._resume && testbed._resume(); }); stage.on("pause", function() { paused = true; testbed._pause && testbed._pause(); }); testbed.isPaused = function() { return paused; }; testbed.togglePause = function() { paused ? testbed.resume() : testbed.pause(); }; testbed.pause = function() { stage.pause(); }; testbed.resume = function() { stage.resume(); testbed.focus(); }; testbed.focus = function() { document.activeElement && document.activeElement.blur(); canvas.focus(); }; testbed.debug = false; testbed.width = 80; testbed.height = 60; testbed.x = 0; testbed.y = -10; testbed.ratio = 16; testbed.hz = 60; testbed.speed = 1; testbed.activeKeys = {}; testbed.background = "#222222"; var statusText = ""; var statusMap = {}; function statusSet(name, value) { if (typeof value !== "function" && typeof value !== "object") { statusMap[name] = value; } } function statusMerge(obj) { for (var key in obj) { statusSet(key, obj[key]); } } testbed.status = function(a, b) { if (typeof b !== "undefined") { statusSet(a, b); } else if (a && typeof a === "object") { statusMerge(a); } else if (typeof a === "string") { statusText = a; } testbed._status && testbed._status(statusText, statusMap); }; testbed.info = function(text) { testbed._info && testbed._info(text); }; var lastDrawHash = "", drawHash = ""; (function() { var drawingTexture = new Stage.Texture(); stage.append(Stage.image(drawingTexture)); var buffer = []; stage.tick(function() { buffer.length = 0; }, true); drawingTexture.draw = function(ctx) { ctx.save(); ctx.transform(1, 0, 0, -1, -testbed.x, -testbed.y); ctx.lineWidth = 2 / testbed.ratio; ctx.lineCap = "round"; for (var drawing = buffer.shift(); drawing; drawing = buffer.shift()) { drawing(ctx, testbed.ratio); } ctx.restore(); }; testbed.drawPoint = function(p, r, color) { buffer.push(function(ctx, ratio) { ctx.beginPath(); ctx.arc(p.x, p.y, 5 / ratio, 0, 2 * Math.PI); ctx.strokeStyle = color; ctx.stroke(); }); drawHash += "point" + p.x + "," + p.y + "," + r + "," + color; }; testbed.drawCircle = function(p, r, color) { buffer.push(function(ctx) { ctx.beginPath(); ctx.arc(p.x, p.y, r, 0, 2 * Math.PI); ctx.strokeStyle = color; ctx.stroke(); }); drawHash += "circle" + p.x + "," + p.y + "," + r + "," + color; }; testbed.drawSegment = function(a, b, color) { buffer.push(function(ctx) { ctx.beginPath(); ctx.moveTo(a.x, a.y); ctx.lineTo(b.x, b.y); ctx.strokeStyle = color; ctx.stroke(); }); drawHash += "segment" + a.x + "," + a.y + "," + b.x + "," + b.y + "," + color; }; testbed.drawPolygon = function(points, color) { if (!points || !points.length) { return; } buffer.push(function(ctx) { ctx.beginPath(); ctx.moveTo(points[0].x, points[0].y); for (var i = 1; i < points.length; i++) { ctx.lineTo(points[i].x, points[i].y); } ctx.strokeStyle = color; ctx.closePath(); ctx.stroke(); }); drawHash += "segment"; for (var i = 1; i < points.length; i++) { drawHash += points[i].x + "," + points[i].y + ","; } drawHash += color; }; testbed.drawAABB = function(aabb, color) { buffer.push(function(ctx) { ctx.beginPath(); ctx.moveTo(aabb.lowerBound.x, aabb.lowerBound.y); ctx.lineTo(aabb.upperBound.x, aabb.lowerBound.y); ctx.lineTo(aabb.upperBound.x, aabb.upperBound.y); ctx.lineTo(aabb.lowerBound.x, aabb.upperBound.y); ctx.strokeStyle = color; ctx.closePath(); ctx.stroke(); }); drawHash += "aabb"; drawHash += aabb.lowerBound.x + "," + aabb.lowerBound.y + ","; drawHash += aabb.upperBound.x + "," + aabb.upperBound.y + ","; drawHash += color; }; testbed.color = function(r, g, b) { r = r * 256 | 0; g = g * 256 | 0; b = b * 256 | 0; return "rgb(" + r + ", " + g + ", " + b + ")"; }; })(); var world = callback(testbed); var viewer = new Viewer(world, testbed); var lastX = 0, lastY = 0; stage.tick(function(dt, t) { if (lastX !== testbed.x || lastY !== testbed.y) { viewer.offset(-testbed.x, -testbed.y); lastX = testbed.x, lastY = testbed.y; } }); viewer.tick(function(dt, t) { if (typeof testbed.step === "function") { testbed.step(dt, t); } if (targetBody) { testbed.drawSegment(targetBody.getPosition(), mouseMove, "rgba(255,255,255,0.2)"); } if (lastDrawHash !== drawHash) { lastDrawHash = drawHash; stage.touch(); } drawHash = ""; return true; }); stage.background(testbed.background); stage.viewbox(testbed.width, testbed.height); stage.pin("alignX", -.5); stage.pin("alignY", -.5); stage.prepend(viewer); function findBody(point) { var body; var aabb = planck.AABB(point, point); world.queryAABB(aabb, function(fixture) { if (body) { return; } if (!fixture.getBody().isDynamic() || !fixture.testPoint(point)) { return; } body = fixture.getBody(); return true; }); return body; } var mouseGround = world.createBody(); var mouseJoint; var targetBody; var mouseMove = { x: 0, y: 0 }; viewer.attr("spy", true).on(Stage.Mouse.START, function(point) { point = { x: point.x, y: -point.y }; if (targetBody) { return; } var body = findBody(point); if (!body) { return; } if (testbed.mouseForce) { targetBody = body; } else { mouseJoint = planck.MouseJoint({ maxForce: 1e3 }, mouseGround, body, Vec2(point)); world.createJoint(mouseJoint); } }).on(Stage.Mouse.MOVE, function(point) { point = { x: point.x, y: -point.y }; if (mouseJoint) { mouseJoint.setTarget(point); } mouseMove.x = point.x; mouseMove.y = point.y; }).on(Stage.Mouse.END, function(point) { point = { x: point.x, y: -point.y }; if (mouseJoint) { world.destroyJoint(mouseJoint); mouseJoint = null; } if (targetBody) { var force = Vec2.sub(point, targetBody.getPosition()); targetBody.applyForceToCenter(force.mul(testbed.mouseForce), true); targetBody = null; } }).on(Stage.Mouse.CANCEL, function(point) { point = { x: point.x, y: -point.y }; if (mouseJoint) { world.destroyJoint(mouseJoint); mouseJoint = null; } if (targetBody) { targetBody = null; } }); window.addEventListener("keydown", function(e) { switch (e.keyCode) { case "P".charCodeAt(0): testbed.togglePause(); break; } }, false); var downKeys = {}; window.addEventListener("keydown", function(e) { var keyCode = e.keyCode; downKeys[keyCode] = true; updateActiveKeys(keyCode, true); testbed.keydown && testbed.keydown(keyCode, String.fromCharCode(keyCode)); }); window.addEventListener("keyup", function(e) { var keyCode = e.keyCode; downKeys[keyCode] = false; updateActiveKeys(keyCode, false); testbed.keyup && testbed.keyup(keyCode, String.fromCharCode(keyCode)); }); var activeKeys = testbed.activeKeys; function updateActiveKeys(keyCode, down) { var char = String.fromCharCode(keyCode); if (/\w/.test(char)) { activeKeys[char] = down; } activeKeys.right = downKeys[39] || activeKeys["D"]; activeKeys.left = downKeys[37] || activeKeys["A"]; activeKeys.up = downKeys[38] || activeKeys["W"]; activeKeys.down = downKeys[40] || activeKeys["S"]; activeKeys.fire = downKeys[32] || downKeys[13]; } }); }; Viewer._super = Stage; Viewer.prototype = Stage._create(Viewer._super.prototype); function Viewer(world, opts) { Viewer._super.call(this); this.label("Planck"); opts = opts || {}; var options = this._options = {}; this._options.speed = opts.speed || 1; this._options.hz = opts.hz || 60; if (Math.abs(this._options.hz) < 1) { this._options.hz = 1 / this._options.hz; } this._options.ratio = opts.ratio || 16; this._options.lineWidth = 2 / this._options.ratio; this._world = world; var timeStep = 1 / this._options.hz; var elapsedTime = 0; this.tick(function(dt) { dt = dt * .001 * options.speed; elapsedTime += dt; while (elapsedTime > timeStep) { world.step(timeStep); elapsedTime -= timeStep; } this.renderWorld(); return true; }, true); world.on("remove-fixture", function(obj) { obj.ui && obj.ui.remove(); }); world.on("remove-joint", function(obj) { obj.ui && obj.ui.remove(); }); } Viewer.prototype.renderWorld = function(world) { var world = this._world; var viewer = this; for (var b = world.getBodyList(); b; b = b.getNext()) { for (var f = b.getFixtureList(); f; f = f.getNext()) { if (!f.ui) { if (f.render && f.render.stroke) { this._options.strokeStyle = f.render.stroke; } else if (b.render && b.render.stroke) { this._options.strokeStyle = b.render.stroke; } else if (b.isDynamic()) { this._options.strokeStyle = "rgba(255,255,255,0.9)"; } else if (b.isKinematic()) { this._options.strokeStyle = "rgba(255,255,255,0.7)"; } else if (b.isStatic()) { this._options.strokeStyle = "rgba(255,255,255,0.5)"; } if (f.render && f.render.fill) { this._options.fillStyle = f.render.fill; } else if (b.render && b.render.fill) { this._options.fillStyle = b.render.fill; } else { this._options.fillStyle = ""; } var type = f.getType(); var shape = f.getShape(); if (type == "circle") { f.ui = viewer.drawCircle(shape, this._options); } if (type == "edge") { f.ui = viewer.drawEdge(shape, this._options); } if (type == "polygon") { f.ui = viewer.drawPolygon(shape, this._options); } if (type == "chain") { f.ui = viewer.drawChain(shape, this._options); } if (f.ui) { f.ui.appendTo(viewer); } } if (f.ui) { var p = b.getPosition(), r = b.getAngle(); if (f.ui.__lastX !== p.x || f.ui.__lastY !== p.y || f.ui.__lastR !== r) { f.ui.__lastX = p.x; f.ui.__lastY = p.y; f.ui.__lastR = r; f.ui.offset(p.x, -p.y); f.ui.rotate(-r); } } } } for (var j = world.getJointList(); j; j = j.getNext()) { var type = j.getType(); var a = j.getAnchorA(); var b = j.getAnchorB(); if (!j.ui) { this._options.strokeStyle = "rgba(255,255,255,0.2)"; j.ui = viewer.drawJoint(j, this._options); j.ui.pin("handle", .5); if (j.ui) { j.ui.appendTo(viewer); } } if (j.ui) { var cx = (a.x + b.x) * .5; var cy = (-a.y + -b.y) * .5; var dx = a.x - b.x; var dy = -a.y - -b.y; var d = Math.sqrt(dx * dx + dy * dy); j.ui.width(d); j.ui.rotate(Math.atan2(dy, dx)); j.ui.offset(cx, cy); } } }; Viewer.prototype.drawJoint = function(joint, options) { var lw = options.lineWidth; var ratio = options.ratio; var length = 10; var texture = Stage.canvas(function(ctx) { this.size(length + 2 * lw, 2 * lw, ratio); ctx.scale(ratio, ratio); ctx.beginPath(); ctx.moveTo(lw, lw); ctx.lineTo(lw + length, lw); ctx.lineCap = "round"; ctx.lineWidth = options.lineWidth; ctx.strokeStyle = options.strokeStyle; ctx.stroke(); }); var image = Stage.image(texture).stretch(); return image; }; Viewer.prototype.drawCircle = function(shape, options) { var lw = options.lineWidth; var ratio = options.ratio; var r = shape.m_radius; var cx = r + lw; var cy = r + lw; var w = r * 2 + lw * 2; var h = r * 2 + lw * 2; var texture = Stage.canvas(function(ctx) { this.size(w, h, ratio); ctx.scale(ratio, ratio); ctx.arc(cx, cy, r, 0, 2 * Math.PI); if (options.fillStyle) { ctx.fillStyle = options.fillStyle; ctx.fill(); } ctx.lineTo(cx, cy); ctx.lineWidth = options.lineWidth; ctx.strokeStyle = options.strokeStyle; ctx.stroke(); }); var image = Stage.image(texture).offset(shape.m_p.x - cx, -shape.m_p.y - cy); var node = Stage.create().append(image); return node; }; Viewer.prototype.drawEdge = function(edge, options) { var lw = options.lineWidth; var ratio = options.ratio; var v1 = edge.m_vertex1; var v2 = edge.m_vertex2; var dx = v2.x - v1.x; var dy = v2.y - v1.y; var length = Math.sqrt(dx * dx + dy * dy); var texture = Stage.canvas(function(ctx) { this.size(length + 2 * lw, 2 * lw, ratio); ctx.scale(ratio, ratio); ctx.beginPath(); ctx.moveTo(lw, lw); ctx.lineTo(lw + length, lw); ctx.lineCap = "round"; ctx.lineWidth = options.lineWidth; ctx.strokeStyle = options.strokeStyle; ctx.stroke(); }); var minX = Math.min(v1.x, v2.x); var minY = Math.min(-v1.y, -v2.y); var image = Stage.image(texture); console.log(-Math.atan2(dy, dx)); image.rotate(-Math.atan2(dy, dx)); image.offset(minX - lw, minY - lw); var node = Stage.create().append(image); return node; }; Viewer.prototype.drawPolygon = function(shape, options) { var lw = options.lineWidth; var ratio = options.ratio; var vertices = shape.m_vertices; if (!vertices.length) { return; } var minX = Infinity, minY = Infinity; var maxX = -Infinity, maxY = -Infinity; for (var i = 0; i < vertices.length; ++i) { var v = vertices[i]; minX = Math.min(minX, v.x); maxX = Math.max(maxX, v.x); minY = Math.min(minY, -v.y); maxY = Math.max(maxY, -v.y); } var width = maxX - minX; var height = maxY - minY; var texture = Stage.canvas(function(ctx) { this.size(width + 2 * lw, height + 2 * lw, ratio); ctx.scale(ratio, ratio); ctx.beginPath(); for (var i = 0; i < vertices.length; ++i) { var v = vertices[i]; var x = v.x - minX + lw; var y = -v.y - minY + lw; if (i == 0) ctx.moveTo(x, y); else ctx.lineTo(x, y); } if (vertices.length > 2) { ctx.closePath(); } if (options.fillStyle) { ctx.fillStyle = options.fillStyle; ctx.fill(); ctx.closePath(); } ctx.lineCap = "round"; ctx.lineWidth = options.lineWidth; ctx.strokeStyle = options.strokeStyle; ctx.stroke(); }); var image = Stage.image(texture); image.offset(minX - lw, minY - lw); var node = Stage.create().append(image); return node; }; Viewer.prototype.drawChain = function(shape, options) { var lw = options.lineWidth; var ratio = options.ratio; var vertices = shape.m_vertices; if (!vertices.length) { return; } var minX = Infinity, minY = Infinity; var maxX = -Infinity, maxY = -Infinity; for (var i = 0; i < vertices.length; ++i) { var v = vertices[i]; minX = Math.min(minX, v.x); maxX = Math.max(maxX, v.x); minY = Math.min(minY, -v.y); maxY = Math.max(maxY, -v.y); } var width = maxX - minX; var height = maxY - minY; var texture = Stage.canvas(function(ctx) { this.size(width + 2 * lw, height + 2 * lw, ratio); ctx.scale(ratio, ratio); ctx.beginPath(); for (var i = 0; i < vertices.length; ++i) { var v = vertices[i]; var x = v.x - minX + lw; var y = -v.y - minY + lw; if (i == 0) ctx.moveTo(x, y); else ctx.lineTo(x, y); } if (vertices.length > 2) {} if (options.fillStyle) { ctx.fillStyle = options.fillStyle; ctx.fill(); ctx.closePath(); } ctx.lineCap = "round"; ctx.lineWidth = options.lineWidth; ctx.strokeStyle = options.strokeStyle; ctx.stroke(); }); var image = Stage.image(texture); image.offset(minX - lw, minY - lw); var node = Stage.create().append(image); return node; }; },{"../lib/":27,"stage-js/platform/web":82}],2:[function(require,module,exports){ var _DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; var _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = Body; var common = require("./util/common"); var options = require("./util/options"); var Vec2 = require("./common/Vec2"); var Rot = require("./common/Rot"); var Math = require("./common/Math"); var Sweep = require("./common/Sweep"); var Transform = require("./common/Transform"); var Velocity = require("./common/Velocity"); var Position = require("./common/Position"); var Fixture = require("./Fixture"); var Shape = require("./Shape"); var World = require("./World"); var staticBody = Body.STATIC = "static"; var kinematicBody = Body.KINEMATIC = "kinematic"; var dynamicBody = Body.DYNAMIC = "dynamic"; var BodyDef = { type: staticBody, position: Vec2.zero(), angle: 0, linearVelocity: Vec2.zero(), angularVelocity: 0, linearDamping: 0, angularDamping: 0, fixedRotation: false, bullet: false, gravityScale: 1, allowSleep: true, awake: true, active: true, userData: null }; function Body(world, def) { def = options(def, BodyDef); _ASSERT && common.assert(Vec2.isValid(def.position)); _ASSERT && common.assert(Vec2.isValid(def.linearVelocity)); _ASSERT && common.assert(Math.isFinite(def.angle)); _ASSERT && common.assert(Math.isFinite(def.angularVelocity)); _ASSERT && common.assert(Math.isFinite(def.angularDamping) && def.angularDamping >= 0); _ASSERT && common.assert(Math.isFinite(def.linearDamping) && def.linearDamping >= 0); this.m_world = world; this.m_awakeFlag = def.awake; this.m_autoSleepFlag = def.allowSleep; this.m_bulletFlag = def.bullet; this.m_fixedRotationFlag = def.fixedRotation; this.m_activeFlag = def.active; this.m_islandFlag = false; this.m_toiFlag = false; this.m_userData = def.userData; this.m_type = def.type; if (this.m_type == dynamicBody) { this.m_mass = 1; this.m_invMass = 1; } else { this.m_mass = 0; this.m_invMass = 0; } this.m_I = 0; this.m_invI = 0; this.m_xf = Transform.identity(); this.m_xf.p = Vec2.clone(def.position); this.m_xf.q.setAngle(def.angle); this.m_sweep = new Sweep(); this.m_sweep.setTransform(this.m_xf); this.c_velocity = new Velocity(); this.c_position = new Position(); this.m_force = Vec2.zero(); this.m_torque = 0; this.m_linearVelocity = Vec2.clone(def.linearVelocity); this.m_angularVelocity = def.angularVelocity; this.m_linearDamping = def.linearDamping; this.m_angularDamping = def.angularDamping; this.m_gravityScale = def.gravityScale; this.m_sleepTime = 0; this.m_jointList = null; this.m_contactList = null; this.m_fixtureList = null; this.m_prev = null; this.m_next = null; } Body.prototype.isWorldLocked = function() { return this.m_world && this.m_world.isLocked() ? true : false; }; Body.prototype.getWorld = function() { return this.m_world; }; Body.prototype.getNext = function() { return this.m_next; }; Body.prototype.setUserData = function(data) { this.m_userData = data; }; Body.prototype.getUserData = function() { return this.m_userData; }; Body.prototype.getFixtureList = function() { return this.m_fixtureList; }; Body.prototype.getJointList = function() { return this.m_jointList; }; Body.prototype.getContactList = function() { return this.m_contactList; }; Body.prototype.isStatic = function() { return this.m_type == staticBody; }; Body.prototype.isDynamic = function() { return this.m_type == dynamicBody; }; Body.prototype.isKinematic = function() { return this.m_type == kinematicBody; }; Body.prototype.setStatic = function() { this.setType(staticBody); return this; }; Body.prototype.setDynamic = function() { this.setType(dynamicBody); return this; }; Body.prototype.setKinematic = function() { this.setType(kinematicBody); return this; }; Body.prototype.getType = function() { return this.m_type; }; Body.prototype.setType = function(type) { _ASSERT && common.assert(type === staticBody || type === kinematicBody || type === dynamicBody); _ASSERT && common.assert(this.isWorldLocked() == false); if (this.isWorldLocked() == true) { return; } if (this.m_type == type) { return; } this.m_type = type; this.resetMassData(); if (this.m_type == staticBody) { this.m_linearVelocity.setZero(); this.m_angularVelocity = 0; this.m_sweep.forward(); this.synchronizeFixtures(); } this.setAwake(true); this.m_force.setZero(); this.m_torque = 0; var ce = this.m_contactList; while (ce) { var ce0 = ce; ce = ce.next; this.m_world.destroyContact(ce0.contact); } this.m_contactList = null; var broadPhase = this.m_world.m_broadPhase; for (var f = this.m_fixtureList; f; f = f.m_next) { var proxyCount = f.m_proxyCount; for (var i = 0; i < proxyCount; ++i) { broadPhase.touchProxy(f.m_proxies[i].proxyId); } } }; Body.prototype.isBullet = function() { return this.m_bulletFlag; }; Body.prototype.setBullet = function(flag) { this.m_bulletFlag = !!flag; }; Body.prototype.isSleepingAllowed = function() { return this.m_autoSleepFlag; }; Body.prototype.setSleepingAllowed = function(flag) { this.m_autoSleepFlag = !!flag; if (this.m_autoSleepFlag == false) { this.setAwake(true); } }; Body.prototype.isAwake = function() { return this.m_awakeFlag; }; Body.prototype.setAwake = function(flag) { if (flag) { if (this.m_awakeFlag == false) { this.m_awakeFlag = true; this.m_sleepTime = 0; } } else { this.m_awakeFlag = false; this.m_sleepTime = 0; this.m_linearVelocity.setZero(); this.m_angularVelocity = 0; this.m_force.setZero(); this.m_torque = 0; } }; Body.prototype.isActive = function() { return this.m_activeFlag; }; Body.prototype.setActive = function(flag) { _ASSERT && common.assert(this.isWorldLocked() == false); if (flag == this.m_activeFlag) { return; } this.m_activeFlag = !!flag; if (this.m_activeFlag) { var broadPhase = this.m_world.m_broadPhase; for (var f = this.m_fixtureList; f; f = f.m_next) { f.createProxies(broadPhase, this.m_xf); } } else { var broadPhase = this.m_world.m_broadPhase; for (var f = this.m_fixtureList; f; f = f.m_next) { f.destroyProxies(broadPhase); } var ce = this.m_contactList; while (ce) { var ce0 = ce; ce = ce.next; this.m_world.destroyContact(ce0.contact); } this.m_contactList = null; } }; Body.prototype.isFixedRotation = function() { return this.m_fixedRotationFlag; }; Body.prototype.setFixedRotation = function(flag) { if (this.m_fixedRotationFlag == flag) { return; } this.m_fixedRotationFlag = !!flag; this.m_angularVelocity = 0; this.resetMassData(); }; Body.prototype.getTransform = function() { return this.m_xf; }; Body.prototype.setTransform = function(position, angle) { _ASSERT && common.assert(this.isWorldLocked() == false); if (this.isWorldLocked() == true) { return; } this.m_xf.set(position, angle); this.m_sweep.setTransform(this.m_xf); var broadPhase = this.m_world.m_broadPhase; for (var f = this.m_fixtureList; f; f = f.m_next) { f.synchronize(broadPhase, this.m_xf, this.m_xf); } }; Body.prototype.synchronizeTransform = function() { this.m_sweep.getTransform(this.m_xf, 1); }; Body.prototype.synchronizeFixtures = function() { var xf = Transform.identity(); this.m_sweep.getTransform(xf, 0); var broadPhase = this.m_world.m_broadPhase; for (var f = this.m_fixtureList; f; f = f.m_next) { f.synchronize(broadPhase, xf, this.m_xf); } }; Body.prototype.advance = function(alpha) { this.m_sweep.advance(alpha); this.m_sweep.c.set(this.m_sweep.c0); this.m_sweep.a = this.m_sweep.a0; this.m_sweep.getTransform(this.m_xf, 1); }; Body.prototype.getPosition = function() { return this.m_xf.p; }; Body.prototype.setPosition = function(p) { this.setTransform(p, this.m_sweep.a); }; Body.prototype.getAngle = function() { return this.m_sweep.a; }; Body.prototype.setAngle = function(angle) { this.setTransform(this.m_xf.p, angle); }; Body.prototype.getWorldCenter = function() { return this.m_sweep.c; }; Body.prototype.getLocalCenter = function() { return this.m_sweep.localCenter; }; Body.prototype.getLinearVelocity = function() { return this.m_linearVelocity; }; Body.prototype.getLinearVelocityFromWorldPoint = function(worldPoint) { var localCenter = Vec2.sub(worldPoint, this.m_sweep.c); return Vec2.add(this.m_linearVelocity, Vec2.cross(this.m_angularVelocity, localCenter)); }; Body.prototype.getLinearVelocityFromLocalPoint = function(localPoint) { return this.getLinearVelocityFromWorldPoint(this.getWorldPoint(localPoint)); }; Body.prototype.setLinearVelocity = function(v) { if (this.m_type == staticBody) { return; } if (Vec2.dot(v, v) > 0) { this.setAwake(true); } this.m_linearVelocity.set(v); }; Body.prototype.getAngularVelocity = function() { return this.m_angularVelocity; }; Body.prototype.setAngularVelocity = function(w) { if (this.m_type == staticBody) { return; } if (w * w > 0) { this.setAwake(true); } this.m_angularVelocity = w; }; Body.prototype.getLinearDamping = function() { return this.m_linearDamping; }; Body.prototype.setLinearDamping = function(linearDamping) { this.m_linearDamping = linearDamping; }; Body.prototype.getAngularDamping = function() { return this.m_angularDamping; }; Body.prototype.setAngularDamping = function(angularDamping) { this.m_angularDamping = angularDamping; }; Body.prototype.getGravityScale = function() { return this.m_gravityScale; }; Body.prototype.setGravityScale = function(scale) { this.m_gravityScale = scale; }; Body.prototype.getMass = function() { return this.m_mass; }; Body.prototype.getInertia = function() { return this.m_I + this.m_mass * Vec2.dot(this.m_sweep.localCenter, this.m_sweep.localCenter); }; function MassData() { this.mass = 0; this.center = Vec2.zero(); this.I = 0; } Body.prototype.getMassData = function(data) { data.mass = this.m_mass; data.I = this.getInertia(); data.center.set(this.m_sweep.localCenter); }; Body.prototype.resetMassData = function() { this.m_mass = 0; this.m_invMass = 0; this.m_I = 0; this.m_invI = 0; this.m_sweep.localCenter.setZero(); if (this.isStatic() || this.isKinematic()) { this.m_sweep.c0.set(this.m_xf.p); this.m_sweep.c.set(this.m_xf.p); this.m_sweep.a0 = this.m_sweep.a; return; } _ASSERT && common.assert(this.isDynamic()); var localCenter = Vec2.zero(); for (var f = this.m_fixtureList; f; f = f.m_next) { if (f.m_density == 0) { continue; } var massData = new MassData(); f.getMassData(massData); this.m_mass += massData.mass; localCenter.addMul(massData.mass, massData.center); this.m_I += massData.I; } if (this.m_mass > 0) { this.m_invMass = 1 / this.m_mass; localCenter.mul(this.m_invMass); } else { this.m_mass = 1; this.m_invMass = 1; } if (this.m_I > 0 && this.m_fixedRotationFlag == false) { this.m_I -= this.m_mass * Vec2.dot(localCenter, localCenter); _ASSERT && common.assert(this.m_I > 0); this.m_invI = 1 / this.m_I; } else { this.m_I = 0; this.m_invI = 0; } var oldCenter = Vec2.clone(this.m_sweep.c); this.m_sweep.setLocalCenter(localCenter, this.m_xf); this.m_linearVelocity.add(Vec2.cross(this.m_angularVelocity, Vec2.sub(this.m_sweep.c, oldCenter))); }; Body.prototype.setMassData = function(massData) { _ASSERT && common.assert(this.isWorldLocked() == false); if (this.isWorldLocked() == true) { return; } if (this.m_type != dynamicBody) { return; } this.m_invMass = 0; this.m_I = 0; this.m_invI = 0; this.m_mass = massData.mass; if (this.m_mass <= 0) { this.m_mass = 1; } this.m_invMass = 1 / this.m_mass; if (massData.I > 0 && this.m_fixedRotationFlag == false) { this.m_I = massData.I - this.m_mass * Vec2.dot(massData.center, massData.center); _ASSERT && common.assert(this.m_I > 0); this.m_invI = 1 / this.m_I; } var oldCenter = Vec2.clone(this.m_sweep.c); this.m_sweep.setLocalCenter(massData.center, this.m_xf); this.m_linearVelocity.add(Vec2.cross(this.m_angularVelocity, Vec2.sub(this.m_sweep.c, oldCenter))); }; Body.prototype.applyForce = function(force, point, wake) { if (this.m_type != dynamicBody) { return; } if (wake && this.m_awakeFlag == false) { this.setAwake(true); } if (this.m_awakeFlag) { this.m_force.add(force); this.m_torque += Vec2.cross(Vec2.sub(point, this.m_sweep.c), force); } }; Body.prototype.applyForceToCenter = function(force, wake) { if (this.m_type != dynamicBody) { return; } if (wake && this.m_awakeFlag == false) { this.setAwake(true); } if (this.m_awakeFlag) { this.m_force.add(force); } }; Body.prototype.applyTorque = function(torque, wake) { if (this.m_type != dynamicBody) { return; } if (wake && this.m_awakeFlag == false) { this.setAwake(true); } if (this.m_awakeFlag) { this.m_torque += torque; } }; Body.prototype.applyLinearImpulse = function(impulse, point, wake) { if (this.m_type != dynamicBody) { return; } if (wake && this.m_awakeFlag == false) { this.setAwake(true); } if (this.m_awakeFlag) { this.m_linearVelocity.addMul(this.m_invMass, impulse); this.m_angularVelocity += this.m_invI * Vec2.cross(Vec2.sub(point, this.m_sweep.c), impulse); } }; Body.prototype.applyAngularImpulse = function(impulse, wake) { if (this.m_type != dynamicBody) { return; } if (wake && this.m_awakeFlag == false) { this.setAwake(true); } if (this.m_awakeFlag) { this.m_angularVelocity += this.m_invI * impulse; } }; Body.prototype.shouldCollide = function(that) { if (this.m_type != dynamicBody && that.m_type != dynamicBody) { return false; } for (var jn = this.m_jointList; jn; jn = jn.next) { if (jn.other == that) { if (jn.joint.m_collideConnected == false) { return false; } } } return true; }; Body.prototype.createFixture = function(shape, fixdef) { _ASSERT && common.assert(this.isWorldLocked() == false); if (this.isWorldLocked() == true) { return null; } var fixture = new Fixture(this, shape, fixdef); if (this.m_activeFlag) { var broadPhase = this.m_world.m_broadPhase; fixture.createProxies(broadPhase, this.m_xf); } fixture.m_next = this.m_fixtureList; this.m_fixtureList = fixture; if (fixture.m_density > 0) { this.resetMassData(); } this.m_world.m_newFixture = true; return fixture; }; Body.prototype.destroyFixture = function(fixture) { _ASSERT && common.assert(this.isWorldLocked() == false); if (this.isWorldLocked() == true) { return; } _ASSERT && common.assert(fixture.m_body == this); var found = false; if (this.m_fixtureList === fixture) { this.m_fixtureList = fixture.m_next; found = true; } else { var node = this.m_fixtureList; while (node != null) { if (node.m_next === fixture) { node.m_next = fixture.m_next; found = true; break; } node = node.m_next; } } _ASSERT && common.assert(found); var edge = this.m_contactList; while (edge) { var c = edge.contact; edge = edge.next; var fixtureA = c.getFixtureA(); var fixtureB = c.getFixtureB(); if (fixture == fixtureA || fixture == fixtureB) { this.m_world.destroyContact(c); } } if (this.m_activeFlag) { var broadPhase = this.m_world.m_broadPhase; fixture.destroyProxies(broadPhase); } fixture.m_body = null; fixture.m_next = null; this.m_world.publish("remove-fixture", fixture); this.resetMassData(); }; Body.prototype.getWorldPoint = function(localPoint) { return Transform.mul(this.m_xf, localPoint); }; Body.prototype.getWorldVector = function(localVector) { return Rot.mul(this.m_xf.q, localVector); }; Body.prototype.getLocalPoint = function(worldPoint) { return Transform.mulT(this.m_xf, worldPoint); }; Body.prototype.getLocalVector = function(worldVector) { return Rot.mulT(this.m_xf.q, worldVector); }; },{"./Fixture":4,"./Shape":8,"./World":10,"./common/Math":18,"./common/Position":19,"./common/Rot":20,"./common/Sweep":21,"./common/Transform":22,"./common/Vec2":23,"./common/Velocity":25,"./util/common":51,"./util/options":53}],3:[function(require,module,exports){ var _DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; var _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; var DEBUG_SOLVER = false; var common = require("./util/common"); var Math = require("./common/Math"); var Vec2 = require("./common/Vec2"); var Transform = require("./common/Transform"); var Mat22 = require("./common/Mat22"); var Rot = require("./common/Rot"); var Settings = require("./Settings"); var Manifold = require("./Manifold"); var Distance = require("./collision/Distance"); module.exports = Contact; function ContactEdge(contact) { this.contact = contact; this.prev; this.next; this.other; } function Contact(fA, indexA, fB, indexB, evaluateFcn) { this.m_nodeA = new ContactEdge(this); this.m_nodeB = new ContactEdge(this); this.m_fixtureA = fA; this.m_fixtureB = fB; this.m_indexA = indexA; this.m_indexB = indexB; this.m_evaluateFcn = evaluateFcn; this.m_manifold = new Manifold(); this.m_prev = null; this.m_next = null; this.m_toi = 1; this.m_toiCount = 0; this.m_toiFlag = false; this.m_friction = mixFriction(this.m_fixtureA.m_friction, this.m_fixtureB.m_friction); this.m_restitution = mixRestitution(this.m_fixtureA.m_restitution, this.m_fixtureB.m_restitution); this.m_tangentSpeed = 0; this.m_enabledFlag = true; this.m_islandFlag = false; this.m_touchingFlag = false; this.m_filterFlag = false; this.m_bulletHitFlag = false; this.v_points = []; this.v_normal = Vec2.zero(); this.v_normalMass = new Mat22(); this.v_K = new Mat22(); this.v_pointCount; this.v_tangentSpeed; this.v_friction; this.v_restitution; this.v_invMassA; this.v_invMassB; this.v_invIA; this.v_invIB; this.p_localPoints = []; this.p_localNormal = Vec2.zero(); this.p_localPoint = Vec2.zero(); this.p_localCenterA = Vec2.zero(); this.p_localCenterB = Vec2.zero(); this.p_type; this.p_radiusA; this.p_radiusB; this.p_pointCount; this.p_invMassA; this.p_invMassB; this.p_invIA; this.p_invIB; } Contact.prototype.initConstraint = function(step) { var fixtureA = this.m_fixtureA; var fixtureB = this.m_fixtureB; var shapeA = fixtureA.getShape(); var shapeB = fixtureB.getShape(); var bodyA = fixtureA.getBody(); var bodyB = fixtureB.getBody(); var manifold = this.getManifold(); var pointCount = manifold.pointCount; _ASSERT && common.assert(pointCount > 0); this.v_invMassA = bodyA.m_invMass; this.v_invMassB = bodyB.m_invMass; this.v_invIA = bodyA.m_invI; this.v_invIB = bodyB.m_invI; this.v_friction = this.m_friction; this.v_restitution = this.m_restitution; this.v_tangentSpeed = this.m_tangentSpeed; this.v_pointCount = pointCount; this.v_K.setZero(); this.v_normalMass.setZero(); this.p_invMassA = bodyA.m_invMass; this.p_invMassB = bodyB.m_invMass; this.p_invIA = bodyA.m_invI; this.p_invIB = bodyB.m_invI; this.p_localCenterA = Vec2.clone(bodyA.m_sweep.localCenter); this.p_localCenterB = Vec2.clone(bodyB.m_sweep.localCenter); this.p_radiusA = shapeA.m_radius; this.p_radiusB = shapeB.m_radius; this.p_type = manifold.type; this.p_localNormal = Vec2.clone(manifold.localNormal); this.p_localPoint = Vec2.clone(manifold.localPoint); this.p_pointCount = pointCount; for (var j = 0; j < pointCount; ++j) { var cp = manifold.points[j]; var vcp = this.v_points[j] = new VelocityConstraintPoint(); if (step.warmStarting) { vcp.normalImpulse = step.dtRatio * cp.normalImpulse; vcp.tangentImpulse = step.dtRatio * cp.tangentImpulse; } else { vcp.normalImpulse = 0; vcp.tangentImpulse = 0; } vcp.rA.setZero(); vcp.rB.setZero(); vcp.normalMass = 0; vcp.tangentMass = 0; vcp.velocityBias = 0; this.p_localPoints[j] = Vec2.clone(cp.localPoint); } }; Contact.prototype.getManifold = function() { return this.m_manifold; }; Contact.prototype.getWorldManifold = function(worldManifold) { var bodyA = this.m_fixtureA.getBody(); var bodyB = this.m_fixtureB.getBody(); var shapeA = this.m_fixtureA.getShape(); var shapeB = this.m_fixtureB.getShape(); return this.m_manifold.getWorldManifold(worldManifold, bodyA.getTransform(), shapeA.m_radius, bodyB.getTransform(), shapeB.m_radius); }; Contact.prototype.setEnabled = function(flag) { this.m_enabledFlag = !!flag; }; Contact.prototype.isEnabled = function() { return this.m_enabledFlag; }; Contact.prototype.isTouching = function() { return this.m_touchingFlag; }; Contact.prototype.getNext = function() { return this.m_next; }; Contact.prototype.getFixtureA = function() { return this.m_fixtureA; }; Contact.prototype.getFixtureB = function() { return this.m_fixtureB; }; Contact.prototype.getChildIndexA = function() { return this.m_indexA; }; Contact.prototype.getChildIndexB = function() { return this.m_indexB; }; Contact.prototype.flagForFiltering = function() { this.m_filterFlag = true; }; Contact.prototype.setFriction = function(friction) { this.m_friction = friction; }; Contact.prototype.getFriction = function() { return this.m_friction; }; Contact.prototype.resetFriction = function() { this.m_friction = mixFriction(this.m_fixtureA.m_friction, this.m_fixtureB.m_friction); }; Contact.prototype.setRestitution = function(restitution) { this.m_restitution = restitution; }; Contact.prototype.getRestitution = function() { return this.m_restitution; }; Contact.prototype.resetRestitution = function() { this.m_restitution = mixRestitution(this.m_fixtureA.m_restitution, this.m_fixtureB.m_restitution); }; Contact.prototype.setTangentSpeed = function(speed) { this.m_tangentSpeed = speed; }; Contact.prototype.getTangentSpeed = function() { return this.m_tangentSpeed; }; Contact.prototype.evaluate = function(manifold, xfA, xfB) { this.m_evaluateFcn(manifold, xfA, this.m_fixtureA, this.m_indexA, xfB, this.m_fixtureB, this.m_indexB); }; Contact.prototype.update = function(listener) { this.m_enabledFlag = true; var touching = false; var wasTouching = this.m_touchingFlag; var sensorA = this.m_fixtureA.isSensor(); var sensorB = this.m_fixtureB.isSensor(); var sensor = sensorA || sensorB; var bodyA = this.m_fixtureA.getBody(); var bodyB = this.m_fixtureB.getBody(); var xfA = bodyA.getTransform(); var xfB = bodyB.getTransform(); if (sensor) { var shapeA = this.m_fixtureA.getShape(); var shapeB = this.m_fixtureB.getShape(); touching = Distance.testOverlap(shapeA, this.m_indexA, shapeB, this.m_indexB, xfA, xfB); this.m_manifold.pointCount = 0; } else { var oldManifold = this.m_manifold; this.m_manifold = new Manifold(); this.evaluate(this.m_manifold, xfA, xfB); touching = this.m_manifold.pointCount > 0; for (var i = 0; i < this.m_manifold.pointCount; ++i) { var nmp = this.m_manifold.points[i]; nmp.normalImpulse = 0; nmp.tangentImpulse = 0; for (var j = 0; j < oldManifold.pointCount; ++j) { var omp = oldManifold.points[j]; if (omp.id.key == nmp.id.key) { nmp.normalImpulse = omp.normalImpulse; nmp.tangentImpulse = omp.tangentImpulse; break; } } } if (touching != wasTouching) { bodyA.setAwake(true); bodyB.setAwake(true); } } this.m_touchingFlag = touching; if (wasTouching == false && touching == true && listener) { listener.beginContact(this); } if (wasTouching == true && touching == false && listener) { listener.endContact(this); } if (sensor == false && touching && listener) { listener.preSolve(this, oldManifold); } }; Contact.prototype.solvePositionConstraint = function(step) { return this._solvePositionConstraint(step, false); }; Contact.prototype.solvePositionConstraintTOI = function(step, toiA, toiB) { return this._solvePositionConstraint(step, true, toiA, toiB); }; Contact.prototype._solvePositionConstraint = function(step, toi, toiA, toiB) { var fixtureA = this.m_fixtureA; var fixtureB = this.m_fixtureB; var bodyA = fixtureA.getBody(); var bodyB = fixtureB.getBody(); var velocityA = bodyA.c_velocity; var velocityB = bodyB.c_velocity; var positionA = bodyA.c_position; var positionB = bodyB.c_position; var localCenterA = Vec2.clone(this.p_localCenterA); var localCenterB = Vec2.clone(this.p_localCenterB); var mA = 0; var iA = 0; if (!toi || (bodyA == toiA || bodyA == toiB)) { mA = this.p_invMassA; iA = this.p_invIA; } var mB = 0; var iB = 0; if (!toi || (bodyB == toiA || bodyB == toiB)) { mB = this.p_invMassB; iB = this.p_invIB; } var cA = Vec2.clone(positionA.c); var aA = positionA.a; var cB = Vec2.clone(positionB.c); var aB = positionB.a; var minSeparation = 0; for (var j = 0; j < this.p_pointCount; ++j) { var xfA = Transform.identity(); var xfB = Transform.identity(); xfA.q.set(aA); xfB.q.set(aB); xfA.p = Vec2.sub(cA, Rot.mul(xfA.q, localCenterA)); xfB.p = Vec2.sub(cB, Rot.mul(xfB.q, localCenterB)); var normal, point, separation; switch (this.p_type) { case Manifold.e_circles: var pointA = Transform.mul(xfA, this.p_localPoint); var pointB = Transform.mul(xfB, this.p_localPoints[0]); normal = Vec2.sub(pointB, pointA); normal.normalize(); point = Vec2.combine(.5, pointA, .5, pointB); separation = Vec2.dot(Vec2.sub(pointB, pointA), normal) - this.p_radiusA - this.p_radiusB; break; case Manifold.e_faceA: normal = Rot.mul(xfA.q, this.p_localNormal); var planePoint = Transform.mul(xfA, this.p_localPoint); var clipPoint = Transform.mul(xfB, this.p_localPoints[j]); separation = Vec2.dot(Vec2.sub(clipPoint, planePoint), normal) - this.p_radiusA - this.p_radiusB; point = clipPoint; break; case Manifold.e_faceB: normal = Rot.mul(xfB.q, this.p_localNormal); var planePoint = Transform.mul(xfB, this.p_localPoint); var clipPoint = Transform.mul(xfA, this.p_localPoints[j]); separation = Vec2.dot(Vec2.sub(clipPoint, planePoint), normal) - this.p_radiusA - this.p_radiusB; point = clipPoint; normal.mul(-1); break; } var rA = Vec2.sub(point, cA); var rB = Vec2.sub(point, cB); minSeparation = Math.min(minSeparation, separation); var baumgarte = toi ? Settings.toiBaugarte : Settings.baumgarte; var linearSlop = Settings.linearSlop; var maxLinearCorrection = Settings.maxLinearCorrection; var C = Math.clamp(baumgarte * (separation + linearSlop), -maxLinearCorrection, 0); var rnA = Vec2.cross(rA, normal); var rnB = Vec2.cross(rB, normal); var K = mA + mB + iA * rnA * rnA + iB * rnB * rnB; var impulse = K > 0 ? -C / K : 0; var P = Vec2.mul(impulse, normal); cA.subMul(mA, P); aA -= iA * Vec2.cross(rA, P); cB.addMul(mB, P); aB += iB * Vec2.cross(rB, P); } positionA.c.set(cA); positionA.a = aA; positionB.c.set(cB); positionB.a = aB; return minSeparation; }; function VelocityConstraintPoint() { this.rA = Vec2.zero(); this.rB = Vec2.zero(); this.normalImpulse = 0; this.tangentImpulse = 0; this.normalMass = 0; this.tangentMass = 0; this.velocityBias = 0; } Contact.prototype.initVelocityConstraint = function(step) { var fixtureA = this.m_fixtureA; var fixtureB = this.m_fixtureB; var bodyA = fixtureA.getBody(); var bodyB = fixtureB.getBody(); var velocityA = bodyA.c_velocity; var velocityB = bodyB.c_velocity; var positionA = bodyA.c_position; var positionB = bodyB.c_position; var radiusA = this.p_radiusA; var radiusB = this.p_radiusB; var manifold = this.getManifold(); var mA = this.v_invMassA; var mB = this.v_invMassB; var iA = this.v_invIA; var iB = this.v_invIB; var localCenterA = Vec2.clone(this.p_localCenterA); var localCenterB = Vec2.clone(this.p_localCenterB); var cA = Vec2.clone(positionA.c); var aA = positionA.a; var vA = Vec2.clone(velocityA.v); var wA = velocityA.w; var cB = Vec2.clone(positionB.c); var aB = positionB.a; var vB = Vec2.clone(velocityB.v); var wB = velocityB.w; _ASSERT && common.assert(manifold.pointCount > 0); var xfA = Transform.identity(); var xfB = Transform.identity(); xfA.q.set(aA); xfB.q.set(aB); xfA.p.setCombine(1, cA, -1, Rot.mul(xfA.q, localCenterA)); xfB.p.setCombine(1, cB, -1, Rot.mul(xfB.q, localCenterB)); var worldManifold = manifold.getWorldManifold(null, xfA, radiusA, xfB, radiusB); this.v_normal.set(worldManifold.normal); for (var j = 0; j < this.v_pointCount; ++j) { var vcp = this.v_points[j]; vcp.rA.set(Vec2.sub(worldManifold.points[j], cA)); vcp.rB.set(Vec2.sub(worldManifold.points[j], cB)); var rnA = Vec2.cross(vcp.rA, this.v_normal); var rnB = Vec2.cross(vcp.rB, this.v_normal); var kNormal = mA + mB + iA * rnA * rnA + iB * rnB * rnB; vcp.normalMass = kNormal > 0 ? 1 / kNormal : 0; var tangent = Vec2.cross(this.v_normal, 1); var rtA = Vec2.cross(vcp.rA, tangent); var rtB = Vec2.cross(vcp.rB, tangent); var kTangent = mA + mB + iA * rtA * rtA + iB * rtB * rtB; vcp.tangentMass = kTangent > 0 ? 1 / kTangent : 0; vcp.velocityBias = 0; var vRel = Vec2.dot(this.v_normal, vB) + Vec2.dot(this.v_normal, Vec2.cross(wB, vcp.rB)) - Vec2.dot(this.v_normal, vA) - Vec2.dot(this.v_normal, Vec2.cross(wA, vcp.rA)); if (vRel < -Settings.velocityThreshold) { vcp.velocityBias = -this.v_restitution * vRel; } } if (this.v_pointCount == 2 && step.blockSolve) { var vcp1 = this.v_points[0]; var vcp2 = this.v_points[1]; var rn1A = Vec2.cross(vcp1.rA, this.v_normal); var rn1B = Vec2.cross(vcp1.rB, this.v_normal); var rn2A = Vec2.cross(vcp2.rA, this.v_normal); var rn2B = Vec2.cross(vcp2.rB, this.v_normal); var k11 = mA + mB + iA * rn1A * rn1A + iB * rn1B * rn1B; var k22 = mA + mB + iA * rn2A * rn2A + iB * rn2B * rn2B; var k12 = mA + mB + iA * rn1A * rn2A + iB * rn1B * rn2B; var k_maxConditionNumber = 1e3; if (k11 * k11 < k_maxConditionNumber * (k11 * k22 - k12 * k12)) { this.v_K.ex.set(k11, k12); this.v_K.ey.set(k12, k22); this.v_normalMass.set(this.v_K.getInverse()); } else { this.v_pointCount = 1; } } positionA.c.set(cA); positionA.a = aA; velocityA.v.set(vA); velocityA.w = wA; positionB.c.set(cB); positionB.a = aB; velocityB.v.set(vB); velocityB.w = wB; }; Contact.prototype.warmStartConstraint = function(step) { var fixtureA = this.m_fixtureA; var fixtureB = this.m_fixtureB; var bodyA = fixtureA.getBody(); var bodyB = fixtureB.getBody(); var velocityA = bodyA.c_velocity; var velocityB = bodyB.c_velocity; var positionA = bodyA.c_position; var positionB = bodyB.c_position; var mA = this.v_invMassA; var iA = this.v_invIA; var mB = this.v_invMassB; var iB = this.v_invIB; var vA = Vec2.clone(velocityA.v); var wA = velocityA.w; var vB = Vec2.clone(velocityB.v); var wB = velocityB.w; var normal = this.v_normal; var tangent = Vec2.cross(normal, 1); for (var j = 0; j < this.v_pointCount; ++j) { var vcp = this.v_points[j]; var P = Vec2.combine(vcp.normalImpulse, normal, vcp.tangentImpulse, tangent); wA -= iA * Vec2.cross(vcp.rA, P); vA.subMul(mA, P); wB += iB * Vec2.cross(vcp.rB, P); vB.addMul(mB, P); } velocityA.v.set(vA); velocityA.w = wA; velocityB.v.set(vB); velocityB.w = wB; }; Contact.prototype.storeConstraintImpulses = function(step) { var manifold = this.m_manifold; for (var j = 0; j < this.v_pointCount; ++j) { manifold.points[j].normalImpulse = this.v_points[j].normalImpulse; manifold.points[j].tangentImpulse = this.v_points[j].tangentImpulse; } }; Contact.prototype.solveVelocityConstraint = function(step) { var bodyA = this.m_fixtureA.m_body; var bodyB = this.m_fixtureB.m_body; var velocityA = bodyA.c_velocity; var positionA = bodyA.c_position; var velocityB = bodyB.c_velocity; var positionB = bodyB.c_position; var mA = this.v_invMassA; var iA = this.v_invIA; var mB = this.v_invMassB; var iB = this.v_invIB; var vA = Vec2.clone(velocityA.v); var wA = velocityA.w; var vB = Vec2.clone(velocityB.v); var wB = velocityB.w; var normal = this.v_normal; var tangent = Vec2.cross(normal, 1); var friction = this.v_friction; _ASSERT && common.assert(this.v_pointCount == 1 || this.v_pointCount == 2); for (var j = 0; j < this.v_pointCount; ++j) { var vcp = this.v_points[j]; var dv = Vec2.zero(); dv.addCombine(1, vB, 1, Vec2.cross(wB, vcp.rB)); dv.subCombine(1, vA, 1, Vec2.cross(wA, vcp.rA)); var vt = Vec2.dot(dv, tangent) - this.v_tangentSpeed; var lambda = vcp.tangentMass * -vt; var maxFriction = friction * vcp.normalImpulse; var newImpulse = Math.clamp(vcp.tangentImpulse + lambda, -maxFriction, maxFriction); lambda = newImpulse - vcp.tangentImpulse; vcp.tangentImpulse = newImpulse; var P = Vec2.mul(lambda, tangent); vA.subMul(mA, P); wA -= iA * Vec2.cross(vcp.rA, P); vB.addMul(mB, P); wB += iB * Vec2.cross(vcp.rB, P); } if (this.v_pointCount == 1 || step.blockSolve == false) { for (var i = 0; i < this.v_pointCount; ++i) { var vcp = this.v_points[i]; var dv = Vec2.zero(); dv.addCombine(1, vB, 1, Vec2.cross(wB, vcp.rB)); dv.subCombine(1, vA, 1, Vec2.cross(wA, vcp.rA)); var vn = Vec2.dot(dv, normal); var lambda = -vcp.normalMass * (vn - vcp.velocityBias); var newImpulse = Math.max(vcp.normalImpulse + lambda, 0); lambda = newImpulse - vcp.normalImpulse; vcp.normalImpulse = newImpulse; var P = Vec2.mul(lambda, normal); vA.subMul(mA, P); wA -= iA * Vec2.cross(vcp.rA, P); vB.addMul(mB, P); wB += iB * Vec2.cross(vcp.rB, P); } } else { var vcp1 = this.v_points[0]; var vcp2 = this.v_points[1]; var a = Vec2.neo(vcp1.normalImpulse, vcp2.normalImpulse); _ASSERT && common.assert(a.x >= 0 && a.y >= 0); var dv1 = Vec2.zero().add(vB).add(Vec2.cross(wB, vcp1.rB)).sub(vA).sub(Vec2.cross(wA, vcp1.rA)); var dv2 = Vec2.zero().add(vB).add(Vec2.cross(wB, vcp2.rB)).sub(vA).sub(Vec2.cross(wA, vcp2.rA)); var vn1 = Vec2.dot(dv1, normal); var vn2 = Vec2.dot(dv2, normal); var b = Vec2.neo(vn1 - vcp1.velocityBias, vn2 - vcp2.velocityBias); b.sub(Mat22.mul(this.v_K, a)); var k_errorTol = .001; for (;;) { var x = Vec2.neg(Mat22.mul(this.v_normalMass, b)); if (x.x >= 0 && x.y >= 0) { var d = Vec2.sub(x, a); var P1 = Vec2.mul(d.x, normal); var P2 = Vec2.mul(d.y, normal); vA.subCombine(mA, P1, mA, P2); wA -= iA * (Vec2.cross(vcp1.rA, P1) + Vec2.cross(vcp2.rA, P2)); vB.addCombine(mB, P1, mB, P2); wB += iB * (Vec2.cross(vcp1.rB, P1) + Vec2.cross(vcp2.rB, P2)); vcp1.normalImpulse = x.x; vcp2.normalImpulse = x.y; if (DEBUG_SOLVER) { dv1 = vB + Vec2.cross(wB, vcp1.rB) - vA - Vec2.cross(wA, vcp1.rA); dv2 = vB + Vec2.cross(wB, vcp2.rB) - vA - Vec2.cross(wA, vcp2.rA); vn1 = Dot(dv1, normal); vn2 = Dot(dv2, normal); _ASSERT && common.assert(Abs(vn1 - vcp1.velocityBias) < k_errorTol); _ASSERT && common.assert(Abs(vn2 - vcp2.velocityBias) < k_errorTol); } break; } x.x = -vcp1.normalMass * b.x; x.y = 0; vn1 = 0; vn2 = this.v_K.ex.y * x.x + b.y; if (x.x >= 0 && vn2 >= 0) { var d = Vec2.sub(x, a); var P1 = Vec2.mul(d.x, normal); var P2 = Vec2.mul(d.y, normal); vA.subCombine(mA, P1, mA, P2); wA -= iA * (Vec2.cross(vcp1.rA, P1) + Vec2.cross(vcp2.rA, P2)); vB.addCombine(mB, P1, mB, P2); wB += iB * (Vec2.cross(vcp1.rB, P1) + Vec2.cross(vcp2.rB, P2)); vcp1.normalImpulse = x.x; vcp2.normalImpulse = x.y; if (DEBUG_SOLVER) { var dv1B = Vec2.add(vB, Vec2.cross(wB, vcp1.rB)); var dv1A = Vec2.add(vA, Vec2.cross(wA, vcp1.rA)); var dv1 = Vec2.sub(dv1B, dv1A); vn1 = Vec2.dot(dv1, normal); _ASSERT && common.assert(Math.abs(vn1 - vcp1.velocityBias) < k_errorTol); } break; } x.x = 0; x.y = -vcp2.normalMass * b.y; vn1 = this.v_K.ey.x * x.y + b.x; vn2 = 0; if (x.y >= 0 && vn1 >= 0) { var d = Vec2.sub(x, a); var P1 = Vec2.mul(d.x, normal); var P2 = Vec2.mul(d.y, normal); vA.subCombine(mA, P1, mA, P2); wA -= iA * (Vec2.cross(vcp1.rA, P1) + Vec2.cross(vcp2.rA, P2)); vB.addCombine(mB, P1, mB, P2); wB += iB * (Vec2.cross(vcp1.rB, P1) + Vec2.cross(vcp2.rB, P2)); vcp1.normalImpulse = x.x; vcp2.normalImpulse = x.y; if (DEBUG_SOLVER) { var dv2B = Vec2.add(vB, Vec2.cross(wB, vcp2.rB)); var dv2A = Vec2.add(vA, Vec2.cross(wA, vcp2.rA)); var dv1 = Vec2.sub(dv2B, dv2A); vn2 = Vec2.dot(dv2, normal); _ASSERT && common.assert(Math.abs(vn2 - vcp2.velocityBias) < k_errorTol); } break; } x.x = 0; x.y = 0; vn1 = b.x; vn2 = b.y; if (vn1 >= 0 && vn2 >= 0) { var d = Vec2.sub(x, a); var P1 = Vec2.mul(d.x, normal); var P2 = Vec2.mul(d.y, normal); vA.subCombine(mA, P1, mA, P2); wA -= iA * (Vec2.cross(vcp1.rA, P1) + Vec2.cross(vcp2.rA, P2)); vB.addCombine(mB, P1, mB, P2); wB += iB * (Vec2.cross(vcp1.rB, P1) + Vec2.cross(vcp2.rB, P2)); vcp1.normalImpulse = x.x; vcp2.normalImpulse = x.y; break; } break; } } velocityA.v.set(vA); velocityA.w = wA; velocityB.v.set(vB); velocityB.w = wB; }; function mixFriction(friction1, friction2) { return Math.sqrt(friction1 * friction2); } function mixRestitution(restitution1, restitution2) { return restitution1 > restitution2 ? restitution1 : restitution2; } var s_registers = []; Contact.addType = function(type1, type2, callback) { s_registers[type1] = s_registers[type1] || {}; s_registers[type1][type2] = callback; }; Contact.create = function(fixtureA, indexA, fixtureB, indexB) { var typeA = fixtureA.getType(); var typeB = fixtureB.getType(); var contact, evaluateFcn; if (evaluateFcn = s_registers[typeA] && s_registers[typeA][typeB]) { contact = new Contact(fixtureA, indexA, fixtureB, indexB, evaluateFcn); } else if (evaluateFcn = s_registers[typeB] && s_registers[typeB][typeA]) { contact = new Contact(fixtureB, indexB, fixtureA, indexA, evaluateFcn); } else { return null; } fixtureA = contact.getFixtureA(); fixtureB = contact.getFixtureB(); indexA = contact.getChildIndexA(); indexB = contact.getChildIndexB(); var bodyA = fixtureA.getBody(); var bodyB = fixtureB.getBody(); contact.m_nodeA.contact = contact; contact.m_nodeA.other = bodyB; contact.m_nodeA.prev = null; contact.m_nodeA.next = bodyA.m_contactList; if (bodyA.m_contactList != null) { bodyA.m_contactList.prev = contact.m_nodeA; } bodyA.m_contactList = contact.m_nodeA; contact.m_nodeB.contact = contact; contact.m_nodeB.other = bodyA; contact.m_nodeB.prev = null; contact.m_nodeB.next = bodyB.m_contactList; if (bodyB.m_contactList != null) { bodyB.m_contactList.prev = contact.m_nodeB; } bodyB.m_contactList = contact.m_nodeB; if (fixtureA.isSensor() == false && fixtureB.isSensor() == false) { bodyA.setAwake(true); bodyB.setAwake(true); } return contact; }; Contact.destroy = function(contact, listener) { var fixtureA = contact.m_fixtureA; var fixtureB = contact.m_fixtureB; var bodyA = fixtureA.getBody(); var bodyB = fixtureB.getBody(); if (contact.isTouching()) { listener.endContact(contact); } if (contact.m_nodeA.prev) { contact.m_nodeA.prev.next = contact.m_nodeA.next; } if (contact.m_nodeA.next) { contact.m_nodeA.next.prev = contact.m_nodeA.prev; } if (contact.m_nodeA == bodyA.m_contactList) { bodyA.m_contactList = contact.m_nodeA.next; } if (contact.m_nodeB.prev) { contact.m_nodeB.prev.next = contact.m_nodeB.next; } if (contact.m_nodeB.next) { contact.m_nodeB.next.prev = contact.m_nodeB.prev; } if (contact.m_nodeB == bodyB.m_contactList) { bodyB.m_contactList = contact.m_nodeB.next; } if (contact.m_manifold.pointCount > 0 && fixtureA.isSensor() == false && fixtureB.isSensor() == false) { bodyA.setAwake(true); bodyB.setAwake(true); } var typeA = fixtureA.getType(); var typeB = fixtureB.getType(); var destroyFcn = s_registers[typeA][typeB].destroyFcn; if (typeof destroyFcn === "function") { destroyFcn(contact); } }; },{"./Manifold":6,"./Settings":7,"./collision/Distance":13,"./common/Mat22":16,"./common/Math":18,"./common/Rot":20,"./common/Transform":22,"./common/Vec2":23,"./util/common":51}],4:[function(require,module,exports){ var _DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; var _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = Fixture; var common = require("./util/common"); var options = require("./util/options"); var Math = require("./common/Math"); var Vec2 = require("./common/Vec2"); var AABB = require("./collision/AABB"); var FixtureDef = { userData: null, friction: .2, restitution: 0, density: 0, isSensor: false, filterGroupIndex: 0, filterCategoryBits: 1, filterMaskBits: 65535 }; function FixtureProxy(fixture, childIndex) { this.aabb = new AABB(); this.fixture = fixture; this.childIndex = childIndex; this.proxyId; } function Fixture(body, shape, def) { if (shape.shape) { def = shape; shape = shape.shape; } else if (typeof def === "number") { def = { density: def }; } def = options(def, FixtureDef); this.m_body = body; this.m_friction = def.friction; this.m_restitution = def.restitution; this.m_density = def.density; this.m_isSensor = def.isSensor; this.m_filterGroupIndex = def.filterGroupIndex; this.m_filterCategoryBits = def.filterCategoryBits; this.m_filterMaskBits = def.filterMaskBits; this.m_shape = shape; this.m_next = null; this.m_proxies = []; this.m_proxyCount = 0; var childCount = this.m_shape.getChildCount(); for (var i = 0; i < childCount; ++i) { this.m_proxies[i] = new FixtureProxy(this, i); } this.m_userData = def.userData; } Fixture.prototype.getType = function() { return this.m_shape.getType(); }; Fixture.prototype.getShape = function() { return this.m_shape; }; Fixture.prototype.isSensor = function() { return this.m_isSensor; }; Fixture.prototype.setSensor = function(sensor) { if (sensor != this.m_isSensor) { this.m_body.setAwake(true); this.m_isSensor = sensor; } }; Fixture.prototype.getUserData = function() { return this.m_userData; }; Fixture.prototype.setUserData = function(data) { this.m_userData = data; }; Fixture.prototype.getBody = function() { return this.m_body; }; Fixture.prototype.getNext = function() { return this.m_next; }; Fixture.prototype.getDensity = function() { return this.m_density; }; Fixture.prototype.setDensity = function(density) { _ASSERT && common.assert(Math.isFinite(density) && density >= 0); this.m_density = density; }; Fixture.prototype.getFriction = function() { return this.m_friction; }; Fixture.prototype.setFriction = function(friction) { this.m_friction = friction; }; Fixture.prototype.getRestitution = function() { return this.m_restitution; }; Fixture.prototype.setRestitution = function(restitution) { this.m_restitution = restitution; }; Fixture.prototype.testPoint = function(p) { return this.m_shape.testPoint(this.m_body.getTransform(), p); }; Fixture.prototype.rayCast = function(output, input, childIndex) { return this.m_shape.rayCast(output, input, this.m_body.getTransform(), childIndex); }; Fixture.prototype.getMassData = function(massData) { this.m_shape.computeMass(massData, this.m_density); }; Fixture.prototype.getAABB = function(childIndex) { _ASSERT && common.assert(0 <= childIndex && childIndex < this.m_proxyCount); return this.m_proxies[childIndex].aabb; }; Fixture.prototype.createProxies = function(broadPhase, xf) { _ASSERT && common.assert(this.m_proxyCount == 0); this.m_proxyCount = this.m_shape.getChildCount(); for (var i = 0; i < this.m_proxyCount; ++i) { var proxy = this.m_proxies[i]; this.m_shape.computeAABB(proxy.aabb, xf, i); proxy.proxyId = broadPhase.createProxy(proxy.aabb, proxy); } }; Fixture.prototype.destroyProxies = function(broadPhase) { for (var i = 0; i < this.m_proxyCount; ++i) { var proxy = this.m_proxies[i]; broadPhase.destroyProxy(proxy.proxyId); proxy.proxyId = null; } this.m_proxyCount = 0; }; Fixture.prototype.synchronize = function(broadPhase, xf1, xf2) { for (var i = 0; i < this.m_proxyCount; ++i) { var proxy = this.m_proxies[i]; var aabb1 = new AABB(); var aabb2 = new AABB(); this.m_shape.computeAABB(aabb1, xf1, proxy.childIndex); this.m_shape.computeAABB(aabb2, xf2, proxy.childIndex); proxy.aabb.combine(aabb1, aabb2); var displacement = Vec2.sub(xf2.p, xf1.p); broadPhase.moveProxy(proxy.proxyId, proxy.aabb, displacement); } }; Fixture.prototype.setFilterData = function(filter) { this.m_filterGroupIndex = filter.groupIndex; this.m_filterCategoryBits = filter.categoryBits; this.m_filterMaskBits = filter.maskBits; this.refilter(); }; Fixture.prototype.getFilterGroupIndex = function() { return this.m_filterGroupIndex; }; Fixture.prototype.getFilterCategoryBits = function() { return this.m_filterCategoryBits; }; Fixture.prototype.getFilterMaskBits = function() { return this.m_filterMaskBits; }; Fixture.prototype.refilter = function() { if (this.m_body == null) { return; } var edge = this.m_body.getContactList(); while (edge) { var contact = edge.contact; var fixtureA = contact.getFixtureA(); var fixtureB = contact.getFixtureB(); if (fixtureA == this || fixtureB == this) { contact.flagForFiltering(); } edge = edge.next; } var world = this.m_body.getWorld(); if (world == null) { return; } var broadPhase = world.m_broadPhase; for (var i = 0; i < this.m_proxyCount; ++i) { broadPhase.touchProxy(this.m_proxies[i].proxyId); } }; Fixture.prototype.shouldCollide = function(that) { if (that.m_filterGroupIndex == this.m_filterGroupIndex && that.m_filterGroupIndex != 0) { return that.m_filterGroupIndex > 0; } var collide = (that.m_filterMaskBits & this.m_filterCategoryBits) != 0 && (that.m_filterCategoryBits & this.m_filterMaskBits) != 0; return collide; }; },{"./collision/AABB":11,"./common/Math":18,"./common/Vec2":23,"./util/common":51,"./util/options":53}],5:[function(require,module,exports){ var _DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; var _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = Joint; var common = require("./util/common"); function JointEdge() { this.other = null; this.joint = null; this.prev = null; this.next = null; } var JointDef = { userData: null, collideConnected: false }; function Joint(def, bodyA, bodyB) { bodyA = def.bodyA || bodyA; bodyB = def.bodyB || bodyB; _ASSERT && common.assert(bodyA); _ASSERT && common.assert(bodyB); _ASSERT && common.assert(bodyA != bodyB); this.m_type = "unknown-joint"; this.m_bodyA = bodyA; this.m_bodyB = bodyB; this.m_index = 0; this.m_collideConnected = !!def.collideConnected; this.m_prev = null; this.m_next = null; this.m_edgeA = new JointEdge(); this.m_edgeB = new JointEdge(); this.m_islandFlag = false; this.m_userData = def.userData; } Joint.prototype.isActive = function() { return this.m_bodyA.isActive() && this.m_bodyB.isActive(); }; Joint.prototype.getType = function() { return this.m_type; }; Joint.prototype.getBodyA = function() { return this.m_bodyA; }; Joint.prototype.getBodyB = function() { return this.m_bodyB; }; Joint.prototype.getNext = function() { return this.m_next; }; Joint.prototype.getUserData = function() { return this.m_userData; }; Joint.prototype.setUserData = function(data) { this.m_userData = data; }; Joint.prototype.getCollideConnected = function() { return this.m_collideConnected; }; Joint.prototype.getAnchorA = function() {}; Joint.prototype.getAnchorB = function() {}; Joint.prototype.getReactionForce = function(inv_dt) {}; Joint.prototype.getReactionTorque = function(inv_dt) {}; Joint.prototype.shiftOrigin = function(newOrigin) {}; Joint.prototype.initVelocityConstraints = function(step) {}; Joint.prototype.solveVelocityConstraints = function(step) {}; Joint.prototype.solvePositionConstraints = function(step) {}; },{"./util/common":51}],6:[function(require,module,exports){ var _DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; var _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; var common = require("./util/common"); var Vec2 = require("./common/Vec2"); var Transform = require("./common/Transform"); var Math = require("./common/Math"); var Rot = require("./common/Rot"); module.exports = Manifold; module.exports.clipSegmentToLine = clipSegmentToLine; module.exports.clipVertex = ClipVertex; module.exports.getPointStates = getPointStates; module.exports.PointState = PointState; Manifold.e_circles = 0; Manifold.e_faceA = 1; Manifold.e_faceB = 2; Manifold.e_vertex = 0; Manifold.e_face = 1; function Manifold() { this.type; this.localNormal = Vec2.zero(); this.localPoint = Vec2.zero(); this.points = [ new ManifoldPoint(), new ManifoldPoint() ]; this.pointCount = 0; } function ManifoldPoint() { this.localPoint = Vec2.zero(); this.normalImpulse = 0; this.tangentImpulse = 0; this.id = new ContactID(); } function ContactID() { this.cf = new ContactFeature(); var key = ""; Object.defineProperty(this, "key", { get: function() { return this.cf.indexA + this.cf.indexB * 4 + this.cf.typeA * 16 + this.cf.typeB * 64; }, enumerable: true, configurable: true }); } ContactID.prototype.set = function(o) { this.cf.set(o.cf); }; function ContactFeature() { this.indexA; this.indexB; this.typeA; this.typeB; } ContactFeature.prototype.set = function(o) { this.indexA = o.indexA; this.indexB = o.indexB; this.typeA = o.typeA; this.typeB = o.typeB; }; function WorldManifold() { this.normal; this.points = []; this.separations = []; } Manifold.prototype.getWorldManifold = function(wm, xfA, radiusA, xfB, radiusB) { if (this.pointCount == 0) { return; } wm = wm || new WorldManifold(); var normal = wm.normal; var points = wm.points; var separations = wm.separations; switch (this.type) { case Manifold.e_circles: normal = Vec2.neo(1, 0); var pointA = Transform.mul(xfA, this.localPoint); var pointB = Transform.mul(xfB, this.points[0].localPoint); var dist = Vec2.sub(pointB, pointA); if (Vec2.lengthSquared(dist) > Math.EPSILON * Math.EPSILON) { normal.set(dist); normal.normalize(); } points[0] = Vec2.mid(pointA, pointB); separations[0] = -radiusB - radiusA; points.length = 1; separations.length = 1; break; case Manifold.e_faceA: normal = Rot.mul(xfA.q, this.localNormal); var planePoint = Transform.mul(xfA, this.localPoint); for (var i = 0; i < this.pointCount; ++i) { var clipPoint = Transform.mul(xfB, this.points[i].localPoint); var cA = Vec2.clone(clipPoint).addMul(radiusA - Vec2.dot(Vec2.sub(clipPoint, planePoint), normal), normal); var cB = Vec2.clone(clipPoint).subMul(radiusB, normal); points[i] = Vec2.mid(cA, cB); separations[i] = Vec2.dot(Vec2.sub(cB, cA), normal); } points.length = this.pointCount; separations.length = this.pointCount; break; case Manifold.e_faceB: normal = Rot.mul(xfB.q, this.localNormal); var planePoint = Transform.mul(xfB, this.localPoint); for (var i = 0; i < this.pointCount; ++i) { var clipPoint = Transform.mul(xfA, this.points[i].localPoint); var cB = Vec2.combine(1, clipPoint, radiusB - Vec2.dot(Vec2.sub(clipPoint, planePoint), normal), normal); var cA = Vec2.combine(1, clipPoint, -radiusA, normal); points[i] = Vec2.mid(cA, cB); separations[i] = Vec2.dot(Vec2.sub(cA, cB), normal); } points.length = this.pointCount; separations.length = this.pointCount; normal.mul(-1); break; } wm.normal = normal; wm.points = points; wm.separations = separations; return wm; }; var PointState = { nullState: 0, addState: 1, persistState: 2, removeState: 3 }; function getPointStates(state1, state2, manifold1, manifold2) { for (var i = 0; i < manifold1.pointCount; ++i) { var id = manifold1.points[i].id; state1[i] = PointState.removeState; for (var j = 0; j < manifold2.pointCount; ++j) { if (manifold2.points[j].id.key == id.key) { state1[i] = PointState.persistState; break; } } } for (var i = 0; i < manifold2.pointCount; ++i) { var id = manifold2.points[i].id; state2[i] = PointState.addState; for (var j = 0; j < manifold1.pointCount; ++j) { if (manifold1.points[j].id.key == id.key) { state2[i] = PointState.persistState; break; } } } } function ClipVertex() { this.v = Vec2.zero(); this.id = new ContactID(); } ClipVertex.prototype.set = function(o) { this.v.set(o.v); this.id.set(o.id); }; function clipSegmentToLine(vOut, vIn, normal, offset, vertexIndexA) { var numOut = 0; var distance0 = Vec2.dot(normal, vIn[0].v) - offset; var distance1 = Vec2.dot(normal, vIn[1].v) - offset; if (distance0 <= 0) vOut[numOut++].set(vIn[0]); if (distance1 <= 0) vOut[numOut++].set(vIn[1]); if (distance0 * distance1 < 0) { var interp = distance0 / (distance0 - distance1); vOut[numOut].v.setCombine(1 - interp, vIn[0].v, interp, vIn[1].v); vOut[numOut].id.cf.indexA = vertexIndexA; vOut[numOut].id.cf.indexB = vIn[0].id.cf.indexB; vOut[numOut].id.cf.typeA = Manifold.e_vertex; vOut[numOut].id.cf.typeB = Manifold.e_face; ++numOut; } return numOut; } },{"./common/Math":18,"./common/Rot":20,"./common/Transform":22,"./common/Vec2":23,"./util/common":51}],7:[function(require,module,exports){ var _DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; var _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; var Settings = exports; Settings.maxManifoldPoints = 2; Settings.maxPolygonVertices = 12; Settings.aabbExtension = .1; Settings.aabbMultiplier = 2; Settings.linearSlop = .005; Settings.linearSlopSquared = Settings.linearSlop * Settings.linearSlop; Settings.angularSlop = 2 / 180 * Math.PI; Settings.polygonRadius = 2 * Settings.linearSlop; Settings.maxSubSteps = 8; Settings.maxTOIContacts = 32; Settings.maxTOIIterations = 20; Settings.maxDistnceIterations = 20; Settings.velocityThreshold = 1; Settings.maxLinearCorrection = .2; Settings.maxAngularCorrection = 8 / 180 * Math.PI; Settings.maxTranslation = 2; Settings.maxTranslationSquared = Settings.maxTranslation * Settings.maxTranslation; Settings.maxRotation = .5 * Math.PI; Settings.maxRotationSquared = Settings.maxRotation * Settings.maxRotation; Settings.baumgarte = .2; Settings.toiBaugarte = .75; Settings.timeToSleep = .5; Settings.linearSleepTolerance = .01; Settings.linearSleepToleranceSqr = Math.pow(Settings.linearSleepTolerance, 2); Settings.angularSleepTolerance = 2 / 180 * Math.PI; Settings.angularSleepToleranceSqr = Math.pow(Settings.angularSleepTolerance, 2); },{}],8:[function(require,module,exports){ var _DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; var _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = Shape; var Math = require("./common/Math"); function Shape() { this.m_type; this.m_radius; } Shape.isValid = function(shape) { return !!shape; }; Shape.prototype.getRadius = function() { return this.m_radius; }; Shape.prototype.getType = function() { return this.m_type; }; Shape.prototype._clone = function() {}; Shape.prototype.getChildCount = function() {}; Shape.prototype.testPoint = function(xf, p) {}; Shape.prototype.rayCast = function(output, input, transform, childIndex) {}; Shape.prototype.computeAABB = function(aabb, xf, childIndex) {}; Shape.prototype.computeMass = function(massData, density) {}; Shape.prototype.computeDistanceProxy = function(proxy) {}; },{"./common/Math":18}],9:[function(require,module,exports){ var _DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; var _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = Solver; module.exports.TimeStep = TimeStep; var Settings = require("./Settings"); var common = require("./util/common"); var Vec2 = require("./common/Vec2"); var Math = require("./common/Math"); var Body = require("./Body"); var Contact = require("./Contact"); var Joint = require("./Joint"); var TimeOfImpact = require("./collision/TimeOfImpact"); var TOIInput = TimeOfImpact.Input; var TOIOutput = TimeOfImpact.Output; var Distance = require("./collision/Distance"); var DistanceInput = Distance.Input; var DistanceOutput = Distance.Output; var DistanceProxy = Distance.Proxy; var SimplexCache = Distance.Cache; function TimeStep(dt) { this.dt = 0; this.inv_dt = 0; this.velocityIterations = 0; this.positionIterations = 0; this.warmStarting = false; this.blockSolve = true; this.inv_dt0 = 0; this.dtRatio = 1; } TimeStep.prototype.reset = function(dt) { if (this.dt > 0) { this.inv_dt0 = this.inv_dt; } this.dt = dt; this.inv_dt = dt == 0 ? 0 : 1 / dt; this.dtRatio = dt * this.inv_dt0; }; function Solver(world) { this.m_world = world; this.m_stack = []; this.m_bodies = []; this.m_contacts = []; this.m_joints = []; } Solver.prototype.clear = function() { this.m_stack.length = 0; this.m_bodies.length = 0; this.m_contacts.length = 0; this.m_joints.length = 0; }; Solver.prototype.addBody = function(body) { _ASSERT && common.assert(body instanceof Body, "Not a Body!", body); this.m_bodies.push(body); }; Solver.prototype.addContact = function(contact) { _ASSERT && common.assert(contact instanceof Contact, "Not a Contact!", contact); this.m_contacts.push(contact); }; Solver.prototype.addJoint = function(joint) { _ASSERT && common.assert(joint instanceof Joint, "Not a Joint!", joint); this.m_joints.push(joint); }; Solver.prototype.solveWorld = function(step) { var world = this.m_world; for (var b = world.m_bodyList; b; b = b.m_next) { b.m_islandFlag = false; } for (var c = world.m_contactList; c; c = c.m_next) { c.m_islandFlag = false; } for (var j = world.m_jointList; j; j = j.m_next) { j.m_islandFlag = false; } var stack = this.m_stack; var loop = -1; for (var seed = world.m_bodyList; seed; seed = seed.m_next) { loop++; if (seed.m_islandFlag) { continue; } if (seed.isAwake() == false || seed.isActive() == false) { continue; } if (seed.isStatic()) { continue; } this.clear(); stack.push(seed); seed.m_islandFlag = true; while (stack.length > 0) { var b = stack.pop(); _ASSERT && common.assert(b.isActive() == true); this.addBody(b); b.setAwake(true); if (b.isStatic()) { continue; } for (var ce = b.m_contactList; ce; ce = ce.next) { var contact = ce.contact; if (contact.m_islandFlag) { continue; } if (contact.isEnabled() == false || contact.isTouching() == false) { continue; } var sensorA = contact.m_fixtureA.m_isSensor; var sensorB = contact.m_fixtureB.m_isSensor; if (sensorA || sensorB) { continue; } this.addContact(contact); contact.m_islandFlag = true; var other = ce.other; if (other.m_islandFlag) { continue; } stack.push(other); other.m_islandFlag = true; } for (var je = b.m_jointList; je; je = je.next) { if (je.joint.m_islandFlag == true) { continue; } var other = je.other; if (other.isActive() == false) { continue; } this.addJoint(je.joint); je.joint.m_islandFlag = true; if (other.m_islandFlag) { continue; } stack.push(other); other.m_islandFlag = true; } } this.solveIsland(step); for (var i = 0; i < this.m_bodies.length; ++i) { var b = this.m_bodies[i]; if (b.isStatic()) { b.m_islandFlag = false; } } } }; Solver.prototype.solveIsland = function(step) { var world = this.m_world; var gravity = world.m_gravity; var allowSleep = world.m_allowSleep; var h = step.dt; for (var i = 0; i < this.m_bodies.length; ++i) { var body = this.m_bodies[i]; var c = Vec2.clone(body.m_sweep.c); var a = body.m_sweep.a; var v = Vec2.clone(body.m_linearVelocity); var w = body.m_angularVelocity; body.m_sweep.c0.set(body.m_sweep.c); body.m_sweep.a0 = body.m_sweep.a; if (body.isDynamic()) { v.addMul(h * body.m_gravityScale, gravity); v.addMul(h * body.m_invMass, body.m_force); w += h * body.m_invI * body.m_torque; v.mul(1 / (1 + h * body.m_linearDamping)); w *= 1 / (1 + h * body.m_angularDamping); } body.c_position.c = c; body.c_position.a = a; body.c_velocity.v = v; body.c_velocity.w = w; } for (var i = 0; i < this.m_contacts.length; ++i) { var contact = this.m_contacts[i]; contact.initConstraint(step); } _DEBUG && this.printBodies("M: "); for (var i = 0; i < this.m_contacts.length; ++i) { var contact = this.m_contacts[i]; contact.initVelocityConstraint(step); } _DEBUG && this.printBodies("R: "); if (step.warmStarting) { for (var i = 0; i < this.m_contacts.length; ++i) { var contact = this.m_contacts[i]; contact.warmStartConstraint(step); } } _DEBUG && this.printBodies("Q: "); for (var i = 0; i < this.m_joints.length; ++i) { var joint = this.m_joints[i]; joint.initVelocityConstraints(step); } _DEBUG && this.printBodies("E: "); for (var i = 0; i < step.velocityIterations; ++i) { for (var j = 0; j < this.m_joints.length; ++j) { var joint = this.m_joints[j]; joint.solveVelocityConstraints(step); } for (var j = 0; j < this.m_contacts.length; ++j) { var contact = this.m_contacts[j]; contact.solveVelocityConstraint(step); } } _DEBUG && this.printBodies("D: "); for (var i = 0; i < this.m_contacts.length; ++i) { var contact = this.m_contacts[i]; contact.storeConstraintImpulses(step); } _DEBUG && this.printBodies("C: "); for (var i = 0; i < this.m_bodies.length; ++i) { var body = this.m_bodies[i]; var c = Vec2.clone(body.c_position.c); var a = body.c_position.a; var v = Vec2.clone(body.c_velocity.v); var w = body.c_velocity.w; var translation = Vec2.mul(h, v); if (Vec2.lengthSquared(translation) > Settings.maxTranslationSquared) { var ratio = Settings.maxTranslation / translation.length(); v.mul(ratio); } var rotation = h * w; if (rotation * rotation > Settings.maxRotationSquared) { var ratio = Settings.maxRotation / Math.abs(rotation); w *= ratio; } c.addMul(h, v); a += h * w; body.c_position.c.set(c); body.c_position.a = a; body.c_velocity.v.set(v); body.c_velocity.w = w; } _DEBUG && this.printBodies("B: "); var positionSolved = false; for (var i = 0; i < step.positionIterations; ++i) { var minSeparation = 0; for (var j = 0; j < this.m_contacts.length; ++j) { var contact = this.m_contacts[j]; var separation = contact.solvePositionConstraint(step); minSeparation = Math.min(minSeparation, separation); } var contactsOkay = minSeparation >= -3 * Settings.linearSlop; var jointsOkay = true; for (var j = 0; j < this.m_joints.length; ++j) { var joint = this.m_joints[j]; var jointOkay = joint.solvePositionConstraints(step); jointsOkay = jointsOkay && jointOkay; } if (contactsOkay && jointsOkay) { positionSolved = true; break; } } _DEBUG && this.printBodies("L: "); for (var i = 0; i < this.m_bodies.length; ++i) { var body = this.m_bodies[i]; body.m_sweep.c.set(body.c_position.c); body.m_sweep.a = body.c_position.a; body.m_linearVelocity.set(body.c_velocity.v); body.m_angularVelocity = body.c_velocity.w; body.synchronizeTransform(); } this.postSolveIsland(); if (allowSleep) { var minSleepTime = Infinity; var linTolSqr = Settings.linearSleepToleranceSqr; var angTolSqr = Settings.angularSleepToleranceSqr; for (var i = 0; i < this.m_bodies.length; ++i) { var body = this.m_bodies[i]; if (body.isStatic()) { continue; } if (body.m_autoSleepFlag == false || body.m_angularVelocity * body.m_angularVelocity > angTolSqr || Vec2.lengthSquared(body.m_linearVelocity) > linTolSqr) { body.m_sleepTime = 0; minSleepTime = 0; } else { body.m_sleepTime += h; minSleepTime = Math.min(minSleepTime, body.m_sleepTime); } } if (minSleepTime >= Settings.timeToSleep && positionSolved) { for (var i = 0; i < this.m_bodies.length; ++i) { var body = this.m_bodies[i]; body.setAwake(false); } } } }; Solver.prototype.printBodies = function(tag) { for (var i = 0; i < this.m_bodies.length; ++i) { var b = this.m_bodies[i]; common.debug(tag, b.c_position.a, b.c_position.c.x, b.c_position.c.y, b.c_velocity.w, b.c_velocity.v.x, b.c_velocity.v.y); } }; var s_subStep = new TimeStep(); Solver.prototype.solveWorldTOI = function(step) { var world = this.m_world; if (world.m_stepComplete) { for (var b = world.m_bodyList; b; b = b.m_next) { b.m_islandFlag = false; b.m_sweep.alpha0 = 0; } for (var c = world.m_contactList; c; c = c.m_next) { c.m_toiFlag = false; c.m_islandFlag = false; c.m_toiCount = 0; c.m_toi = 1; } } for (;;) { var minContact = null; var minAlpha = 1; for (var c = world.m_contactList; c; c = c.m_next) { if (c.isEnabled() == false) { continue; } if (c.m_toiCount > Settings.maxSubSteps) { continue; } var alpha = 1; if (c.m_toiFlag) { alpha = c.m_toi; } else { var fA = c.getFixtureA(); var fB = c.getFixtureB(); if (fA.isSensor() || fB.isSensor()) { continue; } var bA = fA.getBody(); var bB = fB.getBody(); _ASSERT && common.assert(bA.isDynamic() || bB.isDynamic()); var activeA = bA.isAwake() && !bA.isStatic(); var activeB = bB.isAwake() && !bB.isStatic(); if (activeA == false && activeB == false) { continue; } var collideA = bA.isBullet() || !bA.isDynamic(); var collideB = bB.isBullet() || !bB.isDynamic(); if (collideA == false && collideB == false) { continue; } var alpha0 = bA.m_sweep.alpha0; if (bA.m_sweep.alpha0 < bB.m_sweep.alpha0) { alpha0 = bB.m_sweep.alpha0; bA.m_sweep.advance(alpha0); } else if (bB.m_sweep.alpha0 < bA.m_sweep.alpha0) { alpha0 = bA.m_sweep.alpha0; bB.m_sweep.advance(alpha0); } _ASSERT && common.assert(alpha0 < 1); var indexA = c.getChildIndexA(); var indexB = c.getChildIndexB(); var sweepA = bA.m_sweep; var sweepB = bB.m_sweep; var input = new TOIInput(); input.proxyA.set(fA.getShape(), indexA); input.proxyB.set(fB.getShape(), indexB); input.sweepA.set(bA.m_sweep); input.sweepB.set(bB.m_sweep); input.tMax = 1; var output = new TOIOutput(); TimeOfImpact(output, input); var beta = output.t; if (output.state == TOIOutput.e_touching) { alpha = Math.min(alpha0 + (1 - alpha0) * beta, 1); } else { alpha = 1; } c.m_toi = alpha; c.m_toiFlag = true; } if (alpha < minAlpha) { minContact = c; minAlpha = alpha; } } if (minContact == null || 1 - 10 * Math.EPSILON < minAlpha) { world.m_stepComplete = true; break; } var fA = minContact.getFixtureA(); var fB = minContact.getFixtureB(); var bA = fA.getBody(); var bB = fB.getBody(); var backup1 = bA.m_sweep.clone(); var backup2 = bB.m_sweep.clone(); bA.advance(minAlpha); bB.advance(minAlpha); minContact.update(world); minContact.m_toiFlag = false; ++minContact.m_toiCount; if (minContact.isEnabled() == false || minContact.isTouching() == false) { minContact.setEnabled(false); bA.m_sweep.set(backup1); bB.m_sweep.set(backup2); bA.synchronizeTransform(); bB.synchronizeTransform(); continue; } bA.setAwake(true); bB.setAwake(true); this.clear(); this.addBody(bA); this.addBody(bB); this.addContact(minContact); bA.m_islandFlag = true; bB.m_islandFlag = true; minContact.m_islandFlag = true; var bodies = [ bA, bB ]; for (var i = 0; i < bodies.length; ++i) { var body = bodies[i]; if (body.isDynamic()) { for (var ce = body.m_contactList; ce; ce = ce.next) { var contact = ce.contact; if (contact.m_islandFlag) { continue; } var other = ce.other; if (other.isDynamic() && !body.isBullet() && !other.isBullet()) { continue; } var sensorA = contact.m_fixtureA.m_isSensor; var sensorB = contact.m_fixtureB.m_isSensor; if (sensorA || sensorB) { continue; } var backup = other.m_sweep.clone(); if (other.m_islandFlag == false) { other.advance(minAlpha); } contact.update(world); if (contact.isEnabled() == false || contact.isTouching() == false) { other.m_sweep.set(backup); other.synchronizeTransform(); continue; } contact.m_islandFlag = true; this.addContact(contact); if (other.m_islandFlag) { continue; } other.m_islandFlag = true; if (!other.isStatic()) { other.setAwake(true); } this.addBody(other); } } } s_subStep.reset((1 - minAlpha) * step.dt); s_subStep.dtRatio = 1; s_subStep.positionIterations = 20; s_subStep.velocityIterations = step.velocityIterations; s_subStep.warmStarting = false; this.solveIslandTOI(s_subStep, bA, bB); for (var i = 0; i < this.m_bodies.length; ++i) { var body = this.m_bodies[i]; body.m_islandFlag = false; if (!body.isDynamic()) { continue; } body.synchronizeFixtures(); for (var ce = body.m_contactList; ce; ce = ce.next) { ce.contact.m_toiFlag = false; ce.contact.m_islandFlag = false; } } world.findNewContacts(); if (world.m_subStepping) { world.m_stepComplete = false; break; } } if (_DEBUG) for (var b = world.m_bodyList; b; b = b.m_next) { var c = b.m_sweep.c; var a = b.m_sweep.a; var v = b.m_linearVelocity; var w = b.m_angularVelocity; } }; Solver.prototype.solveIslandTOI = function(subStep, toiA, toiB) { var world = this.m_world; for (var i = 0; i < this.m_bodies.length; ++i) { var body = this.m_bodies[i]; body.c_position.c.set(body.m_sweep.c); body.c_position.a = body.m_sweep.a; body.c_velocity.v.set(body.m_linearVelocity); body.c_velocity.w = body.m_angularVelocity; } for (var i = 0; i < this.m_contacts.length; ++i) { var contact = this.m_contacts[i]; contact.initConstraint(subStep); } for (var i = 0; i < subStep.positionIterations; ++i) { var minSeparation = 0; for (var j = 0; j < this.m_contacts.length; ++j) { var contact = this.m_contacts[j]; var separation = contact.solvePositionConstraintTOI(subStep, toiA, toiB); minSeparation = Math.min(minSeparation, separation); } var contactsOkay = minSeparation >= -1.5 * Settings.linearSlop; if (contactsOkay) { break; } } if (false) { for (var i = 0; i < this.m_contacts.length; ++i) { var c = this.m_contacts[i]; var fA = c.getFixtureA(); var fB = c.getFixtureB(); var bA = fA.getBody(); var bB = fB.getBody(); var indexA = c.getChildIndexA(); var indexB = c.getChildIndexB(); var input = new DistanceInput(); input.proxyA.set(fA.getShape(), indexA); input.proxyB.set(fB.getShape(), indexB); input.transformA = bA.getTransform(); input.transformB = bB.getTransform(); input.useRadii = false; var output = new DistanceOutput(); var cache = new SimplexCache(); Distance(output, cache, input); if (output.distance == 0 || cache.count == 3) { cache.count += 0; } } } toiA.m_sweep.c0.set(toiA.c_position.c); toiA.m_sweep.a0 = toiA.c_position.a; toiB.m_sweep.c0.set(toiB.c_position.c); toiB.m_sweep.a0 = toiB.c_position.a; for (var i = 0; i < this.m_contacts.length; ++i) { var contact = this.m_contacts[i]; contact.initVelocityConstraint(subStep); } for (var i = 0; i < subStep.velocityIterations; ++i) { for (var j = 0; j < this.m_contacts.length; ++j) { var contact = this.m_contacts[j]; contact.solveVelocityConstraint(subStep); } } var h = subStep.dt; for (var i = 0; i < this.m_bodies.length; ++i) { var body = this.m_bodies[i]; var c = Vec2.clone(body.c_position.c); var a = body.c_position.a; var v = Vec2.clone(body.c_velocity.v); var w = body.c_velocity.w; var translation = Vec2.mul(h, v); if (Vec2.dot(translation, translation) > Settings.maxTranslationSquared) { var ratio = Settings.maxTranslation / translation.length(); v.mul(ratio); } var rotation = h * w; if (rotation * rotation > Settings.maxRotationSquared) { var ratio = Settings.maxRotation / Math.abs(rotation); w *= ratio; } c.addMul(h, v); a += h * w; body.c_position.c = c; body.c_position.a = a; body.c_velocity.v = v; body.c_velocity.w = w; body.m_sweep.c = c; body.m_sweep.a = a; body.m_linearVelocity = v; body.m_angularVelocity = w; body.synchronizeTransform(); } this.postSolveIsland(); }; function ContactImpulse() { this.normalImpulses = []; this.tangentImpulses = []; } Solver.prototype.postSolveIsland = function() { var impulse = new ContactImpulse(); for (var c = 0; c < this.m_contacts.length; ++c) { var contact = this.m_contacts[c]; for (var p = 0; p < contact.v_points.length; ++p) { impulse.normalImpulses.push(contact.v_points[p].normalImpulse); impulse.tangentImpulses.push(contact.v_points[p].tangentImpulse); } this.m_world.postSolve(contact, impulse); } }; },{"./Body":2,"./Contact":3,"./Joint":5,"./Settings":7,"./collision/Distance":13,"./collision/TimeOfImpact":15,"./common/Math":18,"./common/Vec2":23,"./util/common":51}],10:[function(require,module,exports){ var _DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; var _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = World; var options = require("./util/options"); var common = require("./util/common"); var Vec2 = require("./common/Vec2"); var BroadPhase = require("./collision/BroadPhase"); var Solver = require("./Solver"); var Body = require("./Body"); var Contact = require("./Contact"); var WorldDef = { gravity: Vec2.zero(), allowSleep: true, warmStarting: true, continuousPhysics: true, subStepping: false, blockSolve: true, velocityIterations: 8, positionIterations: 3 }; function World(def) { if (!(this instanceof World)) { return new World(def); } if (def && Vec2.isValid(def)) { def = { gravity: def }; } def = options(def, WorldDef); this.m_solver = new Solver(this); this.m_broadPhase = new BroadPhase(); this.m_contactList = null; this.m_contactCount = 0; this.m_bodyList = null; this.m_bodyCount = 0; this.m_jointList = null; this.m_jointCount = 0; this.m_stepComplete = true; this.m_allowSleep = def.allowSleep; this.m_gravity = Vec2.clone(def.gravity); this.m_clearForces = true; this.m_newFixture = false; this.m_locked = false; this.m_warmStarting = def.warmStarting; this.m_continuousPhysics = def.continuousPhysics; this.m_subStepping = def.subStepping; this.m_blockSolve = def.blockSolve; this.m_velocityIterations = def.velocityIterations; this.m_positionIterations = def.positionIterations; this.m_t = 0; this.m_stepCount = 0; this.addPair = this.createContact.bind(this); } World.prototype.getBodyList = function() { return this.m_bodyList; }; World.prototype.getJointList = function() { return this.m_jointList; }; World.prototype.getContactList = function() { return this.m_contactList; }; World.prototype.getBodyCount = function() { return this.m_bodyCount; }; World.prototype.getJointCount = function() { return this.m_jointCount; }; World.prototype.getContactCount = function() { return this.m_contactCount; }; World.prototype.setGravity = function(gravity) { this.m_gravity = gravity; }; World.prototype.getGravity = function() { return this.m_gravity; }; World.prototype.isLocked = function() { return this.m_locked; }; World.prototype.setAllowSleeping = function(flag) { if (flag == this.m_allowSleep) { return; } this.m_allowSleep = flag; if (this.m_allowSleep == false) { for (var b = this.m_bodyList; b; b = b.m_next) { b.setAwake(true); } } }; World.prototype.getAllowSleeping = function() { return this.m_allowSleep; }; World.prototype.setWarmStarting = function(flag) { this.m_warmStarting = flag; }; World.prototype.getWarmStarting = function() { return this.m_warmStarting; }; World.prototype.setContinuousPhysics = function(flag) { this.m_continuousPhysics = flag; }; World.prototype.getContinuousPhysics = function() { return this.m_continuousPhysics; }; World.prototype.setSubStepping = function(flag) { this.m_subStepping = flag; }; World.prototype.getSubStepping = function() { return this.m_subStepping; }; World.prototype.setAutoClearForces = function(flag) { this.m_clearForces = flag; }; World.prototype.getAutoClearForces = function() { return this.m_clearForces; }; World.prototype.clearForces = function() { for (var body = this.m_bodyList; body; body = body.getNext()) { body.m_force.setZero(); body.m_torque = 0; } }; World.prototype.queryAABB = function(aabb, queryCallback) { _ASSERT && common.assert(typeof queryCallback === "function"); var broadPhase = this.m_broadPhase; this.m_broadPhase.query(aabb, function(proxyId) { var proxy = broadPhase.getUserData(proxyId); return queryCallback(proxy.fixture); }); }; World.prototype.rayCast = function(point1, point2, reportFixtureCallback) { _ASSERT && common.assert(typeof reportFixtureCallback === "function"); var broadPhase = this.m_broadPhase; this.m_broadPhase.rayCast({ maxFraction: 1, p1: point1, p2: point2 }, function(input, proxyId) { var proxy = broadPhase.getUserData(proxyId); var fixture = proxy.fixture; var index = proxy.childIndex; var output = {}; var hit = fixture.rayCast(output, input, index); if (hit) { var fraction = output.fraction; var point = Vec2.add(Vec2.mul(1 - fraction, input.p1), Vec2.mul(fraction, input.p2)); return reportFixtureCallback(fixture, point, output.normal, fraction); } return input.maxFraction; }); }; World.prototype.getProxyCount = function() { return this.m_broadPhase.getProxyCount(); }; World.prototype.getTreeHeight = function() { return this.m_broadPhase.getTreeHeight(); }; World.prototype.getTreeBalance = function() { return this.m_broadPhase.getTreeBalance(); }; World.prototype.getTreeQuality = function() { return this.m_broadPhase.getTreeQuality(); }; World.prototype.shiftOrigin = function(newOrigin) { _ASSERT && common.assert(this.m_locked == false); if (this.m_locked) { return; } for (var b = this.m_bodyList; b; b = b.m_next) { b.m_xf.p.sub(newOrigin); b.m_sweep.c0.sub(newOrigin); b.m_sweep.c.sub(newOrigin); } for (var j = this.m_jointList; j; j = j.m_next) { j.shiftOrigin(newOrigin); } this.m_broadPhase.shiftOrigin(newOrigin); }; World.prototype.createBody = function(def, angle) { _ASSERT && common.assert(this.isLocked() == false); if (this.isLocked()) { return null; } if (def && Vec2.isValid(def)) { def = { position: def, angle: angle }; } var body = new Body(this, def); body.m_prev = null; body.m_next = this.m_bodyList; if (this.m_bodyList) { this.m_bodyList.m_prev = body; } this.m_bodyList = body; ++this.m_bodyCount; return body; }; World.prototype.createDynamicBody = function(def, angle) { if (!def) { def = {}; } else if (Vec2.isValid(def)) { def = { position: def, angle: angle }; } def.type = "dynamic"; return this.createBody(def); }; World.prototype.createKinematicBody = function(def, angle) { if (!def) { def = {}; } else if (Vec2.isValid(def)) { def = { position: def, angle: angle }; } def.type = "kinematic"; return this.createBody(def); }; World.prototype.destroyBody = function(b) { _ASSERT && common.assert(this.m_bodyCount > 0); _ASSERT && common.assert(this.isLocked() == false); if (this.isLocked()) { return; } if (b.m_destroyed) { return false; } var je = b.m_jointList; while (je) { var je0 = je; je = je.next; this.publish("remove-joint", je0.joint); this.destroyJoint(je0.joint); b.m_jointList = je; } b.m_jointList = null; var ce = b.m_contactList; while (ce) { var ce0 = ce; ce = ce.next; this.destroyContact(ce0.contact); b.m_contactList = ce; } b.m_contactList = null; var f = b.m_fixtureList; while (f) { var f0 = f; f = f.m_next; this.publish("remove-fixture", f0); f0.destroyProxies(this.m_broadPhase); b.m_fixtureList = f; } b.m_fixtureList = null; if (b.m_prev) { b.m_prev.m_next = b.m_next; } if (b.m_next) { b.m_next.m_prev = b.m_prev; } if (b == this.m_bodyList) { this.m_bodyList = b.m_next; } b.m_destroyed = true; --this.m_bodyCount; return true; }; World.prototype.createJoint = function(joint) { _ASSERT && common.assert(!!joint.m_bodyA); _ASSERT && common.assert(!!joint.m_bodyB); _ASSERT && common.assert(this.isLocked() == false); if (this.isLocked()) { return null; } joint.m_prev = null; joint.m_next = this.m_jointList; if (this.m_jointList) { this.m_jointList.m_prev = joint; } this.m_jointList = joint; ++this.m_jointCount; joint.m_edgeA.joint = joint; joint.m_edgeA.other = joint.m_bodyB; joint.m_edgeA.prev = null; joint.m_edgeA.next = joint.m_bodyA.m_jointList; if (joint.m_bodyA.m_jointList) joint.m_bodyA.m_jointList.prev = joint.m_edgeA; joint.m_bodyA.m_jointList = joint.m_edgeA; joint.m_edgeB.joint = joint; joint.m_edgeB.other = joint.m_bodyA; joint.m_edgeB.prev = null; joint.m_edgeB.next = joint.m_bodyB.m_jointList; if (joint.m_bodyB.m_jointList) joint.m_bodyB.m_jointList.prev = joint.m_edgeB; joint.m_bodyB.m_jointList = joint.m_edgeB; if (joint.m_collideConnected == false) { for (var edge = joint.m_bodyB.getContactList(); edge; edge = edge.next) { if (edge.other == joint.m_bodyA) { edge.contact.flagForFiltering(); } } } return joint; }; World.prototype.destroyJoint = function(joint) { _ASSERT && common.assert(this.isLocked() == false); if (this.isLocked()) { return; } if (joint.m_prev) { joint.m_prev.m_next = joint.m_next; } if (joint.m_next) { joint.m_next.m_prev = joint.m_prev; } if (joint == this.m_jointList) { this.m_jointList = joint.m_next; } var bodyA = joint.m_bodyA; var bodyB = joint.m_bodyB; bodyA.setAwake(true); bodyB.setAwake(true); if (joint.m_edgeA.prev) { joint.m_edgeA.prev.next = joint.m_edgeA.next; } if (joint.m_edgeA.next) { joint.m_edgeA.next.prev = joint.m_edgeA.prev; } if (joint.m_edgeA == bodyA.m_jointList) { bodyA.m_jointList = joint.m_edgeA.next; } joint.m_edgeA.prev = null; joint.m_edgeA.next = null; if (joint.m_edgeB.prev) { joint.m_edgeB.prev.next = joint.m_edgeB.next; } if (joint.m_edgeB.next) { joint.m_edgeB.next.prev = joint.m_edgeB.prev; } if (joint.m_edgeB == bodyB.m_jointList) { bodyB.m_jointList = joint.m_edgeB.next; } joint.m_edgeB.prev = null; joint.m_edgeB.next = null; _ASSERT && common.assert(this.m_jointCount > 0); --this.m_jointCount; if (joint.m_collideConnected == false) { var edge = bodyB.getContactList(); while (edge) { if (edge.other == bodyA) { edge.contact.flagForFiltering(); } edge = edge.next; } } this.publish("remove-joint", joint); }; var s_step = new Solver.TimeStep(); World.prototype.step = function(timeStep, velocityIterations, positionIterations) { if ((velocityIterations | 0) !== velocityIterations) { velocityIterations = 0; } velocityIterations = velocityIterations || this.m_velocityIterations; positionIterations = positionIterations || this.m_positionIterations; this.m_stepCount++; if (this.m_newFixture) { this.findNewContacts(); this.m_newFixture = false; } this.m_locked = true; s_step.reset(timeStep); s_step.velocityIterations = velocityIterations; s_step.positionIterations = positionIterations; s_step.warmStarting = this.m_warmStarting; s_step.blockSolve = this.m_blockSolve; this.updateContacts(); if (this.m_stepComplete && timeStep > 0) { this.m_solver.solveWorld(s_step); for (var b = this.m_bodyList; b; b = b.getNext()) { if (b.m_islandFlag == false) { continue; } if (b.isStatic()) { continue; } b.synchronizeFixtures(); } this.findNewContacts(); } if (this.m_continuousPhysics && timeStep > 0) { this.m_solver.solveWorldTOI(s_step); } if (this.m_clearForces) { this.clearForces(); } this.m_locked = false; }; World.prototype.findNewContacts = function() { this.m_broadPhase.updatePairs(this.addPair); }; World.prototype.createContact = function(proxyA, proxyB) { var fixtureA = proxyA.fixture; var fixtureB = proxyB.fixture; var indexA = proxyA.childIndex; var indexB = proxyB.childIndex; var bodyA = fixtureA.getBody(); var bodyB = fixtureB.getBody(); if (bodyA == bodyB) { return; } var edge = bodyB.getContactList(); while (edge) { if (edge.other == bodyA) { var fA = edge.contact.getFixtureA(); var fB = edge.contact.getFixtureB(); var iA = edge.contact.getChildIndexA(); var iB = edge.contact.getChildIndexB(); if (fA == fixtureA && fB == fixtureB && iA == indexA && iB == indexB) { return; } if (fA == fixtureB && fB == fixtureA && iA == indexB && iB == indexA) { return; } } edge = edge.next; } if (bodyB.shouldCollide(bodyA) == false) { return; } if (fixtureB.shouldCollide(fixtureA) == false) { return; } var contact = Contact.create(fixtureA, indexA, fixtureB, indexB); if (contact == null) { return; } contact.m_prev = null; if (this.m_contactList != null) { contact.m_next = this.m_contactList; this.m_contactList.m_prev = contact; } this.m_contactList = contact; ++this.m_contactCount; }; World.prototype.updateContacts = function() { var c, next_c = this.m_contactList; while (c = next_c) { next_c = c.getNext(); var fixtureA = c.getFixtureA(); var fixtureB = c.getFixtureB(); var indexA = c.getChildIndexA(); var indexB = c.getChildIndexB(); var bodyA = fixtureA.getBody(); var bodyB = fixtureB.getBody(); if (c.m_filterFlag) { if (bodyB.shouldCollide(bodyA) == false) { this.destroyContact(c); continue; } if (fixtureB.shouldCollide(fixtureA) == false) { this.destroyContact(c); continue; } c.m_filterFlag = false; } var activeA = bodyA.isAwake() && !bodyA.isStatic(); var activeB = bodyB.isAwake() && !bodyB.isStatic(); if (activeA == false && activeB == false) { continue; } var proxyIdA = fixtureA.m_proxies[indexA].proxyId; var proxyIdB = fixtureB.m_proxies[indexB].proxyId; var overlap = this.m_broadPhase.testOverlap(proxyIdA, proxyIdB); if (overlap == false) { this.destroyContact(c); continue; } c.update(this); } }; World.prototype.destroyContact = function(contact) { Contact.destroy(contact, this); if (contact.m_prev) { contact.m_prev.m_next = contact.m_next; } if (contact.m_next) { contact.m_next.m_prev = contact.m_prev; } if (contact == this.m_contactList) { this.m_contactList = contact.m_next; } --this.m_contactCount; }; World.prototype._listeners = null; World.prototype.on = function(name, listener) { if (typeof name !== "string" || typeof listener !== "function") { return this; } if (!this._listeners) { this._listeners = {}; } if (!this._listeners[name]) { this._listeners[name] = []; } this._listeners[name].push(listener); return this; }; World.prototype.off = function(name, listener) { if (typeof name !== "string" || typeof listener !== "function") { return this; } var listeners = this._listeners && this._listeners[name]; if (!listeners || !listeners.length) { return this; } var index = listeners.indexOf(listener); if (index >= 0) { listeners.splice(index, 1); } return this; }; World.prototype.publish = function(name, arg1, arg2, arg3) { var listeners = this._listeners && this._listeners[name]; if (!listeners || !listeners.length) { return 0; } for (var l = 0; l < listeners.length; l++) { listeners[l].call(this, arg1, arg2, arg3); } return listeners.length; }; World.prototype.beginContact = function(contact) { this.publish("begin-contact", contact); }; World.prototype.endContact = function(contact) { this.publish("end-contact", contact); }; World.prototype.preSolve = function(contact, oldManifold) { this.publish("pre-solve", contact, oldManifold); }; World.prototype.postSolve = function(contact, impulse) { this.publish("post-solve", contact, impulse); }; },{"./Body":2,"./Contact":3,"./Solver":9,"./collision/BroadPhase":12,"./common/Vec2":23,"./util/common":51,"./util/options":53}],11:[function(require,module,exports){ var _DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; var _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; var Settings = require("../Settings"); var Math = require("../common/Math"); var Vec2 = require("../common/Vec2"); module.exports = AABB; function AABB(lower, upper) { if (!(this instanceof AABB)) { return new AABB(lower, upper); } this.lowerBound = Vec2.zero(); this.upperBound = Vec2.zero(); if (typeof lower === "object") { this.lowerBound.set(lower); } if (typeof upper === "object") { this.upperBound.set(upper); } } AABB.prototype.isValid = function() { return AABB.isValid(this); }; AABB.isValid = function(aabb) { var d = Vec2.sub(aabb.upperBound, aabb.lowerBound); var valid = d.x >= 0 && d.y >= 0 && Vec2.isValid(aabb.lowerBound) && Vec2.isValid(aabb.upperBound); return valid; }; AABB.assert = function(o) { if (!_ASSERT) return; if (!AABB.isValid(o)) { _DEBUG && common.debug(o); throw new Error("Invalid AABB!"); } }; AABB.prototype.getCenter = function() { return Vec2.neo((this.lowerBound.x + this.upperBound.x) * .5, (this.lowerBound.y + this.upperBound.y) * .5); }; AABB.prototype.getExtents = function() { return Vec2.neo((this.upperBound.x - this.lowerBound.x) * .5, (this.upperBound.y - this.lowerBound.y) * .5); }; AABB.prototype.getPerimeter = function() { return 2 * (this.upperBound.x - this.lowerBound.x + this.upperBound.y - this.lowerBound.y); }; AABB.prototype.combine = function(a, b) { var lowerA, upperA, lowerB, upperB; if ("x" in a && "y" in a) { lowerA = a; upperA = a; } else if ("lowerBound" in a && "upperBound" in a) { lowerA = a.lowerBound; upperA = a.upperBound; } else if (_ASSERT) { throw new Error("Invalid param!"); } if ("x" in b && "y" in b) { lowerB = b; upperB = b; } else if ("lowerBound" in b && "upperBound" in b) { lowerB = b.lowerBound; upperB = b.upperBound; } else if (_ASSERT) { throw new Error("Invalid param!"); } var lowerX = Math.min(lowerA.x, lowerB.x); var lowerY = Math.min(lowerA.y, lowerB.y); var upperX = Math.max(upperB.x, upperA.x); var upperY = Math.max(upperB.y, upperA.y); this.lowerBound.set(lowerX, lowerY); this.upperBound.set(upperX, upperY); }; AABB.prototype.combinePoints = function(a, b) { this.lowerBound.set(Math.min(a.x, b.x), Math.min(a.y, b.y)); this.upperBound.set(Math.max(a.x, b.x), Math.max(a.y, b.y)); }; AABB.prototype.set = function(aabb) { this.lowerBound.set(aabb.lowerBound.x, aabb.lowerBound.y); this.upperBound.set(aabb.upperBound.x, aabb.upperBound.y); }; AABB.prototype.contains = function(aabb) { var result = true; result = result && this.lowerBound.x <= aabb.lowerBound.x; result = result && this.lowerBound.y <= aabb.lowerBound.y; result = result && aabb.upperBound.x <= this.upperBound.x; result = result && aabb.upperBound.y <= this.upperBound.y; return result; }; AABB.prototype.extend = function(value) { AABB.extend(this, value); }; AABB.extend = function(aabb, value) { aabb.lowerBound.x -= value; aabb.lowerBound.y -= value; aabb.upperBound.x += value; aabb.upperBound.y += value; }; AABB.testOverlap = function(a, b) { var d1x = b.lowerBound.x - a.upperBound.x; var d2x = a.lowerBound.x - b.upperBound.x; var d1y = b.lowerBound.y - a.upperBound.y; var d2y = a.lowerBound.y - b.upperBound.y; if (d1x > 0 || d1y > 0 || d2x > 0 || d2y > 0) { return false; } return true; }; AABB.areEqual = function(a, b) { return Vec2.areEqual(a.lowerBound, b.lowerBound) && Vec2.areEqual(a.upperBound, b.upperBound); }; AABB.diff = function(a, b) { var wD = Math.max(0, Math.min(a.upperBound.x, b.upperBound.x) - Math.max(b.lowerBound.x, a.lowerBound.x)); var hD = Math.max(0, Math.min(a.upperBound.y, b.upperBound.y) - Math.max(b.lowerBound.y, a.lowerBound.y)); var wA = a.upperBound.x - a.lowerBound.x; var hA = a.upperBound.y - a.lowerBound.y; var wB = b.upperBound.x - b.lowerBound.x; var hB = b.upperBound.y - b.lowerBound.y; return wA * hA + wB * hB - wD * hD; }; AABB.prototype.rayCast = function(output, input) { var tmin = -Infinity; var tmax = Infinity; var p = input.p1; var d = Vec2.sub(input.p2, input.p1); var absD = Vec2.abs(d); var normal = Vec2.zero(); for (var f = "x"; f !== null; f = f === "x" ? "y" : null) { if (absD.x < Math.EPSILON) { if (p[f] < this.lowerBound[f] || this.upperBound[f] < p[f]) { return false; } } else { var inv_d = 1 / d[f]; var t1 = (this.lowerBound[f] - p[f]) * inv_d; var t2 = (this.upperBound[f] - p[f]) * inv_d; var s = -1; if (t1 > t2) { var temp = t1; t1 = t2, t2 = temp; s = 1; } if (t1 > tmin) { normal.setZero(); normal[f] = s; tmin = t1; } tmax = Math.min(tmax, t2); if (tmin > tmax) { return false; } } } if (tmin < 0 || input.maxFraction < tmin) { return false; } output.fraction = tmin; output.normal = normal; return true; }; AABB.prototype.toString = function() { return JSON.stringify(this); }; },{"../Settings":7,"../common/Math":18,"../common/Vec2":23}],12:[function(require,module,exports){ var _DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; var _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; var Settings = require("../Settings"); var common = require("../util/common"); var Math = require("../common/Math"); var AABB = require("./AABB"); var DynamicTree = require("./DynamicTree"); module.exports = BroadPhase; function BroadPhase() { this.m_tree = new DynamicTree(); this.m_proxyCount = 0; this.m_moveBuffer = []; this.queryCallback = this.queryCallback.bind(this); } BroadPhase.prototype.getUserData = function(proxyId) { return this.m_tree.getUserData(proxyId); }; BroadPhase.prototype.testOverlap = function(proxyIdA, proxyIdB) { var aabbA = this.m_tree.getFatAABB(proxyIdA); var aabbB = this.m_tree.getFatAABB(proxyIdB); return AABB.testOverlap(aabbA, aabbB); }; BroadPhase.prototype.getFatAABB = function(proxyId) { return this.m_tree.getFatAABB(proxyId); }; BroadPhase.prototype.getProxyCount = function() { return this.m_proxyCount; }; BroadPhase.prototype.getTreeHeight = function() { return this.m_tree.getHeight(); }; BroadPhase.prototype.getTreeBalance = function() { return this.m_tree.getMaxBalance(); }; BroadPhase.prototype.getTreeQuality = function() { return this.m_tree.getAreaRatio(); }; BroadPhase.prototype.query = function(aabb, queryCallback) { this.m_tree.query(aabb, queryCallback); }; BroadPhase.prototype.rayCast = function(input, rayCastCallback) { this.m_tree.rayCast(input, rayCastCallback); }; BroadPhase.prototype.shiftOrigin = function(newOrigin) { this.m_tree.shiftOrigin(newOrigin); }; BroadPhase.prototype.createProxy = function(aabb, userData) { _ASSERT && common.assert(AABB.isValid(aabb)); var proxyId = this.m_tree.createProxy(aabb, userData); this.m_proxyCount++; this.bufferMove(proxyId); return proxyId; }; BroadPhase.prototype.destroyProxy = function(proxyId) { this.unbufferMove(proxyId); this.m_proxyCount--; this.m_tree.destroyProxy(proxyId); }; BroadPhase.prototype.moveProxy = function(proxyId, aabb, displacement) { _ASSERT && common.assert(AABB.isValid(aabb)); var changed = this.m_tree.moveProxy(proxyId, aabb, displacement); if (changed) { this.bufferMove(proxyId); } }; BroadPhase.prototype.touchProxy = function(proxyId) { this.bufferMove(proxyId); }; BroadPhase.prototype.bufferMove = function(proxyId) { this.m_moveBuffer.push(proxyId); }; BroadPhase.prototype.unbufferMove = function(proxyId) { for (var i = 0; i < this.m_moveBuffer.length; ++i) { if (this.m_moveBuffer[i] == proxyId) { this.m_moveBuffer[i] = null; } } }; BroadPhase.prototype.updatePairs = function(addPairCallback) { _ASSERT && common.assert(typeof addPairCallback === "function"); this.m_callback = addPairCallback; while (this.m_moveBuffer.length > 0) { this.m_queryProxyId = this.m_moveBuffer.pop(); if (this.m_queryProxyId === null) { continue; } var fatAABB = this.m_tree.getFatAABB(this.m_queryProxyId); this.m_tree.query(fatAABB, this.queryCallback); } }; BroadPhase.prototype.queryCallback = function(proxyId) { if (proxyId == this.m_queryProxyId) { return true; } var proxyIdA = Math.min(proxyId, this.m_queryProxyId); var proxyIdB = Math.max(proxyId, this.m_queryProxyId); var userDataA = this.m_tree.getUserData(proxyIdA); var userDataB = this.m_tree.getUserData(proxyIdB); this.m_callback(userDataA, userDataB); return true; }; },{"../Settings":7,"../common/Math":18,"../util/common":51,"./AABB":11,"./DynamicTree":14}],13:[function(require,module,exports){ var _DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; var _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = Distance; module.exports.Input = DistanceInput; module.exports.Output = DistanceOutput; module.exports.Proxy = DistanceProxy; module.exports.Cache = SimplexCache; var Settings = require("../Settings"); var common = require("../util/common"); var stats = require("../common/stats"); var Math = require("../common/Math"); var Vec2 = require("../common/Vec2"); var Vec3 = require("../common/Vec3"); var Mat22 = require("../common/Mat22"); var Mat33 = require("../common/Mat33"); var Rot = require("../common/Rot"); var Sweep = require("../common/Sweep"); var Transform = require("../common/Transform"); var Velocity = require("../common/Velocity"); var Position = require("../common/Position"); stats.gjkCalls = 0; stats.gjkIters = 0; stats.gjkMaxIters = 0; function DistanceInput() { this.proxyA = new DistanceProxy(); this.proxyB = new DistanceProxy(); this.transformA = null; this.transformB = null; this.useRadii = false; } function DistanceOutput() { this.pointA = Vec2.zero(); this.pointB = Vec2.zero(); this.distance; this.iterations; } function SimplexCache() { this.metric = 0; this.indexA = []; this.indexB = []; this.count = 0; } function Distance(output, cache, input) { ++stats.gjkCalls; var proxyA = input.proxyA; var proxyB = input.proxyB; var xfA = input.transformA; var xfB = input.transformB; var simplex = new Simplex(); simplex.readCache(cache, proxyA, xfA, proxyB, xfB); var vertices = simplex.m_v; var k_maxIters = Settings.maxDistnceIterations; var saveA = []; var saveB = []; var saveCount = 0; var distanceSqr1 = Infinity; var distanceSqr2 = Infinity; var iter = 0; while (iter < k_maxIters) { saveCount = simplex.m_count; for (var i = 0; i < saveCount; ++i) { saveA[i] = vertices[i].indexA; saveB[i] = vertices[i].indexB; } simplex.solve(); if (simplex.m_count == 3) { break; } var p = simplex.getClosestPoint(); distanceSqr2 = p.lengthSquared(); if (distanceSqr2 >= distanceSqr1) {} distanceSqr1 = distanceSqr2; var d = simplex.getSearchDirection(); if (d.lengthSquared() < Math.EPSILON * Math.EPSILON) { break; } var vertex = vertices[simplex.m_count]; vertex.indexA = proxyA.getSupport(Rot.mulT(xfA.q, Vec2.neg(d))); vertex.wA = Transform.mul(xfA, proxyA.getVertex(vertex.indexA)); vertex.indexB = proxyB.getSupport(Rot.mulT(xfB.q, d)); vertex.wB = Transform.mul(xfB, proxyB.getVertex(vertex.indexB)); vertex.w = Vec2.sub(vertex.wB, vertex.wA); ++iter; ++stats.gjkIters; var duplicate = false; for (var i = 0; i < saveCount; ++i) { if (vertex.indexA == saveA[i] && vertex.indexB == saveB[i]) { duplicate = true; break; } } if (duplicate) { break; } ++simplex.m_count; } stats.gjkMaxIters = Math.max(stats.gjkMaxIters, iter); simplex.getWitnessPoints(output.pointA, output.pointB); output.distance = Vec2.distance(output.pointA, output.pointB); output.iterations = iter; simplex.writeCache(cache); if (input.useRadii) { var rA = proxyA.m_radius; var rB = proxyB.m_radius; if (output.distance > rA + rB && output.distance > Math.EPSILON) { output.distance -= rA + rB; var normal = Vec2.sub(output.pointB, output.pointA); normal.normalize(); output.pointA.addMul(rA, normal); output.pointB.subMul(rB, normal); } else { var p = Vec2.mid(output.pointA, output.pointB); output.pointA.set(p); output.pointB.set(p); output.distance = 0; } } } function DistanceProxy() { this.m_buffer = []; this.m_vertices = []; this.m_count = 0; this.m_radius = 0; } DistanceProxy.prototype.getVertexCount = function() { return this.m_count; }; DistanceProxy.prototype.getVertex = function(index) { _ASSERT && common.assert(0 <= index && index < this.m_count); return this.m_vertices[index]; }; DistanceProxy.prototype.getSupport = function(d) { var bestIndex = 0; var bestValue = Vec2.dot(this.m_vertices[0], d); for (var i = 0; i < this.m_count; ++i) { var value = Vec2.dot(this.m_vertices[i], d); if (value > bestValue) { bestIndex = i; bestValue = value; } } return bestIndex; }; DistanceProxy.prototype.getSupportVertex = function(d) { return this.m_vertices[this.getSupport(d)]; }; DistanceProxy.prototype.set = function(shape, index) { _ASSERT && common.assert(typeof shape.computeDistanceProxy === "function"); shape.computeDistanceProxy(this, index); }; function SimplexVertex() { this.indexA; this.indexB; this.wA = Vec2.zero(); this.wB = Vec2.zero(); this.w = Vec2.zero(); this.a; } SimplexVertex.prototype.set = function(v) { this.indexA = v.indexA; this.indexB = v.indexB; this.wA = Vec2.clone(v.wA); this.wB = Vec2.clone(v.wB); this.w = Vec2.clone(v.w); this.a = v.a; }; function Simplex() { this.m_v1 = new SimplexVertex(); this.m_v2 = new SimplexVertex(); this.m_v3 = new SimplexVertex(); this.m_v = [ this.m_v1, this.m_v2, this.m_v3 ]; this.m_count; } Simplex.prototype.print = function() { if (this.m_count == 3) { return [ "+" + this.m_count, this.m_v1.a, this.m_v1.wA.x, this.m_v1.wA.y, this.m_v1.wB.x, this.m_v1.wB.y, this.m_v2.a, this.m_v2.wA.x, this.m_v2.wA.y, this.m_v2.wB.x, this.m_v2.wB.y, this.m_v3.a, this.m_v3.wA.x, this.m_v3.wA.y, this.m_v3.wB.x, this.m_v3.wB.y ].toString(); } else if (this.m_count == 2) { return [ "+" + this.m_count, this.m_v1.a, this.m_v1.wA.x, this.m_v1.wA.y, this.m_v1.wB.x, this.m_v1.wB.y, this.m_v2.a, this.m_v2.wA.x, this.m_v2.wA.y, this.m_v2.wB.x, this.m_v2.wB.y ].toString(); } else if (this.m_count == 1) { return [ "+" + this.m_count, this.m_v1.a, this.m_v1.wA.x, this.m_v1.wA.y, this.m_v1.wB.x, this.m_v1.wB.y ].toString(); } else { return "+" + this.m_count; } }; Simplex.prototype.readCache = function(cache, proxyA, transformA, proxyB, transformB) { _ASSERT && common.assert(cache.count <= 3); this.m_count = cache.count; for (var i = 0; i < this.m_count; ++i) { var v = this.m_v[i]; v.indexA = cache.indexA[i]; v.indexB = cache.indexB[i]; var wALocal = proxyA.getVertex(v.indexA); var wBLocal = proxyB.getVertex(v.indexB); v.wA = Transform.mul(transformA, wALocal); v.wB = Transform.mul(transformB, wBLocal); v.w = Vec2.sub(v.wB, v.wA); v.a = 0; } if (this.m_count > 1) { var metric1 = cache.metric; var metric2 = this.getMetric(); if (metric2 < .5 * metric1 || 2 * metric1 < metric2 || metric2 < Math.EPSILON) { this.m_count = 0; } } if (this.m_count == 0) { var v = this.m_v[0]; v.indexA = 0; v.indexB = 0; var wALocal = proxyA.getVertex(0); var wBLocal = proxyB.getVertex(0); v.wA = Transform.mul(transformA, wALocal); v.wB = Transform.mul(transformB, wBLocal); v.w = Vec2.sub(v.wB, v.wA); v.a = 1; this.m_count = 1; } }; Simplex.prototype.writeCache = function(cache) { cache.metric = this.getMetric(); cache.count = this.m_count; for (var i = 0; i < this.m_count; ++i) { cache.indexA[i] = this.m_v[i].indexA; cache.indexB[i] = this.m_v[i].indexB; } }; Simplex.prototype.getSearchDirection = function() { switch (this.m_count) { case 1: return Vec2.neg(this.m_v1.w); case 2: { var e12 = Vec2.sub(this.m_v2.w, this.m_v1.w); var sgn = Vec2.cross(e12, Vec2.neg(this.m_v1.w)); if (sgn > 0) { return Vec2.cross(1, e12); } else { return Vec2.cross(e12, 1); } } default: _ASSERT && common.assert(false); return Vec2.zero(); } }; Simplex.prototype.getClosestPoint = function() { switch (this.m_count) { case 0: _ASSERT && common.assert(false); return Vec2.zero(); case 1: return Vec2.clone(this.m_v1.w); case 2: return Vec2.combine(this.m_v1.a, this.m_v1.w, this.m_v2.a, this.m_v2.w); case 3: return Vec2.zero(); default: _ASSERT && common.assert(false); return Vec2.zero(); } }; Simplex.prototype.getWitnessPoints = function(pA, pB) { switch (this.m_count) { case 0: _ASSERT && common.assert(false); break; case 1: pA.set(this.m_v1.wA); pB.set(this.m_v1.wB); break; case 2: pA.setCombine(this.m_v1.a, this.m_v1.wA, this.m_v2.a, this.m_v2.wA); pB.setCombine(this.m_v1.a, this.m_v1.wB, this.m_v2.a, this.m_v2.wB); break; case 3: pA.setCombine(this.m_v1.a, this.m_v1.wA, this.m_v2.a, this.m_v2.wA); pA.addMul(this.m_v3.a, this.m_v3.wA); pB.set(pA); break; default: _ASSERT && common.assert(false); break; } }; Simplex.prototype.getMetric = function() { switch (this.m_count) { case 0: _ASSERT && common.assert(false); return 0; case 1: return 0; case 2: return Vec2.distance(this.m_v1.w, this.m_v2.w); case 3: return Vec2.cross(Vec2.sub(this.m_v2.w, this.m_v1.w), Vec2.sub(this.m_v3.w, this.m_v1.w)); default: _ASSERT && common.assert(false); return 0; } }; Simplex.prototype.solve = function() { switch (this.m_count) { case 1: break; case 2: this.solve2(); break; case 3: this.solve3(); break; default: _ASSERT && common.assert(false); } }; Simplex.prototype.solve2 = function() { var w1 = this.m_v1.w; var w2 = this.m_v2.w; var e12 = Vec2.sub(w2, w1); var d12_2 = -Vec2.dot(w1, e12); if (d12_2 <= 0) { this.m_v1.a = 1; this.m_count = 1; return; } var d12_1 = Vec2.dot(w2, e12); if (d12_1 <= 0) { this.m_v2.a = 1; this.m_count = 1; this.m_v1.set(this.m_v2); return; } var inv_d12 = 1 / (d12_1 + d12_2); this.m_v1.a = d12_1 * inv_d12; this.m_v2.a = d12_2 * inv_d12; this.m_count = 2; }; Simplex.prototype.solve3 = function() { var w1 = this.m_v1.w; var w2 = this.m_v2.w; var w3 = this.m_v3.w; var e12 = Vec2.sub(w2, w1); var w1e12 = Vec2.dot(w1, e12); var w2e12 = Vec2.dot(w2, e12); var d12_1 = w2e12; var d12_2 = -w1e12; var e13 = Vec2.sub(w3, w1); var w1e13 = Vec2.dot(w1, e13); var w3e13 = Vec2.dot(w3, e13); var d13_1 = w3e13; var d13_2 = -w1e13; var e23 = Vec2.sub(w3, w2); var w2e23 = Vec2.dot(w2, e23); var w3e23 = Vec2.dot(w3, e23); var d23_1 = w3e23; var d23_2 = -w2e23; var n123 = Vec2.cross(e12, e13); var d123_1 = n123 * Vec2.cross(w2, w3); var d123_2 = n123 * Vec2.cross(w3, w1); var d123_3 = n123 * Vec2.cross(w1, w2); if (d12_2 <= 0 && d13_2 <= 0) { this.m_v1.a = 1; this.m_count = 1; return; } if (d12_1 > 0 && d12_2 > 0 && d123_3 <= 0) { var inv_d12 = 1 / (d12_1 + d12_2); this.m_v1.a = d12_1 * inv_d12; this.m_v2.a = d12_2 * inv_d12; this.m_count = 2; return; } if (d13_1 > 0 && d13_2 > 0 && d123_2 <= 0) { var inv_d13 = 1 / (d13_1 + d13_2); this.m_v1.a = d13_1 * inv_d13; this.m_v3.a = d13_2 * inv_d13; this.m_count = 2; this.m_v2.set(this.m_v3); return; } if (d12_1 <= 0 && d23_2 <= 0) { this.m_v2.a = 1; this.m_count = 1; this.m_v1.set(this.m_v2); return; } if (d13_1 <= 0 && d23_1 <= 0) { this.m_v3.a = 1; this.m_count = 1; this.m_v1.set(this.m_v3); return; } if (d23_1 > 0 && d23_2 > 0 && d123_1 <= 0) { var inv_d23 = 1 / (d23_1 + d23_2); this.m_v2.a = d23_1 * inv_d23; this.m_v3.a = d23_2 * inv_d23; this.m_count = 2; this.m_v1.set(this.m_v3); return; } var inv_d123 = 1 / (d123_1 + d123_2 + d123_3); this.m_v1.a = d123_1 * inv_d123; this.m_v2.a = d123_2 * inv_d123; this.m_v3.a = d123_3 * inv_d123; this.m_count = 3; }; Distance.testOverlap = function(shapeA, indexA, shapeB, indexB, xfA, xfB) { var input = new DistanceInput(); input.proxyA.set(shapeA, indexA); input.proxyB.set(shapeB, indexB); input.transformA = xfA; input.transformB = xfB; input.useRadii = true; var cache = new SimplexCache(); var output = new DistanceOutput(); Distance(output, cache, input); return output.distance < 10 * Math.EPSILON; }; },{"../Settings":7,"../common/Mat22":16,"../common/Mat33":17,"../common/Math":18,"../common/Position":19,"../common/Rot":20,"../common/Sweep":21,"../common/Transform":22,"../common/Vec2":23,"../common/Vec3":24,"../common/Velocity":25,"../common/stats":26,"../util/common":51}],14:[function(require,module,exports){ var _DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; var _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; var Settings = require("../Settings"); var common = require("../util/common"); var Pool = require("../util/Pool"); var Vec2 = require("../common/Vec2"); var Math = require("../common/Math"); var AABB = require("./AABB"); module.exports = DynamicTree; function TreeNode(id) { this.id = id; this.aabb = new AABB(); this.userData = null; this.parent = null; this.child1 = null; this.child2 = null; this.height = -1; this.toString = function() { return this.id + ": " + this.userData; }; } TreeNode.prototype.isLeaf = function() { return this.child1 == null; }; function DynamicTree() { this.m_root = null; this.m_nodes = {}; this.m_lastProxyId = 0; this.m_pool = new Pool({ create: function() { return new TreeNode(); } }); } DynamicTree.prototype.getUserData = function(id) { var node = this.m_nodes[id]; _ASSERT && common.assert(!!node); return node.userData; }; DynamicTree.prototype.getFatAABB = function(id) { var node = this.m_nodes[id]; _ASSERT && common.assert(!!node); return node.aabb; }; DynamicTree.prototype.allocateNode = function() { var node = this.m_pool.allocate(); node.id = ++this.m_lastProxyId; node.userData = null; node.parent = null; node.child1 = null; node.child2 = null; node.height = -1; this.m_nodes[node.id] = node; return node; }; DynamicTree.prototype.freeNode = function(node) { this.m_pool.release(node); node.height = -1; delete this.m_nodes[node.id]; }; DynamicTree.prototype.createProxy = function(aabb, userData) { _ASSERT && common.assert(AABB.isValid(aabb)); var node = this.allocateNode(); node.aabb.set(aabb); AABB.extend(node.aabb, Settings.aabbExtension); node.userData = userData; node.height = 0; this.insertLeaf(node); return node.id; }; DynamicTree.prototype.destroyProxy = function(id) { var node = this.m_nodes[id]; _ASSERT && common.assert(!!node); _ASSERT && common.assert(node.isLeaf()); this.removeLeaf(node); this.freeNode(node); }; DynamicTree.prototype.moveProxy = function(id, aabb, d) { _ASSERT && common.assert(AABB.isValid(aabb)); _ASSERT && common.assert(!d || Vec2.isValid(d)); var node = this.m_nodes[id]; _ASSERT && common.assert(!!node); _ASSERT && common.assert(node.isLeaf()); if (node.aabb.contains(aabb)) { return false; } this.removeLeaf(node); node.aabb.set(aabb); aabb = node.aabb; AABB.extend(aabb, Settings.aabbExtension); if (d.x < 0) { aabb.lowerBound.x += d.x * Settings.aabbMultiplier; } else { aabb.upperBound.x += d.x * Settings.aabbMultiplier; } if (d.y < 0) { aabb.lowerBound.y += d.y * Settings.aabbMultiplier; } else { aabb.upperBound.y += d.y * Settings.aabbMultiplier; } this.insertLeaf(node); return true; }; DynamicTree.prototype.insertLeaf = function(leaf) { _ASSERT && common.assert(AABB.isValid(leaf.aabb)); if (this.m_root == null) { this.m_root = leaf; this.m_root.parent = null; return; } var leafAABB = leaf.aabb; var index = this.m_root; while (index.isLeaf() == false) { var child1 = index.child1; var child2 = index.child2; var area = index.aabb.getPerimeter(); var combinedAABB = new AABB(); combinedAABB.combine(index.aabb, leafAABB); var combinedArea = combinedAABB.getPerimeter(); var cost = 2 * combinedArea; var inheritanceCost = 2 * (combinedArea - area); var cost1; if (child1.isLeaf()) { var aabb = new AABB(); aabb.combine(leafAABB, child1.aabb); cost1 = aabb.getPerimeter() + inheritanceCost; } else { var aabb = new AABB(); aabb.combine(leafAABB, child1.aabb); var oldArea = child1.aabb.getPerimeter(); var newArea = aabb.getPerimeter(); cost1 = newArea - oldArea + inheritanceCost; } var cost2; if (child2.isLeaf()) { var aabb = new AABB(); aabb.combine(leafAABB, child2.aabb); cost2 = aabb.getPerimeter() + inheritanceCost; } else { var aabb = new AABB(); aabb.combine(leafAABB, child2.aabb); var oldArea = child2.aabb.getPerimeter(); var newArea = aabb.getPerimeter(); cost2 = newArea - oldArea + inheritanceCost; } if (cost < cost1 && cost < cost2) { break; } if (cost1 < cost2) { index = child1; } else { index = child2; } } var sibling = index; var oldParent = sibling.parent; var newParent = this.allocateNode(); newParent.parent = oldParent; newParent.userData = null; newParent.aabb.combine(leafAABB, sibling.aabb); newParent.height = sibling.height + 1; if (oldParent != null) { if (oldParent.child1 == sibling) { oldParent.child1 = newParent; } else { oldParent.child2 = newParent; } newParent.child1 = sibling; newParent.child2 = leaf; sibling.parent = newParent; leaf.parent = newParent; } else { newParent.child1 = sibling; newParent.child2 = leaf; sibling.parent = newParent; leaf.parent = newParent; this.m_root = newParent; } index = leaf.parent; while (index != null) { index = this.balance(index); var child1 = index.child1; var child2 = index.child2; _ASSERT && common.assert(child1 != null); _ASSERT && common.assert(child2 != null); index.height = 1 + Math.max(child1.height, child2.height); index.aabb.combine(child1.aabb, child2.aabb); index = index.parent; } }; DynamicTree.prototype.removeLeaf = function(leaf) { if (leaf == this.m_root) { this.m_root = null; return; } var parent = leaf.parent; var grandParent = parent.parent; var sibling; if (parent.child1 == leaf) { sibling = parent.child2; } else { sibling = parent.child1; } if (grandParent != null) { if (grandParent.child1 == parent) { grandParent.child1 = sibling; } else { grandParent.child2 = sibling; } sibling.parent = grandParent; this.freeNode(parent); var index = grandParent; while (index != null) { index = this.balance(index); var child1 = index.child1; var child2 = index.child2; index.aabb.combine(child1.aabb, child2.aabb); index.height = 1 + Math.max(child1.height, child2.height); index = index.parent; } } else { this.m_root = sibling; sibling.parent = null; this.freeNode(parent); } }; DynamicTree.prototype.balance = function(iA) { _ASSERT && common.assert(iA != null); var A = iA; if (A.isLeaf() || A.height < 2) { return iA; } var B = A.child1; var C = A.child2; var balance = C.height - B.height; if (balance > 1) { var F = C.child1; var G = C.child2; C.child1 = A; C.parent = A.parent; A.parent = C; if (C.parent != null) { if (C.parent.child1 == iA) { C.parent.child1 = C; } else { C.parent.child2 = C; } } else { this.m_root = C; } if (F.height > G.height) { C.child2 = F; A.child2 = G; G.parent = A; A.aabb.combine(B.aabb, G.aabb); C.aabb.combine(A.aabb, F.aabb); A.height = 1 + Math.max(B.height, G.height); C.height = 1 + Math.max(A.height, F.height); } else { C.child2 = G; A.child2 = F; F.parent = A; A.aabb.combine(B.aabb, F.aabb); C.aabb.combine(A.aabb, G.aabb); A.height = 1 + Math.max(B.height, F.height); C.height = 1 + Math.max(A.height, G.height); } return C; } if (balance < -1) { var D = B.child1; var E = B.child2; B.child1 = A; B.parent = A.parent; A.parent = B; if (B.parent != null) { if (B.parent.child1 == A) { B.parent.child1 = B; } else { B.parent.child2 = B; } } else { this.m_root = B; } if (D.height > E.height) { B.child2 = D; A.child1 = E; E.parent = A; A.aabb.combine(C.aabb, E.aabb); B.aabb.combine(A.aabb, D.aabb); A.height = 1 + Math.max(C.height, E.height); B.height = 1 + Math.max(A.height, D.height); } else { B.child2 = E; A.child1 = D; D.parent = A; A.aabb.combine(C.aabb, D.aabb); B.aabb.combine(A.aabb, E.aabb); A.height = 1 + Math.max(C.height, D.height); B.height = 1 + Math.max(A.height, E.height); } return B; } return A; }; DynamicTree.prototype.getHeight = function() { if (this.m_root == null) { return 0; } return this.m_root.height; }; DynamicTree.prototype.getAreaRatio = function() { if (this.m_root == null) { return 0; } var root = this.m_root; var rootArea = root.aabb.getPerimeter(); var totalArea = 0; var node, it = iteratorPool.allocate().preorder(); while (node = it.next()) { if (node.height < 0) { continue; } totalArea += node.aabb.getPerimeter(); } iteratorPool.release(it); return totalArea / rootArea; }; DynamicTree.prototype.computeHeight = function(id) { var node; if (typeof id !== "undefined") { node = this.m_nodes[id]; } else { node = this.m_root; } if (node.isLeaf()) { return 0; } var height1 = ComputeHeight(node.child1); var height2 = ComputeHeight(node.child2); return 1 + Math.max(height1, height2); }; DynamicTree.prototype.validateStructure = function(node) { if (node == null) { return; } if (node == this.m_root) { _ASSERT && common.assert(node.parent == null); } var child1 = node.child1; var child2 = node.child2; if (node.isLeaf()) { _ASSERT && common.assert(child1 == null); _ASSERT && common.assert(child2 == null); _ASSERT && common.assert(node.height == 0); return; } _ASSERT && common.assert(child1.parent == node); _ASSERT && common.assert(child2.parent == node); this.validateStructure(child1); this.validateStructure(child2); }; DynamicTree.prototype.validateMetrics = function(node) { if (node == null) { return; } var child1 = node.child1; var child2 = node.child2; if (node.isLeaf()) { _ASSERT && common.assert(child1 == null); _ASSERT && common.assert(child2 == null); _ASSERT && common.assert(node.height == 0); return; } var height1 = this.m_nodes[child1].height; var height2 = this.m_nodes[child2].height; var height = 1 + Math.max(height1, height2); _ASSERT && common.assert(node.height == height); var aabb = new AABB(); aabb.combine(child1.aabb, child2.aabb); _ASSERT && common.assert(AABB.areEqual(aabb, node.aabb)); this.validateMetrics(child1); this.validateMetrics(child2); }; DynamicTree.prototype.validate = function() { ValidateStructure(this.m_root); ValidateMetrics(this.m_root); _ASSERT && common.assert(this.getHeight() == this.computeHeight()); }; DynamicTree.prototype.getMaxBalance = function() { var maxBalance = 0; var node, it = iteratorPool.allocate().preorder(); while (node = it.next()) { if (node.height <= 1) { continue; } _ASSERT && common.assert(node.isLeaf() == false); var balance = Math.abs(node.child2.height - node.child1.height); maxBalance = Math.max(maxBalance, balance); } iteratorPool.release(it); return maxBalance; }; DynamicTree.prototype.rebuildBottomUp = function() { var nodes = []; var count = 0; var node, it = iteratorPool.allocate().preorder(); while (node = it.next()) { if (node.height < 0) { continue; } if (node.isLeaf()) { node.parent = null; nodes[count] = node; ++count; } else { this.freeNode(node); } } iteratorPool.release(it); while (count > 1) { var minCost = Infinity; var iMin = -1, jMin = -1; for (var i = 0; i < count; ++i) { var aabbi = nodes[i].aabb; for (var j = i + 1; j < count; ++j) { var aabbj = nodes[j].aabb; var b = new AABB(); b.combine(aabbi, aabbj); var cost = b.getPerimeter(); if (cost < minCost) { iMin = i; jMin = j; minCost = cost; } } } var child1 = nodes[iMin]; var child2 = nodes[jMin]; var parent = this.allocateNode(); parent.child1 = child1; parent.child2 = child2; parent.height = 1 + Math.max(child1.height, child2.height); parent.aabb.combine(child1.aabb, child2.aabb); parent.parent = null; child1.parent = parent; child2.parent = parent; nodes[jMin] = nodes[count - 1]; nodes[iMin] = parent; --count; } this.m_root = nodes[0]; this.validate(); }; DynamicTree.prototype.shiftOrigin = function(newOrigin) { var node, it = iteratorPool.allocate().preorder(); while (node = it.next()) { var aabb = node.aabb; aabb.lowerBound.x -= newOrigin.x; aabb.lowerBound.y -= newOrigin.y; aabb.lowerBound.x -= newOrigin.x; aabb.lowerBound.y -= newOrigin.y; } iteratorPool.release(it); }; DynamicTree.prototype.query = function(aabb, queryCallback) { _ASSERT && common.assert(typeof queryCallback === "function"); var stack = stackPool.allocate(); stack.push(this.m_root); while (stack.length > 0) { var node = stack.pop(); if (node == null) { continue; } if (AABB.testOverlap(node.aabb, aabb)) { if (node.isLeaf()) { var proceed = queryCallback(node.id); if (proceed == false) { return; } } else { stack.push(node.child1); stack.push(node.child2); } } } stackPool.release(stack); }; DynamicTree.prototype.rayCast = function(input, rayCastCallback) { _ASSERT && common.assert(typeof rayCastCallback === "function"); var p1 = input.p1; var p2 = input.p2; var r = Vec2.sub(p2, p1); _ASSERT && common.assert(r.lengthSquared() > 0); r.normalize(); var v = Vec2.cross(1, r); var abs_v = Vec2.abs(v); var maxFraction = input.maxFraction; var segmentAABB = new AABB(); var t = Vec2.combine(1 - maxFraction, p1, maxFraction, p2); segmentAABB.combine(p1, t); var stack = stackPool.allocate(); var subInput = inputPool.allocate(); stack.push(this.m_root); while (stack.length > 0) { var node = stack.pop(); if (node == null) { continue; } if (AABB.testOverlap(node.aabb, segmentAABB) == false) { continue; } var c = node.aabb.getCenter(); var h = node.aabb.getExtents(); var separation = Math.abs(Vec2.dot(v, Vec2.sub(p1, c))) - Vec2.dot(abs_v, h); if (separation > 0) { continue; } if (node.isLeaf()) { subInput.p1 = Vec2.clone(input.p1); subInput.p2 = Vec2.clone(input.p2); subInput.maxFraction = maxFraction; var value = rayCastCallback(subInput, node.id); if (value == 0) { return; } if (value > 0) { maxFraction = value; t = Vec2.combine(1 - maxFraction, p1, maxFraction, p2); segmentAABB.combine(p1, t); } } else { stack.push(node.child1); stack.push(node.child2); } } stackPool.release(stack); inputPool.release(subInput); }; var inputPool = new Pool({ create: function() { return {}; }, release: function(stack) {} }); var stackPool = new Pool({ create: function() { return []; }, release: function(stack) { stack.length = 0; } }); var iteratorPool = new Pool({ create: function() { return new Iterator(); }, release: function(iterator) { iterator.close(); } }); function Iterator() { var parents = []; var states = []; return { preorder: function(root) { parents.length = 0; parents.push(root); states.length = 0; states.push(0); return this; }, next: function() { while (parents.length > 0) { var i = parents.length - 1; var node = parents[i]; if (states[i] === 0) { states[i] = 1; return node; } if (states[i] === 1) { states[i] = 2; if (node.child1) { parents.push(node.child1); states.push(1); return node.child1; } } if (states[i] === 2) { states[i] = 3; if (node.child2) { parents.push(node.child2); states.push(1); return node.child2; } } parents.pop(); states.pop(); } }, close: function() { parents.length = 0; } }; } },{"../Settings":7,"../common/Math":18,"../common/Vec2":23,"../util/Pool":49,"../util/common":51,"./AABB":11}],15:[function(require,module,exports){ var _DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; var _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = TimeOfImpact; module.exports.Input = TOIInput; module.exports.Output = TOIOutput; var Settings = require("../Settings"); var common = require("../util/common"); var Timer = require("../util/Timer"); var stats = require("../common/stats"); var Math = require("../common/Math"); var Vec2 = require("../common/Vec2"); var Vec3 = require("../common/Vec3"); var Mat22 = require("../common/Mat22"); var Mat33 = require("../common/Mat33"); var Rot = require("../common/Rot"); var Sweep = require("../common/Sweep"); var Transform = require("../common/Transform"); var Velocity = require("../common/Velocity"); var Position = require("../common/Position"); var Distance = require("./Distance"); var DistanceInput = Distance.Input; var DistanceOutput = Distance.Output; var DistanceProxy = Distance.Proxy; var SimplexCache = Distance.Cache; function TOIInput() { this.proxyA = new DistanceProxy(); this.proxyB = new DistanceProxy(); this.sweepA = new Sweep(); this.sweepB = new Sweep(); this.tMax; } TOIOutput.e_unknown = 0; TOIOutput.e_failed = 1; TOIOutput.e_overlapped = 2; TOIOutput.e_touching = 3; TOIOutput.e_separated = 4; function TOIOutput() { this.state; this.t; } stats.toiTime = 0; stats.toiMaxTime = 0; stats.toiCalls = 0; stats.toiIters = 0; stats.toiMaxIters = 0; stats.toiRootIters = 0; stats.toiMaxRootIters = 0; function TimeOfImpact(output, input) { var timer = Timer.now(); ++stats.toiCalls; output.state = TOIOutput.e_unknown; output.t = input.tMax; var proxyA = input.proxyA; var proxyB = input.proxyB; var sweepA = input.sweepA; var sweepB = input.sweepB; sweepA.normalize(); sweepB.normalize(); var tMax = input.tMax; var totalRadius = proxyA.m_radius + proxyB.m_radius; var target = Math.max(Settings.linearSlop, totalRadius - 3 * Settings.linearSlop); var tolerance = .25 * Settings.linearSlop; _ASSERT && common.assert(target > tolerance); var t1 = 0; var k_maxIterations = Settings.maxTOIIterations; var iter = 0; var cache = new SimplexCache(); var distanceInput = new DistanceInput(); distanceInput.proxyA = input.proxyA; distanceInput.proxyB = input.proxyB; distanceInput.useRadii = false; for (;;) { var xfA = Transform.identity(); var xfB = Transform.identity(); sweepA.getTransform(xfA, t1); sweepB.getTransform(xfB, t1); distanceInput.transformA = xfA; distanceInput.transformB = xfB; var distanceOutput = new DistanceOutput(); Distance(distanceOutput, cache, distanceInput); if (distanceOutput.distance <= 0) { output.state = TOIOutput.e_overlapped; output.t = 0; break; } if (distanceOutput.distance < target + tolerance) { output.state = TOIOutput.e_touching; output.t = t1; break; } var fcn = new SeparationFunction(); fcn.initialize(cache, proxyA, sweepA, proxyB, sweepB, t1); if (false) { var N = 100; var dx = 1 / N; var xs = []; var fs = []; var x = 0; for (var i = 0; i <= N; ++i) { sweepA.getTransform(xfA, x); sweepB.getTransform(xfB, x); var f = fcn.evaluate(xfA, xfB) - target; printf("%g %g\n", x, f); xs[i] = x; fs[i] = f; x += dx; } } var done = false; var t2 = tMax; var pushBackIter = 0; for (;;) { var s2 = fcn.findMinSeparation(t2); var indexA = fcn.indexA; var indexB = fcn.indexB; if (s2 > target + tolerance) { output.state = TOIOutput.e_separated; output.t = tMax; done = true; break; } if (s2 > target - tolerance) { t1 = t2; break; } var s1 = fcn.evaluate(t1); var indexA = fcn.indexA; var indexB = fcn.indexB; if (s1 < target - tolerance) { output.state = TOIOutput.e_failed; output.t = t1; done = true; break; } if (s1 <= target + tolerance) { output.state = TOIOutput.e_touching; output.t = t1; done = true; break; } var rootIterCount = 0; var a1 = t1, a2 = t2; for (;;) { var t; if (rootIterCount & 1) { t = a1 + (target - s1) * (a2 - a1) / (s2 - s1); } else { t = .5 * (a1 + a2); } ++rootIterCount; ++stats.toiRootIters; var s = fcn.evaluate(t); var indexA = fcn.indexA; var indexB = fcn.indexB; if (Math.abs(s - target) < tolerance) { t2 = t; break; } if (s > target) { a1 = t; s1 = s; } else { a2 = t; s2 = s; } if (rootIterCount == 50) { break; } } stats.toiMaxRootIters = Math.max(stats.toiMaxRootIters, rootIterCount); ++pushBackIter; if (pushBackIter == Settings.maxPolygonVertices) { break; } } ++iter; ++stats.toiIters; if (done) { break; } if (iter == k_maxIterations) { output.state = TOIOutput.e_failed; output.t = t1; break; } } stats.toiMaxIters = Math.max(stats.toiMaxIters, iter); var time = Timer.diff(timer); stats.toiMaxTime = Math.max(stats.toiMaxTime, time); stats.toiTime += time; } var e_points = 1; var e_faceA = 2; var e_faceB = 3; function SeparationFunction() { this.m_proxyA = new DistanceProxy(); this.m_proxyB = new DistanceProxy(); this.m_sweepA; this.m_sweepB; this.m_type; this.m_localPoint = Vec2.zero(); this.m_axis = Vec2.zero(); } SeparationFunction.prototype.initialize = function(cache, proxyA, sweepA, proxyB, sweepB, t1) { this.m_proxyA = proxyA; this.m_proxyB = proxyB; var count = cache.count; _ASSERT && common.assert(0 < count && count < 3); this.m_sweepA = sweepA; this.m_sweepB = sweepB; var xfA = Transform.identity(); var xfB = Transform.identity(); this.m_sweepA.getTransform(xfA, t1); this.m_sweepB.getTransform(xfB, t1); if (count == 1) { this.m_type = e_points; var localPointA = this.m_proxyA.getVertex(cache.indexA[0]); var localPointB = this.m_proxyB.getVertex(cache.indexB[0]); var pointA = Transform.mul(xfA, localPointA); var pointB = Transform.mul(xfB, localPointB); this.m_axis.setCombine(1, pointB, -1, pointA); var s = this.m_axis.normalize(); return s; } else if (cache.indexA[0] == cache.indexA[1]) { this.m_type = e_faceB; var localPointB1 = proxyB.getVertex(cache.indexB[0]); var localPointB2 = proxyB.getVertex(cache.indexB[1]); this.m_axis = Vec2.cross(Vec2.sub(localPointB2, localPointB1), 1); this.m_axis.normalize(); var normal = Rot.mul(xfB.q, this.m_axis); this.m_localPoint = Vec2.mid(localPointB1, localPointB2); var pointB = Transform.mul(xfB, this.m_localPoint); var localPointA = proxyA.getVertex(cache.indexA[0]); var pointA = Transform.mul(xfA, localPointA); var s = Vec2.dot(pointA, normal) - Vec2.dot(pointB, normal); if (s < 0) { this.m_axis = Vec2.neg(this.m_axis); s = -s; } return s; } else { this.m_type = e_faceA; var localPointA1 = this.m_proxyA.getVertex(cache.indexA[0]); var localPointA2 = this.m_proxyA.getVertex(cache.indexA[1]); this.m_axis = Vec2.cross(Vec2.sub(localPointA2, localPointA1), 1); this.m_axis.normalize(); var normal = Rot.mul(xfA.q, this.m_axis); this.m_localPoint = Vec2.mid(localPointA1, localPointA2); var pointA = Transform.mul(xfA, this.m_localPoint); var localPointB = this.m_proxyB.getVertex(cache.indexB[0]); var pointB = Transform.mul(xfB, localPointB); var s = Vec2.dot(pointB, normal) - Vec2.dot(pointA, normal); if (s < 0) { this.m_axis = Vec2.neg(this.m_axis); s = -s; } return s; } }; SeparationFunction.prototype.compute = function(find, t) { var xfA = Transform.identity(); var xfB = Transform.identity(); this.m_sweepA.getTransform(xfA, t); this.m_sweepB.getTransform(xfB, t); switch (this.m_type) { case e_points: { if (find) { var axisA = Rot.mulT(xfA.q, this.m_axis); var axisB = Rot.mulT(xfB.q, Vec2.neg(this.m_axis)); this.indexA = this.m_proxyA.getSupport(axisA); this.indexB = this.m_proxyB.getSupport(axisB); } var localPointA = this.m_proxyA.getVertex(this.indexA); var localPointB = this.m_proxyB.getVertex(this.indexB); var pointA = Transform.mul(xfA, localPointA); var pointB = Transform.mul(xfB, localPointB); var sep = Vec2.dot(pointB, this.m_axis) - Vec2.dot(pointA, this.m_axis); return sep; } case e_faceA: { var normal = Rot.mul(xfA.q, this.m_axis); var pointA = Transform.mul(xfA, this.m_localPoint); if (find) { var axisB = Rot.mulT(xfB.q, Vec2.neg(normal)); this.indexA = -1; this.indexB = this.m_proxyB.getSupport(axisB); } var localPointB = this.m_proxyB.getVertex(this.indexB); var pointB = Transform.mul(xfB, localPointB); var sep = Vec2.dot(pointB, normal) - Vec2.dot(pointA, normal); return sep; } case e_faceB: { var normal = Rot.mul(xfB.q, this.m_axis); var pointB = Transform.mul(xfB, this.m_localPoint); if (find) { var axisA = Rot.mulT(xfA.q, Vec2.neg(normal)); this.indexB = -1; this.indexA = this.m_proxyA.getSupport(axisA); } var localPointA = this.m_proxyA.getVertex(this.indexA); var pointA = Transform.mul(xfA, localPointA); var sep = Vec2.dot(pointA, normal) - Vec2.dot(pointB, normal); return sep; } default: _ASSERT && common.assert(false); if (find) { this.indexA = -1; this.indexB = -1; } return 0; } }; SeparationFunction.prototype.findMinSeparation = function(t) { return this.compute(true, t); }; SeparationFunction.prototype.evaluate = function(t) { return this.compute(false, t); }; },{"../Settings":7,"../common/Mat22":16,"../common/Mat33":17,"../common/Math":18,"../common/Position":19,"../common/Rot":20,"../common/Sweep":21,"../common/Transform":22,"../common/Vec2":23,"../common/Vec3":24,"../common/Velocity":25,"../common/stats":26,"../util/Timer":50,"../util/common":51,"./Distance":13}],16:[function(require,module,exports){ var _DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; var _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = Mat22; var common = require("../util/common"); var Math = require("./Math"); var Vec2 = require("./Vec2"); function Mat22(a, b, c, d) { if (typeof a === "object" && a !== null) { this.ex = Vec2.clone(a); this.ey = Vec2.clone(b); } else if (typeof a === "number") { this.ex = Vec2.neo(a, c); this.ey = Vec2.neo(b, d); } else { this.ex = Vec2.zero(); this.ey = Vec2.zero(); } } Mat22.prototype.toString = function() { return JSON.stringify(this); }; Mat22.isValid = function(o) { return o && Vec2.isValid(o.ex) && Vec2.isValid(o.ey); }; Mat22.assert = function(o) { if (!_ASSERT) return; if (!Mat22.isValid(o)) { _DEBUG && common.debug(o); throw new Error("Invalid Mat22!"); } }; Mat22.prototype.set = function(a, b, c, d) { if (typeof a === "number" && typeof b === "number" && typeof c === "number" && typeof d === "number") { this.ex.set(a, c); this.ey.set(b, d); } else if (typeof a === "object" && typeof b === "object") { this.ex.set(a); this.ey.set(b); } else if (typeof a === "object") { _ASSERT && Mat22.assert(a); this.ex.set(a.ex); this.ey.set(a.ey); } else { _ASSERT && common.assert(false); } }; Mat22.prototype.setIdentity = function() { this.ex.x = 1; this.ey.x = 0; this.ex.y = 0; this.ey.y = 1; }; Mat22.prototype.setZero = function() { this.ex.x = 0; this.ey.x = 0; this.ex.y = 0; this.ey.y = 0; }; Mat22.prototype.getInverse = function() { var a = this.ex.x; var b = this.ey.x; var c = this.ex.y; var d = this.ey.y; var det = a * d - b * c; if (det != 0) { det = 1 / det; } var imx = new Mat22(); imx.ex.x = det * d; imx.ey.x = -det * b; imx.ex.y = -det * c; imx.ey.y = det * a; return imx; }; Mat22.prototype.solve = function(v) { _ASSERT && Vec2.assert(v); var a = this.ex.x; var b = this.ey.x; var c = this.ex.y; var d = this.ey.y; var det = a * d - b * c; if (det != 0) { det = 1 / det; } var w = Vec2.zero(); w.x = det * (d * v.x - b * v.y); w.y = det * (a * v.y - c * v.x); return w; }; Mat22.mul = function(mx, v) { if (v && "x" in v && "y" in v) { _ASSERT && Vec2.assert(v); var x = mx.ex.x * v.x + mx.ey.x * v.y; var y = mx.ex.y * v.x + mx.ey.y * v.y; return Vec2.neo(x, y); } else if (v && "ex" in v && "ey" in v) { _ASSERT && Mat22.assert(v); return new Mat22(Vec2.mul(mx, v.ex), Vec2.mul(mx, v.ey)); } _ASSERT && common.assert(false); }; Mat22.mulT = function(mx, v) { if (v && "x" in v && "y" in v) { _ASSERT && Vec2.assert(v); return Vec2.neo(Vec2.dot(v, mx.ex), Vec2.dot(v, mx.ey)); } else if (v && "ex" in v && "ey" in v) { _ASSERT && Mat22.assert(v); var c1 = Vec2.neo(Vec2.dot(mx.ex, v.ex), Vec2.dot(mx.ey, v.ex)); var c2 = Vec2.neo(Vec2.dot(mx.ex, v.ey), Vec2.dot(mx.ey, v.ey)); return new Mat22(c1, c2); } _ASSERT && common.assert(false); }; Mat22.abs = function(mx) { _ASSERT && Mat22.assert(mx); return new Mat22(Vec2.abs(mx.ex), Vec2.abs(mx.ey)); }; Mat22.add = function(mx1, mx2) { _ASSERT && Mat22.assert(mx1); _ASSERT && Mat22.assert(mx2); return new Mat22(Vec2.add(mx1.ex + mx2.ex), Vec2.add(mx1.ey + mx2.ey)); }; },{"../util/common":51,"./Math":18,"./Vec2":23}],17:[function(require,module,exports){ var _DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; var _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = Mat33; var common = require("../util/common"); var Math = require("./Math"); var Vec2 = require("./Vec2"); var Vec3 = require("./Vec3"); function Mat33(a, b, c) { if (typeof a === "object" && a !== null) { this.ex = Vec3.clone(a); this.ey = Vec3.clone(b); this.ez = Vec3.clone(c); } else { this.ex = Vec3(); this.ey = Vec3(); this.ez = Vec3(); } } Mat33.prototype.toString = function() { return JSON.stringify(this); }; Mat33.isValid = function(o) { return o && Vec3.isValid(o.ex) && Vec3.isValid(o.ey) && Vec3.isValid(o.ez); }; Mat33.assert = function(o) { if (!_ASSERT) return; if (!Mat33.isValid(o)) { _DEBUG && common.debug(o); throw new Error("Invalid Mat33!"); } }; Mat33.prototype.setZero = function() { this.ex.setZero(); this.ey.setZero(); this.ez.setZero(); return this; }; Mat33.prototype.solve33 = function(v) { var det = Vec3.dot(this.ex, Vec3.cross(this.ey, this.ez)); if (det != 0) { det = 1 / det; } var r = new Vec3(); r.x = det * Vec3.dot(v, Vec3.cross(this.ey, this.ez)); r.y = det * Vec3.dot(this.ex, Vec3.cross(v, this.ez)); r.z = det * Vec3.dot(this.ex, Vec3.cross(this.ey, v)); return r; }; Mat33.prototype.solve22 = function(v) { var a11 = this.ex.x; var a12 = this.ey.x; var a21 = this.ex.y; var a22 = this.ey.y; var det = a11 * a22 - a12 * a21; if (det != 0) { det = 1 / det; } var r = Vec2.zero(); r.x = det * (a22 * v.x - a12 * v.y); r.y = det * (a11 * v.y - a21 * v.x); return r; }; Mat33.prototype.getInverse22 = function(M) { var a = this.ex.x; var b = this.ey.x; var c = this.ex.y; var d = this.ey.y; var det = a * d - b * c; if (det != 0) { det = 1 / det; } M.ex.x = det * d; M.ey.x = -det * b; M.ex.z = 0; M.ex.y = -det * c; M.ey.y = det * a; M.ey.z = 0; M.ez.x = 0; M.ez.y = 0; M.ez.z = 0; }; Mat33.prototype.getSymInverse33 = function(M) { var det = Vec3.dot(this.ex, Vec3.cross(this.ey, this.ez)); if (det != 0) { det = 1 / det; } var a11 = this.ex.x; var a12 = this.ey.x; var a13 = this.ez.x; var a22 = this.ey.y; var a23 = this.ez.y; var a33 = this.ez.z; M.ex.x = det * (a22 * a33 - a23 * a23); M.ex.y = det * (a13 * a23 - a12 * a33); M.ex.z = det * (a12 * a23 - a13 * a22); M.ey.x = M.ex.y; M.ey.y = det * (a11 * a33 - a13 * a13); M.ey.z = det * (a13 * a12 - a11 * a23); M.ez.x = M.ex.z; M.ez.y = M.ey.z; M.ez.z = det * (a11 * a22 - a12 * a12); }; Mat33.mul = function(a, b) { _ASSERT && Mat33.assert(a); if (b && "z" in b && "y" in b && "x" in b) { _ASSERT && Vec3.assert(b); var x = a.ex.x * b.x + a.ey.x * b.y + a.ez.x * b.z; var y = a.ex.y * b.x + a.ey.y * b.y + a.ez.y * b.z; var z = a.ex.z * b.x + a.ey.z * b.y + a.ez.z * b.z; return new Vec3(x, y, z); } else if (b && "y" in b && "x" in b) { _ASSERT && Vec2.assert(b); var x = a.ex.x * b.x + a.ey.x * b.y; var y = a.ex.y * b.x + a.ey.y * b.y; return Vec2.neo(x, y); } _ASSERT && common.assert(false); }; Mat33.add = function(a, b) { _ASSERT && Mat33.assert(a); _ASSERT && Mat33.assert(b); return new Vec3(a.x + b.x, a.y + b.y, a.z + b.z); }; },{"../util/common":51,"./Math":18,"./Vec2":23,"./Vec3":24}],18:[function(require,module,exports){ var _DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; var _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; var common = require("../util/common"); var create = require("../util/create"); var native = Math; var math = module.exports = create(native); math.EPSILON = 1e-9; math.isFinite = function(x) { return typeof x === "number" && isFinite(x) && !isNaN(x); }; math.assert = function(x) { if (!_ASSERT) return; if (!math.isFinite(x)) { _DEBUG && common.debug(x); throw new Error("Invalid Number!"); } }; math.invSqrt = function(x) { return 1 / native.sqrt(x); }; math.nextPowerOfTwo = function(x) { x |= x >> 1; x |= x >> 2; x |= x >> 4; x |= x >> 8; x |= x >> 16; return x + 1; }; math.isPowerOfTwo = function(x) { return x > 0 && (x & x - 1) == 0; }; math.mod = function(num, min, max) { if (typeof min === "undefined") { max = 1, min = 0; } else if (typeof max === "undefined") { max = min, min = 0; } if (max > min) { num = (num - min) % (max - min); return num + (num < 0 ? max : min); } else { num = (num - max) % (min - max); return num + (num <= 0 ? min : max); } }; math.clamp = function(num, min, max) { if (num < min) { return min; } else if (num > max) { return max; } else { return num; } }; math.random = function(min, max) { if (typeof min === "undefined") { max = 1; min = 0; } else if (typeof max === "undefined") { max = min; min = 0; } return min == max ? min : native.random() * (max - min) + min; }; },{"../util/common":51,"../util/create":52}],19:[function(require,module,exports){ var _DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; var _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = Position; var Vec2 = require("./Vec2"); var Rot = require("./Rot"); function Position() { this.c = Vec2.zero(); this.a = 0; } Position.prototype.getTransform = function(xf, p) { xf.q.set(this.a); xf.p.set(Vec2.sub(this.c, Rot.mul(xf.q, p))); return xf; }; },{"./Rot":20,"./Vec2":23}],20:[function(require,module,exports){ var _DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; var _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = Rot; var common = require("../util/common"); var Vec2 = require("./Vec2"); var Math = require("./Math"); function Rot(angle) { if (!(this instanceof Rot)) { return new Rot(angle); } if (typeof angle === "number") { this.setAngle(angle); } else if (typeof angle === "object") { this.set(angle); } else { this.setIdentity(); } } Rot.neo = function(angle) { var obj = Object.create(Rot.prototype); obj.setAngle(angle); return obj; }; Rot.clone = function(rot) { _ASSERT && Rot.assert(rot); var obj = Object.create(Rot.prototype); obj.s = rot.s; obj.c = rot.c; return obj; }; Rot.identity = function() { var obj = Object.create(Rot.prototype); obj.s = 0; obj.c = 1; return obj; }; Rot.isValid = function(o) { return o && Math.isFinite(o.s) && Math.isFinite(o.c); }; Rot.assert = function(o) { if (!_ASSERT) return; if (!Rot.isValid(o)) { _DEBUG && common.debug(o); throw new Error("Invalid Rot!"); } }; Rot.prototype.setIdentity = function() { this.s = 0; this.c = 1; }; Rot.prototype.set = function(angle) { if (typeof angle === "object") { _ASSERT && Rot.assert(angle); this.s = angle.s; this.c = angle.c; } else { _ASSERT && Math.assert(angle); this.s = Math.sin(angle); this.c = Math.cos(angle); } }; Rot.prototype.setAngle = function(angle) { _ASSERT && Math.assert(angle); this.s = Math.sin(angle); this.c = Math.cos(angle); }; Rot.prototype.getAngle = function() { return Math.atan2(this.s, this.c); }; Rot.prototype.getXAxis = function() { return Vec2.neo(this.c, this.s); }; Rot.prototype.getYAxis = function() { return Vec2.neo(-this.s, this.c); }; Rot.mul = function(rot, m) { _ASSERT && Rot.assert(rot); if ("c" in m && "s" in m) { _ASSERT && Rot.assert(m); var qr = Rot.identity(); qr.s = rot.s * m.c + rot.c * m.s; qr.c = rot.c * m.c - rot.s * m.s; return qr; } else if ("x" in m && "y" in m) { _ASSERT && Vec2.assert(m); return Vec2.neo(rot.c * m.x - rot.s * m.y, rot.s * m.x + rot.c * m.y); } }; Rot.mulSub = function(rot, v, w) { var x = rot.c * (v.x - w.x) - rot.s * (v.y - w.y); var y = rot.s * (v.x - w.y) + rot.c * (v.y - w.y); return Vec2.neo(x, y); }; Rot.mulT = function(rot, m) { if ("c" in m && "s" in m) { _ASSERT && Rot.assert(m); var qr = Rot.identity(); qr.s = rot.c * m.s - rot.s * m.c; qr.c = rot.c * m.c + rot.s * m.s; return qr; } else if ("x" in m && "y" in m) { _ASSERT && Vec2.assert(m); return Vec2.neo(rot.c * m.x + rot.s * m.y, -rot.s * m.x + rot.c * m.y); } }; },{"../util/common":51,"./Math":18,"./Vec2":23}],21:[function(require,module,exports){ var _DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; var _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = Sweep; var common = require("../util/common"); var Math = require("./Math"); var Vec2 = require("./Vec2"); var Rot = require("./Rot"); var Transform = require("./Transform"); function Sweep(c, a) { _ASSERT && common.assert(typeof c === "undefined"); _ASSERT && common.assert(typeof a === "undefined"); this.localCenter = Vec2.zero(); this.c = Vec2.zero(); this.a = 0; this.alpha0 = 0; this.c0 = Vec2.zero(); this.a0 = 0; } Sweep.prototype.setTransform = function(xf) { var c = Transform.mul(xf, this.localCenter); this.c.set(c); this.c0.set(c); this.a = xf.q.getAngle(); this.a0 = xf.q.getAngle(); }; Sweep.prototype.setLocalCenter = function(localCenter, xf) { this.localCenter.set(localCenter); var c = Transform.mul(xf, this.localCenter); this.c.set(c); this.c0.set(c); }; Sweep.prototype.getTransform = function(xf, beta) { beta = typeof beta === "undefined" ? 0 : beta; xf.q.setAngle((1 - beta) * this.a0 + beta * this.a); xf.p.setCombine(1 - beta, this.c0, beta, this.c); xf.p.sub(Rot.mul(xf.q, this.localCenter)); }; Sweep.prototype.advance = function(alpha) { _ASSERT && common.assert(this.alpha0 < 1); var beta = (alpha - this.alpha0) / (1 - this.alpha0); this.c0.setCombine(beta, this.c, 1 - beta, this.c0); this.a0 = beta * this.a + (1 - beta) * this.a0; this.alpha0 = alpha; }; Sweep.prototype.forward = function() { this.a0 = this.a; this.c0.set(this.c); }; Sweep.prototype.normalize = function() { var a0 = Math.mod(this.a0, -Math.PI, +Math.PI); this.a -= this.a0 - a0; this.a0 = a0; }; Sweep.prototype.clone = function() { var clone = new Sweep(); clone.localCenter.set(this.localCenter); clone.alpha0 = this.alpha0; clone.a0 = this.a0; clone.a = this.a; clone.c0.set(this.c0); clone.c.set(this.c); return clone; }; Sweep.prototype.set = function(that) { this.localCenter.set(that.localCenter); this.alpha0 = that.alpha0; this.a0 = that.a0; this.a = that.a; this.c0.set(that.c0); this.c.set(that.c); }; },{"../util/common":51,"./Math":18,"./Rot":20,"./Transform":22,"./Vec2":23}],22:[function(require,module,exports){ var _DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; var _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = Transform; var common = require("../util/common"); var Vec2 = require("./Vec2"); var Rot = require("./Rot"); function Transform(position, rotation) { if (!(this instanceof Transform)) { return new Transform(position, rotation); } this.p = Vec2.zero(); this.q = Rot.identity(); if (typeof position !== "undefined") { this.p.set(position); } if (typeof rotation !== "undefined") { this.q.set(rotation); } } Transform.clone = function(xf) { var obj = Object.create(Transform.prototype); obj.p = Vec2.clone(xf.p); obj.q = Rot.clone(xf.q); return obj; }; Transform.neo = function(position, rotation) { var obj = Object.create(Transform.prototype); obj.p = Vec2.clone(position); obj.q = Rot.clone(rotation); return obj; }; Transform.identity = function() { var obj = Object.create(Transform.prototype); obj.p = Vec2.zero(); obj.q = Rot.identity(); return obj; }; Transform.prototype.setIdentity = function() { this.p.setZero(); this.q.setIdentity(); }; Transform.prototype.set = function(a, b) { if (Transform.isValid(a)) { this.p.set(a.p); this.q.set(a.q); } else { this.p.set(a); this.q.set(b); } }; Transform.isValid = function(o) { return o && Vec2.isValid(o.p) && Rot.isValid(o.q); }; Transform.assert = function(o) { if (!_ASSERT) return; if (!Transform.isValid(o)) { _DEBUG && common.debug(o); throw new Error("Invalid Transform!"); } }; Transform.mul = function(a, b) { _ASSERT && Transform.assert(a); if (Array.isArray(b)) { var arr = []; for (var i = 0; i < b.length; i++) { arr[i] = Transform.mul(a, b[i]); } return arr; } else if ("x" in b && "y" in b) { _ASSERT && Vec2.assert(b); var x = a.q.c * b.x - a.q.s * b.y + a.p.x; var y = a.q.s * b.x + a.q.c * b.y + a.p.y; return Vec2.neo(x, y); } else if ("p" in b && "q" in b) { _ASSERT && Transform.assert(b); var xf = Transform.identity(); xf.q = Rot.mul(a.q, b.q); xf.p = Vec2.add(Rot.mul(a.q, b.p), a.p); return xf; } }; Transform.mulT = function(a, b) { _ASSERT && Transform.assert(a); if ("x" in b && "y" in b) { _ASSERT && Vec2.assert(b); var px = b.x - a.p.x; var py = b.y - a.p.y; var x = a.q.c * px + a.q.s * py; var y = -a.q.s * px + a.q.c * py; return Vec2.neo(x, y); } else if ("p" in b && "q" in b) { _ASSERT && Transform.assert(b); var xf = Transform.identity(); xf.q.set(Rot.mulT(a.q, b.q)); xf.p.set(Rot.mulT(a.q, Vec2.sub(b.p, a.p))); return xf; } }; },{"../util/common":51,"./Rot":20,"./Vec2":23}],23:[function(require,module,exports){ var _DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; var _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = Vec2; var common = require("../util/common"); var Math = require("./Math"); function Vec2(x, y) { if (!(this instanceof Vec2)) { return new Vec2(x, y); } if (typeof x === "undefined") { this.x = 0; this.y = 0; } else if (typeof x === "object") { this.x = x.x; this.y = x.y; } else { this.x = x; this.y = y; } _ASSERT && Vec2.assert(this); } Vec2.zero = function() { var obj = Object.create(Vec2.prototype); obj.x = 0; obj.y = 0; return obj; }; Vec2.neo = function(x, y) { var obj = Object.create(Vec2.prototype); obj.x = x; obj.y = y; return obj; }; Vec2.clone = function(v, depricated) { _ASSERT && Vec2.assert(v); _ASSERT && common.assert(!depricated); return Vec2.neo(v.x, v.y); }; Vec2.prototype.toString = function() { return JSON.stringify(this); }; Vec2.isValid = function(v) { return v && Math.isFinite(v.x) && Math.isFinite(v.y); }; Vec2.assert = function(o) { if (!_ASSERT) return; if (!Vec2.isValid(o)) { _DEBUG && common.debug(o); throw new Error("Invalid Vec2!"); } }; Vec2.prototype.clone = function(depricated) { return Vec2.clone(this, depricated); }; Vec2.prototype.setZero = function() { this.x = 0; this.y = 0; return this; }; Vec2.prototype.set = function(x, y) { if (typeof x === "object") { _ASSERT && Vec2.assert(x); this.x = x.x; this.y = x.y; } else { _ASSERT && Math.assert(x); _ASSERT && Math.assert(y); this.x = x; this.y = y; } return this; }; Vec2.prototype.wSet = function(a, v, b, w) { if (typeof b !== "undefined" || typeof w !== "undefined") { return this.setCombine(a, v, b, w); } else { return this.setMul(a, v); } }; Vec2.prototype.setCombine = function(a, v, b, w) { _ASSERT && Math.assert(a); _ASSERT && Vec2.assert(v); _ASSERT && Math.assert(b); _ASSERT && Vec2.assert(w); var x = a * v.x + b * w.x; var y = a * v.y + b * w.y; this.x = x; this.y = y; return this; }; Vec2.prototype.setMul = function(a, v, b, w) { _ASSERT && Math.assert(a); _ASSERT && Vec2.assert(v); var x = a * v.x; var y = a * v.y; this.x = x; this.y = y; return this; }; Vec2.prototype.add = function(w) { _ASSERT && Vec2.assert(w); this.x += w.x; this.y += w.y; return this; }; Vec2.prototype.wAdd = function(a, v, b, w) { if (typeof b !== "undefined" || typeof w !== "undefined") { return this.addCombine(a, v, b, w); } else { return this.addMul(a, v); } }; Vec2.prototype.addCombine = function(a, v, b, w) { _ASSERT && Math.assert(a); _ASSERT && Vec2.assert(v); _ASSERT && Math.assert(b); _ASSERT && Vec2.assert(w); var x = a * v.x + b * w.x; var y = a * v.y + b * w.y; this.x += x; this.y += y; return this; }; Vec2.prototype.addMul = function(a, v) { _ASSERT && Math.assert(a); _ASSERT && Vec2.assert(v); var x = a * v.x; var y = a * v.y; this.x += x; this.y += y; return this; }; Vec2.prototype.wSub = function(a, v, b, w) { if (typeof b !== "undefined" || typeof w !== "undefined") { return this.subCombine(a, v, b, w); } else { return this.subMul(a, v); } }; Vec2.prototype.subCombine = function(a, v, b, w) { _ASSERT && Math.assert(a); _ASSERT && Vec2.assert(v); _ASSERT && Math.assert(b); _ASSERT && Vec2.assert(w); var x = a * v.x + b * w.x; var y = a * v.y + b * w.y; this.x -= x; this.y -= y; return this; }; Vec2.prototype.subMul = function(a, v) { _ASSERT && Math.assert(a); _ASSERT && Vec2.assert(v); var x = a * v.x; var y = a * v.y; this.x -= x; this.y -= y; return this; }; Vec2.prototype.sub = function(w) { _ASSERT && Vec2.assert(w); this.x -= w.x; this.y -= w.y; return this; }; Vec2.prototype.mul = function(m) { _ASSERT && Math.assert(m); this.x *= m; this.y *= m; return this; }; Vec2.prototype.length = function() { return Vec2.lengthOf(this); }; Vec2.prototype.lengthSquared = function() { return Vec2.lengthSquared(this); }; Vec2.prototype.normalize = function() { var length = this.length(); if (length < Math.EPSILON) { return 0; } var invLength = 1 / length; this.x *= invLength; this.y *= invLength; return length; }; Vec2.lengthOf = function(v) { _ASSERT && Vec2.assert(v); return Math.sqrt(v.x * v.x + v.y * v.y); }; Vec2.lengthSquared = function(v) { _ASSERT && Vec2.assert(v); return v.x * v.x + v.y * v.y; }; Vec2.distance = function(v, w) { _ASSERT && Vec2.assert(v); _ASSERT && Vec2.assert(w); var dx = v.x - w.x, dy = v.y - w.y; return Math.sqrt(dx * dx + dy * dy); }; Vec2.distanceSquared = function(v, w) { _ASSERT && Vec2.assert(v); _ASSERT && Vec2.assert(w); var dx = v.x - w.x, dy = v.y - w.y; return dx * dx + dy * dy; }; Vec2.areEqual = function(v, w) { _ASSERT && Vec2.assert(v); _ASSERT && Vec2.assert(w); return v == w || typeof w === "object" && w !== null && v.x === w.x && v.y === w.y; }; Vec2.skew = function(v) { _ASSERT && Vec2.assert(v); return Vec2.neo(-v.y, v.x); }; Vec2.dot = function(v, w) { _ASSERT && Vec2.assert(v); _ASSERT && Vec2.assert(w); return v.x * w.x + v.y * w.y; }; Vec2.cross = function(v, w) { if (typeof w === "number") { _ASSERT && Vec2.assert(v); _ASSERT && Math.assert(w); return Vec2.neo(w * v.y, -w * v.x); } else if (typeof v === "number") { _ASSERT && Math.assert(v); _ASSERT && Vec2.assert(w); return Vec2.neo(-v * w.y, v * w.x); } else { _ASSERT && Vec2.assert(v); _ASSERT && Vec2.assert(w); return v.x * w.y - v.y * w.x; } }; Vec2.addCross = function(a, v, w) { if (typeof w === "number") { _ASSERT && Vec2.assert(v); _ASSERT && Math.assert(w); return Vec2.neo(w * v.y + a.x, -w * v.x + a.y); } else if (typeof v === "number") { _ASSERT && Math.assert(v); _ASSERT && Vec2.assert(w); return Vec2.neo(-v * w.y + a.x, v * w.x + a.y); } _ASSERT && common.assert(false); }; Vec2.add = function(v, w) { _ASSERT && Vec2.assert(v); _ASSERT && Vec2.assert(w); return Vec2.neo(v.x + w.x, v.y + w.y); }; Vec2.wAdd = function(a, v, b, w) { if (typeof b !== "undefined" || typeof w !== "undefined") { return Vec2.combine(a, v, b, w); } else { return Vec2.mul(a, v); } }; Vec2.combine = function(a, v, b, w) { return Vec2.zero().setCombine(a, v, b, w); }; Vec2.sub = function(v, w) { _ASSERT && Vec2.assert(v); _ASSERT && Vec2.assert(w); return Vec2.neo(v.x - w.x, v.y - w.y); }; Vec2.mul = function(a, b) { if (typeof a === "object") { _ASSERT && Vec2.assert(a); _ASSERT && Math.assert(b); return Vec2.neo(a.x * b, a.y * b); } else if (typeof b === "object") { _ASSERT && Math.assert(a); _ASSERT && Vec2.assert(b); return Vec2.neo(a * b.x, a * b.y); } }; Vec2.prototype.neg = function() { this.x = -this.x; this.y = -this.y; return this; }; Vec2.neg = function(v) { _ASSERT && Vec2.assert(v); return Vec2.neo(-v.x, -v.y); }; Vec2.abs = function(v) { _ASSERT && Vec2.assert(v); return Vec2.neo(Math.abs(v.x), Math.abs(v.y)); }; Vec2.mid = function(v, w) { _ASSERT && Vec2.assert(v); _ASSERT && Vec2.assert(w); return Vec2.neo((v.x + w.x) * .5, (v.y + w.y) * .5); }; Vec2.upper = function(v, w) { _ASSERT && Vec2.assert(v); _ASSERT && Vec2.assert(w); return Vec2.neo(Math.max(v.x, w.x), Math.max(v.y, w.y)); }; Vec2.lower = function(v, w) { _ASSERT && Vec2.assert(v); _ASSERT && Vec2.assert(w); return Vec2.neo(Math.min(v.x, w.x), Math.min(v.y, w.y)); }; Vec2.prototype.clamp = function(max) { var lengthSqr = this.x * this.x + this.y * this.y; if (lengthSqr > max * max) { var invLength = Math.invSqrt(lengthSqr); this.x *= invLength * max; this.y *= invLength * max; } return this; }; Vec2.clamp = function(v, max) { v = Vec2.neo(v.x, v.y); v.clamp(max); return v; }; },{"../util/common":51,"./Math":18}],24:[function(require,module,exports){ var _DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; var _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = Vec3; var common = require("../util/common"); var Math = require("./Math"); function Vec3(x, y, z) { if (!(this instanceof Vec3)) { return new Vec3(x, y, z); } if (typeof x === "undefined") { this.x = 0, this.y = 0, this.z = 0; } else if (typeof x === "object") { this.x = x.x, this.y = x.y, this.z = x.z; } else { this.x = x, this.y = y, this.z = z; } _ASSERT && Vec3.assert(this); } Vec3.prototype.toString = function() { return JSON.stringify(this); }; Vec3.isValid = function(v) { return v && Math.isFinite(v.x) && Math.isFinite(v.y) && Math.isFinite(v.z); }; Vec3.assert = function(o) { if (!_ASSERT) return; if (!Vec3.isValid(o)) { _DEBUG && common.debug(o); throw new Error("Invalid Vec3!"); } }; Vec3.prototype.setZero = function() { this.x = 0; this.y = 0; this.z = 0; return this; }; Vec3.prototype.set = function(x, y, z) { this.x = x; this.y = y; this.z = z; return this; }; Vec3.prototype.add = function(w) { this.x += w.x; this.y += w.y; this.z += w.z; return this; }; Vec3.prototype.sub = function(w) { this.x -= w.x; this.y -= w.y; this.z -= w.z; return this; }; Vec3.prototype.mul = function(m) { this.x *= m; this.y *= m; this.z *= m; return this; }; Vec3.areEqual = function(v, w) { _ASSERT && Vec3.assert(v); _ASSERT && Vec3.assert(w); return v == w || typeof v === "object" && v !== null && typeof w === "object" && w !== null && v.x === w.x && v.y === w.y && v.z === w.z; }; Vec3.dot = function(v, w) { return v.x * w.x + v.y * w.y + v.z * w.z; }; Vec3.cross = function(v, w) { return new Vec3(v.y * w.z - v.z * w.y, v.z * w.x - v.x * w.z, v.x * w.y - v.y * w.x); }; Vec3.add = function(v, w) { return new Vec3(v.x + w.x, v.y + w.y, v.z + w.z); }; Vec3.sub = function(v, w) { return new Vec3(v.x - w.x, v.y - w.y, v.z - w.z); }; Vec3.mul = function(v, m) { return new Vec3(m * v.x, m * v.y, m * v.z); }; Vec3.prototype.neg = function() { this.x = -this.x; this.y = -this.y; this.z = -this.z; return this; }; Vec3.neg = function(v) { return new Vec3(-v.x, -v.y, -v.z); }; },{"../util/common":51,"./Math":18}],25:[function(require,module,exports){ var _DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; var _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = Velocity; var Vec2 = require("./Vec2"); function Velocity() { this.v = Vec2.zero(); this.w = 0; } },{"./Vec2":23}],26:[function(require,module,exports){ var _DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; var _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; exports.toString = function(newline) { newline = typeof newline === "string" ? newline : "\n"; var string = ""; for (var name in this) { if (typeof this[name] !== "function" && typeof this[name] !== "object") { string += name + ": " + this[name] + newline; } } return string; }; },{}],27:[function(require,module,exports){ exports.internal = {}; exports.Math = require("./common/Math"); exports.Vec2 = require("./common/Vec2"); exports.Vec3 = require("./common/Vec3"); exports.Transform = require("./common/Transform"); exports.Rot = require("./common/Rot"); exports.AABB = require("./collision/AABB"); exports.Shape = require("./Shape"); exports.Fixture = require("./Fixture"); exports.Body = require("./Body"); exports.Contact = require("./Contact"); exports.Joint = require("./Joint"); exports.World = require("./World"); exports.Circle = require("./shape/CircleShape"); exports.Edge = require("./shape/EdgeShape"); exports.Polygon = require("./shape/PolygonShape"); exports.Chain = require("./shape/ChainShape"); exports.Box = require("./shape/BoxShape"); require("./shape/CollideCircle"); require("./shape/CollideEdgeCircle"); exports.internal.CollidePolygons = require("./shape/CollidePolygon"); require("./shape/CollideCirclePolygone"); require("./shape/CollideEdgePolygon"); exports.DistanceJoint = require("./joint/DistanceJoint"); exports.FrictionJoint = require("./joint/FrictionJoint"); exports.GearJoint = require("./joint/GearJoint"); exports.MotorJoint = require("./joint/MotorJoint"); exports.MouseJoint = require("./joint/MouseJoint"); exports.PrismaticJoint = require("./joint/PrismaticJoint"); exports.PulleyJoint = require("./joint/PulleyJoint"); exports.RevoluteJoint = require("./joint/RevoluteJoint"); exports.RopeJoint = require("./joint/RopeJoint"); exports.WeldJoint = require("./joint/WeldJoint"); exports.WheelJoint = require("./joint/WheelJoint"); exports.internal.Sweep = require("./common/Sweep"); exports.internal.stats = require("./common/stats"); exports.internal.Manifold = require("./Manifold"); exports.internal.Distance = require("./collision/Distance"); exports.internal.TimeOfImpact = require("./collision/TimeOfImpact"); exports.internal.DynamicTree = require("./collision/DynamicTree"); exports.internal.Settings = require("./Settings"); },{"./Body":2,"./Contact":3,"./Fixture":4,"./Joint":5,"./Manifold":6,"./Settings":7,"./Shape":8,"./World":10,"./collision/AABB":11,"./collision/Distance":13,"./collision/DynamicTree":14,"./collision/TimeOfImpact":15,"./common/Math":18,"./common/Rot":20,"./common/Sweep":21,"./common/Transform":22,"./common/Vec2":23,"./common/Vec3":24,"./common/stats":26,"./joint/DistanceJoint":28,"./joint/FrictionJoint":29,"./joint/GearJoint":30,"./joint/MotorJoint":31,"./joint/MouseJoint":32,"./joint/PrismaticJoint":33,"./joint/PulleyJoint":34,"./joint/RevoluteJoint":35,"./joint/RopeJoint":36,"./joint/WeldJoint":37,"./joint/WheelJoint":38,"./shape/BoxShape":39,"./shape/ChainShape":40,"./shape/CircleShape":41,"./shape/CollideCircle":42,"./shape/CollideCirclePolygone":43,"./shape/CollideEdgeCircle":44,"./shape/CollideEdgePolygon":45,"./shape/CollidePolygon":46,"./shape/EdgeShape":47,"./shape/PolygonShape":48}],28:[function(require,module,exports){ var _DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; var _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = DistanceJoint; var options = require("../util/options"); var create = require("../util/create"); var Settings = require("../Settings"); var Math = require("../common/Math"); var Vec2 = require("../common/Vec2"); var Vec3 = require("../common/Vec3"); var Mat22 = require("../common/Mat22"); var Mat33 = require("../common/Mat33"); var Rot = require("../common/Rot"); var Sweep = require("../common/Sweep"); var Transform = require("../common/Transform"); var Velocity = require("../common/Velocity"); var Position = require("../common/Position"); var Joint = require("../Joint"); DistanceJoint.TYPE = "distance-joint"; DistanceJoint._super = Joint; DistanceJoint.prototype = create(DistanceJoint._super.prototype); var DistanceJointDef = { frequencyHz: 0, dampingRatio: 0 }; function DistanceJoint(def, bodyA, anchorA, bodyB, anchorB) { if (!(this instanceof DistanceJoint)) { return new DistanceJoint(def, bodyA, anchorA, bodyB, anchorB); } def = options(def, DistanceJointDef); Joint.call(this, def, bodyA, bodyB); this.m_type = DistanceJoint.TYPE; this.m_localAnchorA = def.localAnchorA || bodyA.getLocalPoint(anchorA); this.m_localAnchorB = def.localAnchorB || bodyB.getLocalPoint(anchorB); this.m_length = Vec2.distance(anchorB, anchorA); this.m_frequencyHz = def.frequencyHz; this.m_dampingRatio = def.dampingRatio; this.m_impulse = 0; this.m_gamma = 0; this.m_bias = 0; this.m_u; this.m_rA; this.m_rB; this.m_localCenterA; this.m_localCenterB; this.m_invMassA; this.m_invMassB; this.m_invIA; this.m_invIB; this.m_mass; } DistanceJoint.prototype.getLocalAnchorA = function() { return this.m_localAnchorA; }; DistanceJoint.prototype.getLocalAnchorB = function() { return this.m_localAnchorB; }; DistanceJoint.prototype.setLength = function(length) { this.m_length = length; }; DistanceJoint.prototype.getLength = function() { return this.m_length; }; DistanceJoint.prototype.setFrequency = function(hz) { this.m_frequencyHz = hz; }; DistanceJoint.prototype.getFrequency = function() { return this.m_frequencyHz; }; DistanceJoint.prototype.setDampingRatio = function(ratio) { this.m_dampingRatio = ratio; }; DistanceJoint.prototype.getDampingRatio = function() { return this.m_dampingRatio; }; DistanceJoint.prototype.getAnchorA = function() { return this.m_bodyA.getWorldPoint(this.m_localAnchorA); }; DistanceJoint.prototype.getAnchorB = function() { return this.m_bodyB.getWorldPoint(this.m_localAnchorB); }; DistanceJoint.prototype.getReactionForce = function(inv_dt) { return Vec2.mul(this.m_impulse, this.m_u).mul(inv_dt); }; DistanceJoint.prototype.getReactionTorque = function(inv_dt) { return 0; }; DistanceJoint.prototype.initVelocityConstraints = function(step) { this.m_localCenterA = this.m_bodyA.m_sweep.localCenter; this.m_localCenterB = this.m_bodyB.m_sweep.localCenter; this.m_invMassA = this.m_bodyA.m_invMass; this.m_invMassB = this.m_bodyB.m_invMass; this.m_invIA = this.m_bodyA.m_invI; this.m_invIB = this.m_bodyB.m_invI; var cA = this.m_bodyA.c_position.c; var aA = this.m_bodyA.c_position.a; var vA = this.m_bodyA.c_velocity.v; var wA = this.m_bodyA.c_velocity.w; var cB = this.m_bodyB.c_position.c; var aB = this.m_bodyB.c_position.a; var vB = this.m_bodyB.c_velocity.v; var wB = this.m_bodyB.c_velocity.w; var qA = Rot.neo(aA); var qB = Rot.neo(aB); this.m_rA = Rot.mul(qA, Vec2.sub(this.m_localAnchorA, this.m_localCenterA)); this.m_rB = Rot.mul(qB, Vec2.sub(this.m_localAnchorB, this.m_localCenterB)); this.m_u = Vec2.sub(Vec2.add(cB, this.m_rB), Vec2.add(cA, this.m_rA)); var length = this.m_u.length(); if (length > Settings.linearSlop) { this.m_u.mul(1 / length); } else { this.m_u.set(0, 0); } var crAu = Vec2.cross(this.m_rA, this.m_u); var crBu = Vec2.cross(this.m_rB, this.m_u); var invMass = this.m_invMassA + this.m_invIA * crAu * crAu + this.m_invMassB + this.m_invIB * crBu * crBu; this.m_mass = invMass != 0 ? 1 / invMass : 0; if (this.m_frequencyHz > 0) { var C = length - this.m_length; var omega = 2 * Math.PI * this.m_frequencyHz; var d = 2 * this.m_mass * this.m_dampingRatio * omega; var k = this.m_mass * omega * omega; var h = step.dt; this.m_gamma = h * (d + h * k); this.m_gamma = this.m_gamma != 0 ? 1 / this.m_gamma : 0; this.m_bias = C * h * k * this.m_gamma; invMass += this.m_gamma; this.m_mass = invMass != 0 ? 1 / invMass : 0; } else { this.m_gamma = 0; this.m_bias = 0; } if (step.warmStarting) { this.m_impulse *= step.dtRatio; var P = Vec2.mul(this.m_impulse, this.m_u); vA.subMul(this.m_invMassA, P); wA -= this.m_invIA * Vec2.cross(this.m_rA, P); vB.addMul(this.m_invMassB, P); wB += this.m_invIB * Vec2.cross(this.m_rB, P); } else { this.m_impulse = 0; } this.m_bodyA.c_velocity.v.set(vA); this.m_bodyA.c_velocity.w = wA; this.m_bodyB.c_velocity.v.set(vB); this.m_bodyB.c_velocity.w = wB; }; DistanceJoint.prototype.solveVelocityConstraints = function(step) { var vA = this.m_bodyA.c_velocity.v; var wA = this.m_bodyA.c_velocity.w; var vB = this.m_bodyB.c_velocity.v; var wB = this.m_bodyB.c_velocity.w; var vpA = Vec2.add(vA, Vec2.cross(wA, this.m_rA)); var vpB = Vec2.add(vB, Vec2.cross(wB, this.m_rB)); var Cdot = Vec2.dot(this.m_u, vpB) - Vec2.dot(this.m_u, vpA); var impulse = -this.m_mass * (Cdot + this.m_bias + this.m_gamma * this.m_impulse); this.m_impulse += impulse; var P = Vec2.mul(impulse, this.m_u); vA.subMul(this.m_invMassA, P); wA -= this.m_invIA * Vec2.cross(this.m_rA, P); vB.addMul(this.m_invMassB, P); wB += this.m_invIB * Vec2.cross(this.m_rB, P); this.m_bodyA.c_velocity.v.set(vA); this.m_bodyA.c_velocity.w = wA; this.m_bodyB.c_velocity.v.set(vB); this.m_bodyB.c_velocity.w = wB; }; DistanceJoint.prototype.solvePositionConstraints = function(step) { if (this.m_frequencyHz > 0) { return true; } var cA = this.m_bodyA.c_position.c; var aA = this.m_bodyA.c_position.a; var cB = this.m_bodyB.c_position.c; var aB = this.m_bodyB.c_position.a; var qA = Rot.neo(aA); var qB = Rot.neo(aB); var rA = Rot.mulSub(qA, this.m_localAnchorA, this.m_localCenterA); var rB = Rot.mulSub(qB, this.m_localAnchorB, this.m_localCenterB); var u = Vec2.sub(Vec2.add(cB, rB), Vec2.add(cA, rA)); var length = u.normalize(); var C = length - this.m_length; C = Math.clamp(C, -Settings.maxLinearCorrection, Settings.maxLinearCorrection); var impulse = -this.m_mass * C; var P = Vec2.mul(impulse, u); cA.subMul(this.m_invMassA, P); aA -= this.m_invIA * Vec2.cross(rA, P); cB.addMul(this.m_invMassB, P); aB += this.m_invIB * Vec2.cross(rB, P); this.m_bodyA.c_position.c.set(cA); this.m_bodyA.c_position.a = aA; this.m_bodyB.c_position.c.set(cB); this.m_bodyB.c_position.a = aB; return Math.abs(C) < Settings.linearSlop; }; },{"../Joint":5,"../Settings":7,"../common/Mat22":16,"../common/Mat33":17,"../common/Math":18,"../common/Position":19,"../common/Rot":20,"../common/Sweep":21,"../common/Transform":22,"../common/Vec2":23,"../common/Vec3":24,"../common/Velocity":25,"../util/create":52,"../util/options":53}],29:[function(require,module,exports){ var _DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; var _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = FrictionJoint; var common = require("../util/common"); var options = require("../util/options"); var create = require("../util/create"); var Settings = require("../Settings"); var Math = require("../common/Math"); var Vec2 = require("../common/Vec2"); var Vec3 = require("../common/Vec3"); var Mat22 = require("../common/Mat22"); var Mat33 = require("../common/Mat33"); var Rot = require("../common/Rot"); var Sweep = require("../common/Sweep"); var Transform = require("../common/Transform"); var Velocity = require("../common/Velocity"); var Position = require("../common/Position"); var Joint = require("../Joint"); FrictionJoint.TYPE = "friction-joint"; FrictionJoint._super = Joint; FrictionJoint.prototype = create(FrictionJoint._super.prototype); var FrictionJointDef = { maxForce: 0, maxTorque: 0 }; function FrictionJoint(def, bodyA, bodyB, anchor) { if (!(this instanceof FrictionJoint)) { return new FrictionJoint(def, bodyA, bodyB, anchor); } def = options(def, FrictionJointDef); Joint.call(this, def, bodyA, bodyB); this.m_type = FrictionJoint.TYPE; if (anchor) { this.m_localAnchorA = bodyA.getLocalPoint(anchor); this.m_localAnchorB = bodyB.getLocalPoint(anchor); } else { this.m_localAnchorA = Vec2.zero(); this.m_localAnchorB = Vec2.zero(); } this.m_linearImpulse = Vec2.zero(); this.m_angularImpulse = 0; this.m_maxForce = def.maxForce; this.m_maxTorque = def.maxTorque; this.m_rA; this.m_rB; this.m_localCenterA; this.m_localCenterB; this.m_invMassA; this.m_invMassB; this.m_invIA; this.m_invIB; this.m_linearMass; this.m_angularMass; } FrictionJoint.prototype.getLocalAnchorA = function() { return this.m_localAnchorA; }; FrictionJoint.prototype.getLocalAnchorB = function() { return this.m_localAnchorB; }; FrictionJoint.prototype.setMaxForce = function(force) { _ASSERT && common.assert(IsValid(force) && force >= 0); this.m_maxForce = force; }; FrictionJoint.prototype.getMaxForce = function() { return this.m_maxForce; }; FrictionJoint.prototype.setMaxTorque = function(torque) { _ASSERT && common.assert(IsValid(torque) && torque >= 0); this.m_maxTorque = torque; }; FrictionJoint.prototype.getMaxTorque = function() { return this.m_maxTorque; }; FrictionJoint.prototype.getAnchorA = function() { return this.m_bodyA.getWorldPoint(this.m_localAnchorA); }; FrictionJoint.prototype.getAnchorB = function() { return this.m_bodyB.getWorldPoint(this.m_localAnchorB); }; FrictionJoint.prototype.getReactionForce = function(inv_dt) { return Vec2.mul(inv_dt, this.m_linearImpulse); }; FrictionJoint.prototype.getReactionTorque = function(inv_dt) { return inv_dt * this.m_angularImpulse; }; FrictionJoint.prototype.initVelocityConstraints = function(step) { this.m_localCenterA = this.m_bodyA.m_sweep.localCenter; this.m_localCenterB = this.m_bodyB.m_sweep.localCenter; this.m_invMassA = this.m_bodyA.m_invMass; this.m_invMassB = this.m_bodyB.m_invMass; this.m_invIA = this.m_bodyA.m_invI; this.m_invIB = this.m_bodyB.m_invI; var aA = this.m_bodyA.c_position.a; var vA = this.m_bodyA.c_velocity.v; var wA = this.m_bodyA.c_velocity.w; var aB = this.m_bodyB.c_position.a; var vB = this.m_bodyB.c_velocity.v; var wB = this.m_bodyB.c_velocity.w; var qA = Rot.neo(aA), qB = Rot.neo(aB); this.m_rA = Rot.mul(qA, Vec2.sub(this.m_localAnchorA, this.m_localCenterA)); this.m_rB = Rot.mul(qB, Vec2.sub(this.m_localAnchorB, this.m_localCenterB)); var mA = this.m_invMassA, mB = this.m_invMassB; var iA = this.m_invIA, iB = this.m_invIB; var K = new Mat22(); K.ex.x = mA + mB + iA * this.m_rA.y * this.m_rA.y + iB * this.m_rB.y * this.m_rB.y; K.ex.y = -iA * this.m_rA.x * this.m_rA.y - iB * this.m_rB.x * this.m_rB.y; K.ey.x = K.ex.y; K.ey.y = mA + mB + iA * this.m_rA.x * this.m_rA.x + iB * this.m_rB.x * this.m_rB.x; this.m_linearMass = K.getInverse(); this.m_angularMass = iA + iB; if (this.m_angularMass > 0) { this.m_angularMass = 1 / this.m_angularMass; } if (step.warmStarting) { this.m_linearImpulse.mul(step.dtRatio); this.m_angularImpulse *= step.dtRatio; var P = Vec2.neo(this.m_linearImpulse.x, this.m_linearImpulse.y); vA.subMul(mA, P); wA -= iA * (Vec2.cross(this.m_rA, P) + this.m_angularImpulse); vB.addMul(mB, P); wB += iB * (Vec2.cross(this.m_rB, P) + this.m_angularImpulse); } else { this.m_linearImpulse.setZero(); this.m_angularImpulse = 0; } this.m_bodyA.c_velocity.v = vA; this.m_bodyA.c_velocity.w = wA; this.m_bodyB.c_velocity.v = vB; this.m_bodyB.c_velocity.w = wB; }; FrictionJoint.prototype.solveVelocityConstraints = function(step) { var vA = this.m_bodyA.c_velocity.v; var wA = this.m_bodyA.c_velocity.w; var vB = this.m_bodyB.c_velocity.v; var wB = this.m_bodyB.c_velocity.w; var mA = this.m_invMassA, mB = this.m_invMassB; var iA = this.m_invIA, iB = this.m_invIB; var h = step.dt; { var Cdot = wB - wA; var impulse = -this.m_angularMass * Cdot; var oldImpulse = this.m_angularImpulse; var maxImpulse = h * this.m_maxTorque; this.m_angularImpulse = Math.clamp(this.m_angularImpulse + impulse, -maxImpulse, maxImpulse); impulse = this.m_angularImpulse - oldImpulse; wA -= iA * impulse; wB += iB * impulse; } { var Cdot = Vec2.sub(Vec2.add(vB, Vec2.cross(wB, this.m_rB)), Vec2.add(vA, Vec2.cross(wA, this.m_rA))); var impulse = Vec2.neg(Mat22.mul(this.m_linearMass, Cdot)); var oldImpulse = this.m_linearImpulse; this.m_linearImpulse.add(impulse); var maxImpulse = h * this.m_maxForce; if (this.m_linearImpulse.lengthSquared() > maxImpulse * maxImpulse) { this.m_linearImpulse.normalize(); this.m_linearImpulse.mul(maxImpulse); } impulse = Vec2.sub(this.m_linearImpulse, oldImpulse); vA.subMul(mA, impulse); wA -= iA * Vec2.cross(this.m_rA, impulse); vB.addMul(mB, impulse); wB += iB * Vec2.cross(this.m_rB, impulse); } this.m_bodyA.c_velocity.v = vA; this.m_bodyA.c_velocity.w = wA; this.m_bodyB.c_velocity.v = vB; this.m_bodyB.c_velocity.w = wB; }; FrictionJoint.prototype.solvePositionConstraints = function(step) { return true; }; },{"../Joint":5,"../Settings":7,"../common/Mat22":16,"../common/Mat33":17,"../common/Math":18,"../common/Position":19,"../common/Rot":20,"../common/Sweep":21,"../common/Transform":22,"../common/Vec2":23,"../common/Vec3":24,"../common/Velocity":25,"../util/common":51,"../util/create":52,"../util/options":53}],30:[function(require,module,exports){ var _DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; var _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = GearJoint; var common = require("../util/common"); var options = require("../util/options"); var create = require("../util/create"); var Settings = require("../Settings"); var Math = require("../common/Math"); var Vec2 = require("../common/Vec2"); var Vec3 = require("../common/Vec3"); var Mat22 = require("../common/Mat22"); var Mat33 = require("../common/Mat33"); var Rot = require("../common/Rot"); var Sweep = require("../common/Sweep"); var Transform = require("../common/Transform"); var Velocity = require("../common/Velocity"); var Position = require("../common/Position"); var Joint = require("../Joint"); var RevoluteJoint = require("./RevoluteJoint"); var PrismaticJoint = require("./PrismaticJoint"); GearJoint.TYPE = "gear-joint"; GearJoint._super = Joint; GearJoint.prototype = create(GearJoint._super.prototype); var GearJointDef = { ratio: 1 }; function GearJoint(def, bodyA, bodyB, joint1, joint2, ratio) { if (!(this instanceof GearJoint)) { return new GearJoint(def, bodyA, bodyB, joint1, joint2, ratio); } def = options(def, GearJointDef); Joint.call(this, def, bodyA, bodyB); this.m_type = GearJoint.TYPE; _ASSERT && common.assert(joint1.m_type == RevoluteJoint.TYPE || joint1.m_type == PrismaticJoint.TYPE); _ASSERT && common.assert(joint2.m_type == RevoluteJoint.TYPE || joint2.m_type == PrismaticJoint.TYPE); this.m_joint1 = joint1; this.m_joint2 = joint2; this.m_type1 = this.m_joint1.getType(); this.m_type2 = this.m_joint2.getType(); var coordinateA, coordinateB; this.m_bodyC = this.m_joint1.getBodyA(); this.m_bodyA = this.m_joint1.getBodyB(); var xfA = this.m_bodyA.m_xf; var aA = this.m_bodyA.m_sweep.a; var xfC = this.m_bodyC.m_xf; var aC = this.m_bodyC.m_sweep.a; if (this.m_type1 == RevoluteJoint.TYPE) { var revolute = joint1; this.m_localAnchorC = revolute.m_localAnchorA; this.m_localAnchorA = revolute.m_localAnchorB; this.m_referenceAngleA = revolute.m_referenceAngle; this.m_localAxisC = Vec2.zero(); coordinateA = aA - aC - this.m_referenceAngleA; } else { var prismatic = joint1; this.m_localAnchorC = prismatic.m_localAnchorA; this.m_localAnchorA = prismatic.m_localAnchorB; this.m_referenceAngleA = prismatic.m_referenceAngle; this.m_localAxisC = prismatic.m_localXAxisA; var pC = this.m_localAnchorC; var pA = Rot.mulT(xfC.q, Vec2.add(Rot.mul(xfA.q, this.m_localAnchorA), Vec2.sub(xfA.p, xfC.p))); coordinateA = Vec2.dot(pA, this.m_localAxisC) - Vec2.dot(pC, this.m_localAxisC); } this.m_bodyD = this.m_joint2.getBodyA(); this.m_bodyB = this.m_joint2.getBodyB(); var xfB = this.m_bodyB.m_xf; var aB = this.m_bodyB.m_sweep.a; var xfD = this.m_bodyD.m_xf; var aD = this.m_bodyD.m_sweep.a; if (this.m_type2 == RevoluteJoint.TYPE) { var revolute = joint2; this.m_localAnchorD = revolute.m_localAnchorA; this.m_localAnchorB = revolute.m_localAnchorB; this.m_referenceAngleB = revolute.m_referenceAngle; this.m_localAxisD = Vec2.zero(); coordinateB = aB - aD - this.m_referenceAngleB; } else { var prismatic = joint2; this.m_localAnchorD = prismatic.m_localAnchorA; this.m_localAnchorB = prismatic.m_localAnchorB; this.m_referenceAngleB = prismatic.m_referenceAngle; this.m_localAxisD = prismatic.m_localXAxisA; var pD = this.m_localAnchorD; var pB = Rot.mulT(xfD.q, Vec2.add(Rot.mul(xfB.q, this.m_localAnchorB), Vec2.sub(xfB.p, xfD.p))); coordinateB = Vec2.dot(pB, this.m_localAxisD) - Vec2.dot(pD, this.m_localAxisD); } this.m_ratio = ratio || def.ratio; this.m_constant = coordinateA + this.m_ratio * coordinateB; this.m_impulse = 0; this.m_lcA, this.m_lcB, this.m_lcC, this.m_lcD; this.m_mA, this.m_mB, this.m_mC, this.m_mD; this.m_iA, this.m_iB, this.m_iC, this.m_iD; this.m_JvAC, this.m_JvBD; this.m_JwA, this.m_JwB, this.m_JwC, this.m_JwD; this.m_mass; } GearJoint.prototype.getJoint1 = function() { return this.m_joint1; }; GearJoint.prototype.getJoint2 = function() { return this.m_joint2; }; GearJoint.prototype.setRatio = function(ratio) { _ASSERT && common.assert(Math.isFinite(ratio)); this.m_ratio = ratio; }; GearJoint.prototype.getRatio = function() { return this.m_ratio; }; GearJoint.prototype.getAnchorA = function() { return this.m_bodyA.getWorldPoint(this.m_localAnchorA); }; GearJoint.prototype.getAnchorB = function() { return this.m_bodyB.getWorldPoint(this.m_localAnchorB); }; GearJoint.prototype.getReactionForce = function(inv_dt) { return Vec2.mul(this.m_impulse, this.m_JvAC).mul(inv_dt); }; GearJoint.prototype.getReactionTorque = function(inv_dt) { var L = this.m_impulse * this.m_JwA; return inv_dt * L; }; GearJoint.prototype.initVelocityConstraints = function(step) { this.m_lcA = this.m_bodyA.m_sweep.localCenter; this.m_lcB = this.m_bodyB.m_sweep.localCenter; this.m_lcC = this.m_bodyC.m_sweep.localCenter; this.m_lcD = this.m_bodyD.m_sweep.localCenter; this.m_mA = this.m_bodyA.m_invMass; this.m_mB = this.m_bodyB.m_invMass; this.m_mC = this.m_bodyC.m_invMass; this.m_mD = this.m_bodyD.m_invMass; this.m_iA = this.m_bodyA.m_invI; this.m_iB = this.m_bodyB.m_invI; this.m_iC = this.m_bodyC.m_invI; this.m_iD = this.m_bodyD.m_invI; var aA = this.m_bodyA.c_position.a; var vA = this.m_bodyA.c_velocity.v; var wA = this.m_bodyA.c_velocity.w; var aB = this.m_bodyB.c_position.a; var vB = this.m_bodyB.c_velocity.v; var wB = this.m_bodyB.c_velocity.w; var aC = this.m_bodyC.c_position.a; var vC = this.m_bodyC.c_velocity.v; var wC = this.m_bodyC.c_velocity.w; var aD = this.m_bodyD.c_position.a; var vD = this.m_bodyD.c_velocity.v; var wD = this.m_bodyD.c_velocity.w; var qA = Rot.neo(aA); var qB = Rot.neo(aB); var qC = Rot.neo(aC); var qD = Rot.neo(aD); this.m_mass = 0; if (this.m_type1 == RevoluteJoint.TYPE) { this.m_JvAC = Vec2.zero(); this.m_JwA = 1; this.m_JwC = 1; this.m_mass += this.m_iA + this.m_iC; } else { var u = Rot.mul(qC, this.m_localAxisC); var rC = Rot.mulSub(qC, this.m_localAnchorC, this.m_lcC); var rA = Rot.mulSub(qA, this.m_localAnchorA, this.m_lcA); this.m_JvAC = u; this.m_JwC = Vec2.cross(rC, u); this.m_JwA = Vec2.cross(rA, u); this.m_mass += this.m_mC + this.m_mA + this.m_iC * this.m_JwC * this.m_JwC + this.m_iA * this.m_JwA * this.m_JwA; } if (this.m_type2 == RevoluteJoint.TYPE) { this.m_JvBD = Vec2.zero(); this.m_JwB = this.m_ratio; this.m_JwD = this.m_ratio; this.m_mass += this.m_ratio * this.m_ratio * (this.m_iB + this.m_iD); } else { var u = Rot.mul(qD, this.m_localAxisD); var rD = Rot.mulSub(qD, this.m_localAnchorD, this.m_lcD); var rB = Rot.mulSub(qB, this.m_localAnchorB, this.m_lcB); this.m_JvBD = Vec2.mul(this.m_ratio, u); this.m_JwD = this.m_ratio * Vec2.cross(rD, u); this.m_JwB = this.m_ratio * Vec2.cross(rB, u); this.m_mass += this.m_ratio * this.m_ratio * (this.m_mD + this.m_mB) + this.m_iD * this.m_JwD * this.m_JwD + this.m_iB * this.m_JwB * this.m_JwB; } this.m_mass = this.m_mass > 0 ? 1 / this.m_mass : 0; if (step.warmStarting) { vA.addMul(this.m_mA * this.m_impulse, this.m_JvAC); wA += this.m_iA * this.m_impulse * this.m_JwA; vB.addMul(this.m_mB * this.m_impulse, this.m_JvBD); wB += this.m_iB * this.m_impulse * this.m_JwB; vC.subMul(this.m_mC * this.m_impulse, this.m_JvAC); wC -= this.m_iC * this.m_impulse * this.m_JwC; vD.subMul(this.m_mD * this.m_impulse, this.m_JvBD); wD -= this.m_iD * this.m_impulse * this.m_JwD; } else { this.m_impulse = 0; } this.m_bodyA.c_velocity.v.set(vA); this.m_bodyA.c_velocity.w = wA; this.m_bodyB.c_velocity.v.set(vB); this.m_bodyB.c_velocity.w = wB; this.m_bodyC.c_velocity.v.set(vC); this.m_bodyC.c_velocity.w = wC; this.m_bodyD.c_velocity.v.set(vD); this.m_bodyD.c_velocity.w = wD; }; GearJoint.prototype.solveVelocityConstraints = function(step) { var vA = this.m_bodyA.c_velocity.v; var wA = this.m_bodyA.c_velocity.w; var vB = this.m_bodyB.c_velocity.v; var wB = this.m_bodyB.c_velocity.w; var vC = this.m_bodyC.c_velocity.v; var wC = this.m_bodyC.c_velocity.w; var vD = this.m_bodyD.c_velocity.v; var wD = this.m_bodyD.c_velocity.w; var Cdot = Vec2.dot(this.m_JvAC, vA) - Vec2.dot(this.m_JvAC, vC) + Vec2.dot(this.m_JvBD, vB) - Vec2.dot(this.m_JvBD, vD); Cdot += this.m_JwA * wA - this.m_JwC * wC + (this.m_JwB * wB - this.m_JwD * wD); var impulse = -this.m_mass * Cdot; this.m_impulse += impulse; vA.addMul(this.m_mA * impulse, this.m_JvAC); wA += this.m_iA * impulse * this.m_JwA; vB.addMul(this.m_mB * impulse, this.m_JvBD); wB += this.m_iB * impulse * this.m_JwB; vC.subMul(this.m_mC * impulse, this.m_JvAC); wC -= this.m_iC * impulse * this.m_JwC; vD.subMul(this.m_mD * impulse, this.m_JvBD); wD -= this.m_iD * impulse * this.m_JwD; this.m_bodyA.c_velocity.v.set(vA); this.m_bodyA.c_velocity.w = wA; this.m_bodyB.c_velocity.v.set(vB); this.m_bodyB.c_velocity.w = wB; this.m_bodyC.c_velocity.v.set(vC); this.m_bodyC.c_velocity.w = wC; this.m_bodyD.c_velocity.v.set(vD); this.m_bodyD.c_velocity.w = wD; }; GearJoint.prototype.solvePositionConstraints = function(step) { var cA = this.m_bodyA.c_position.c; var aA = this.m_bodyA.c_position.a; var cB = this.m_bodyB.c_position.c; var aB = this.m_bodyB.c_position.a; var cC = this.m_bodyC.c_position.c; var aC = this.m_bodyC.c_position.a; var cD = this.m_bodyD.c_position.c; var aD = this.m_bodyD.c_position.a; var qA = Rot.neo(aA); var qB = Rot.neo(aB); var qC = Rot.neo(aC); var qD = Rot.neo(aD); var linearError = 0; var coordinateA, coordinateB; var JvAC, JvBD; var JwA, JwB, JwC, JwD; var mass = 0; if (this.m_type1 == RevoluteJoint.TYPE) { JvAC = Vec2.zero(); JwA = 1; JwC = 1; mass += this.m_iA + this.m_iC; coordinateA = aA - aC - this.m_referenceAngleA; } else { var u = Rot.mul(qC, this.m_localAxisC); var rC = Rot.mulSub(qC, this.m_localAnchorC, this.m_lcC); var rA = Rot.mulSub(qA, this.m_localAnchorA, this.m_lcA); JvAC = u; JwC = Vec2.cross(rC, u); JwA = Vec2.cross(rA, u); mass += this.m_mC + this.m_mA + this.m_iC * JwC * JwC + this.m_iA * JwA * JwA; var pC = Vec2.sub(this.m_localAnchorC, this.m_lcC); var pA = Rot.mulT(qC, Vec2.add(rA, Vec2.sub(cA, cC))); coordinateA = Vec2.dot(Vec2.sub(pA, pC), this.m_localAxisC); } if (this.m_type2 == RevoluteJoint.TYPE) { JvBD = Vec2.zero(); JwB = this.m_ratio; JwD = this.m_ratio; mass += this.m_ratio * this.m_ratio * (this.m_iB + this.m_iD); coordinateB = aB - aD - this.m_referenceAngleB; } else { var u = Rot.mul(qD, this.m_localAxisD); var rD = Rot.mulSub(qD, this.m_localAnchorD, this.m_lcD); var rB = Rot.mulSub(qB, this.m_localAnchorB, this.m_lcB); JvBD = Vec2.mul(this.m_ratio, u); JwD = this.m_ratio * Vec2.cross(rD, u); JwB = this.m_ratio * Vec2.cross(rB, u); mass += this.m_ratio * this.m_ratio * (this.m_mD + this.m_mB) + this.m_iD * JwD * JwD + this.m_iB * JwB * JwB; var pD = Vec2.sub(this.m_localAnchorD, this.m_lcD); var pB = Rot.mulT(qD, Vec2.add(rB, Vec2.sub(cB, cD))); coordinateB = Vec2.dot(pB, this.m_localAxisD) - Vec2.dot(pD, this.m_localAxisD); } var C = coordinateA + this.m_ratio * coordinateB - this.m_constant; var impulse = 0; if (mass > 0) { impulse = -C / mass; } cA.addMul(this.m_mA * impulse, JvAC); aA += this.m_iA * impulse * JwA; cB.addMul(this.m_mB * impulse, JvBD); aB += this.m_iB * impulse * JwB; cC.subMul(this.m_mC * impulse, JvAC); aC -= this.m_iC * impulse * JwC; cD.subMul(this.m_mD * impulse, JvBD); aD -= this.m_iD * impulse * JwD; this.m_bodyA.c_position.c.set(cA); this.m_bodyA.c_position.a = aA; this.m_bodyB.c_position.c.set(cB); this.m_bodyB.c_position.a = aB; this.m_bodyC.c_position.c.set(cC); this.m_bodyC.c_position.a = aC; this.m_bodyD.c_position.c.set(cD); this.m_bodyD.c_position.a = aD; return linearError < Settings.linearSlop; }; },{"../Joint":5,"../Settings":7,"../common/Mat22":16,"../common/Mat33":17,"../common/Math":18,"../common/Position":19,"../common/Rot":20,"../common/Sweep":21,"../common/Transform":22,"../common/Vec2":23,"../common/Vec3":24,"../common/Velocity":25,"../util/common":51,"../util/create":52,"../util/options":53,"./PrismaticJoint":33,"./RevoluteJoint":35}],31:[function(require,module,exports){ var _DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; var _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = MotorJoint; var common = require("../util/common"); var options = require("../util/options"); var create = require("../util/create"); var Settings = require("../Settings"); var Math = require("../common/Math"); var Vec2 = require("../common/Vec2"); var Vec3 = require("../common/Vec3"); var Mat22 = require("../common/Mat22"); var Mat33 = require("../common/Mat33"); var Rot = require("../common/Rot"); var Sweep = require("../common/Sweep"); var Transform = require("../common/Transform"); var Velocity = require("../common/Velocity"); var Position = require("../common/Position"); var Joint = require("../Joint"); MotorJoint.TYPE = "motor-joint"; MotorJoint._super = Joint; MotorJoint.prototype = create(MotorJoint._super.prototype); var MotorJointDef = { maxForce: 1, maxTorque: 1, correctionFactor: .3 }; function MotorJoint(def, bodyA, bodyB) { if (!(this instanceof MotorJoint)) { return new MotorJoint(def, bodyA, bodyB); } def = options(def, MotorJointDef); Joint.call(this, def, bodyA, bodyB); this.m_type = MotorJoint.TYPE; var xB = bodyB.getPosition(); this.m_linearOffset = bodyA.getLocalPoint(xB); var angleA = bodyA.getAngle(); var angleB = bodyB.getAngle(); this.m_angularOffset = angleB - angleA; this.m_linearImpulse = Vec2.zero(); this.m_angularImpulse = 0; this.m_maxForce = def.maxForce; this.m_maxTorque = def.maxTorque; this.m_correctionFactor = def.correctionFactor; this.m_rA; this.m_rB; this.m_localCenterA; this.m_localCenterB; this.m_linearError; this.m_angularError; this.m_invMassA; this.m_invMassB; this.m_invIA; this.m_invIB; this.m_linearMass; this.m_angularMass; } MotorJoint.prototype.setMaxForce = function(force) { _ASSERT && common.assert(IsValid(force) && force >= 0); this.m_maxForce = force; }; MotorJoint.prototype.getMaxForce = function() { return this.m_maxForce; }; MotorJoint.prototype.setMaxTorque = function(torque) { _ASSERT && common.assert(IsValid(torque) && torque >= 0); this.m_maxTorque = torque; }; MotorJoint.prototype.getMaxTorque = function() { return this.m_maxTorque; }; MotorJoint.prototype.setCorrectionFactor = function(factor) { _ASSERT && common.assert(IsValid(factor) && 0 <= factor && factor <= 1); this.m_correctionFactor = factor; }; MotorJoint.prototype.getCorrectionFactor = function() { return this.m_correctionFactor; }; MotorJoint.prototype.setLinearOffset = function(linearOffset) { if (linearOffset.x != this.m_linearOffset.x || linearOffset.y != this.m_linearOffset.y) { this.m_bodyA.setAwake(true); this.m_bodyB.setAwake(true); this.m_linearOffset = linearOffset; } }; MotorJoint.prototype.getLinearOffset = function() { return this.m_linearOffset; }; MotorJoint.prototype.setAngularOffset = function(angularOffset) { if (angularOffset != this.m_angularOffset) { this.m_bodyA.setAwake(true); this.m_bodyB.setAwake(true); this.m_angularOffset = angularOffset; } }; MotorJoint.prototype.getAngularOffset = function() { return this.m_angularOffset; }; MotorJoint.prototype.getAnchorA = function() { return this.m_bodyA.getPosition(); }; MotorJoint.prototype.getAnchorB = function() { return this.m_bodyB.getPosition(); }; MotorJoint.prototype.getReactionForce = function(inv_dt) { return Vec2.mul(inv_dt, this.m_linearImpulse); }; MotorJoint.prototype.getReactionTorque = function(inv_dt) { return inv_dt * this.m_angularImpulse; }; MotorJoint.prototype.initVelocityConstraints = function(step) { this.m_localCenterA = this.m_bodyA.m_sweep.localCenter; this.m_localCenterB = this.m_bodyB.m_sweep.localCenter; this.m_invMassA = this.m_bodyA.m_invMass; this.m_invMassB = this.m_bodyB.m_invMass; this.m_invIA = this.m_bodyA.m_invI; this.m_invIB = this.m_bodyB.m_invI; var cA = this.m_bodyA.c_position.c; var aA = this.m_bodyA.c_position.a; var vA = this.m_bodyA.c_velocity.v; var wA = this.m_bodyA.c_velocity.w; var cB = this.m_bodyB.c_position.c; var aB = this.m_bodyB.c_position.a; var vB = this.m_bodyB.c_velocity.v; var wB = this.m_bodyB.c_velocity.w; var qA = Rot.neo(aA), qB = Rot.neo(aB); this.m_rA = Rot.mul(qA, Vec2.neg(this.m_localCenterA)); this.m_rB = Rot.mul(qB, Vec2.neg(this.m_localCenterB)); var mA = this.m_invMassA; var mB = this.m_invMassB; var iA = this.m_invIA; var iB = this.m_invIB; var K = new Mat22(); K.ex.x = mA + mB + iA * this.m_rA.y * this.m_rA.y + iB * this.m_rB.y * this.m_rB.y; K.ex.y = -iA * this.m_rA.x * this.m_rA.y - iB * this.m_rB.x * this.m_rB.y; K.ey.x = K.ex.y; K.ey.y = mA + mB + iA * this.m_rA.x * this.m_rA.x + iB * this.m_rB.x * this.m_rB.x; this.m_linearMass = K.getInverse(); this.m_angularMass = iA + iB; if (this.m_angularMass > 0) { this.m_angularMass = 1 / this.m_angularMass; } this.m_linearError = Vec2.zero(); this.m_linearError.addCombine(1, cB, 1, this.m_rB); this.m_linearError.subCombine(1, cA, 1, this.m_rA); this.m_linearError.sub(Rot.mul(qA, this.m_linearOffset)); this.m_angularError = aB - aA - this.m_angularOffset; if (step.warmStarting) { this.m_linearImpulse.mul(step.dtRatio); this.m_angularImpulse *= step.dtRatio; var P = Vec2.neo(this.m_linearImpulse.x, this.m_linearImpulse.y); vA.subMul(mA, P); wA -= iA * (Vec2.cross(this.m_rA, P) + this.m_angularImpulse); vB.addMul(mB, P); wB += iB * (Vec2.cross(this.m_rB, P) + this.m_angularImpulse); } else { this.m_linearImpulse.setZero(); this.m_angularImpulse = 0; } this.m_bodyA.c_velocity.v = vA; this.m_bodyA.c_velocity.w = wA; this.m_bodyB.c_velocity.v = vB; this.m_bodyB.c_velocity.w = wB; }; MotorJoint.prototype.solveVelocityConstraints = function(step) { var vA = this.m_bodyA.c_velocity.v; var wA = this.m_bodyA.c_velocity.w; var vB = this.m_bodyB.c_velocity.v; var wB = this.m_bodyB.c_velocity.w; var mA = this.m_invMassA, mB = this.m_invMassB; var iA = this.m_invIA, iB = this.m_invIB; var h = step.dt; var inv_h = step.inv_dt; { var Cdot = wB - wA + inv_h * this.m_correctionFactor * this.m_angularError; var impulse = -this.m_angularMass * Cdot; var oldImpulse = this.m_angularImpulse; var maxImpulse = h * this.m_maxTorque; this.m_angularImpulse = Math.clamp(this.m_angularImpulse + impulse, -maxImpulse, maxImpulse); impulse = this.m_angularImpulse - oldImpulse; wA -= iA * impulse; wB += iB * impulse; } { var Cdot = Vec2.zero(); Cdot.addCombine(1, vB, 1, Vec2.cross(wB, this.m_rB)); Cdot.subCombine(1, vA, 1, Vec2.cross(wA, this.m_rA)); Cdot.addMul(inv_h * this.m_correctionFactor, this.m_linearError); var impulse = Vec2.neg(Mat22.mul(this.m_linearMass, Cdot)); var oldImpulse = Vec2.clone(this.m_linearImpulse); this.m_linearImpulse.add(impulse); var maxImpulse = h * this.m_maxForce; this.m_linearImpulse.clamp(maxImpulse); impulse = Vec2.sub(this.m_linearImpulse, oldImpulse); vA.subMul(mA, impulse); wA -= iA * Vec2.cross(this.m_rA, impulse); vB.addMul(mB, impulse); wB += iB * Vec2.cross(this.m_rB, impulse); } this.m_bodyA.c_velocity.v = vA; this.m_bodyA.c_velocity.w = wA; this.m_bodyB.c_velocity.v = vB; this.m_bodyB.c_velocity.w = wB; }; MotorJoint.prototype.solvePositionConstraints = function(step) { return true; }; },{"../Joint":5,"../Settings":7,"../common/Mat22":16,"../common/Mat33":17,"../common/Math":18,"../common/Position":19,"../common/Rot":20,"../common/Sweep":21,"../common/Transform":22,"../common/Vec2":23,"../common/Vec3":24,"../common/Velocity":25,"../util/common":51,"../util/create":52,"../util/options":53}],32:[function(require,module,exports){ var _DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; var _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = MouseJoint; var common = require("../util/common"); var options = require("../util/options"); var create = require("../util/create"); var Math = require("../common/Math"); var Vec2 = require("../common/Vec2"); var Vec3 = require("../common/Vec3"); var Mat22 = require("../common/Mat22"); var Mat33 = require("../common/Mat33"); var Rot = require("../common/Rot"); var Sweep = require("../common/Sweep"); var Transform = require("../common/Transform"); var Velocity = require("../common/Velocity"); var Position = require("../common/Position"); var Joint = require("../Joint"); MouseJoint.TYPE = "mouse-joint"; MouseJoint._super = Joint; MouseJoint.prototype = create(MouseJoint._super.prototype); var MouseJointDef = { maxForce: 0, frequencyHz: 5, dampingRatio: .7 }; function MouseJoint(def, bodyA, bodyB, target) { if (!(this instanceof MouseJoint)) { return new MouseJoint(def, bodyA, bodyB, target); } def = options(def, MouseJointDef); Joint.call(this, def, bodyA, bodyB); this.m_type = MouseJoint.TYPE; _ASSERT && common.assert(Math.isFinite(def.maxForce) && def.maxForce >= 0); _ASSERT && common.assert(Math.isFinite(def.frequencyHz) && def.frequencyHz >= 0); _ASSERT && common.assert(Math.isFinite(def.dampingRatio) && def.dampingRatio >= 0); this.m_targetA = Vec2.clone(target); this.m_localAnchorB = Transform.mulT(this.m_bodyB.getTransform(), this.m_targetA); this.m_maxForce = def.maxForce; this.m_impulse = Vec2.zero(); this.m_frequencyHz = def.frequencyHz; this.m_dampingRatio = def.dampingRatio; this.m_beta = 0; this.m_gamma = 0; this.m_rB = Vec2.zero(); this.m_localCenterB = Vec2.zero(); this.m_invMassB = 0; this.m_invIB = 0; this.mass = new Mat22(); this.m_C = Vec2.zero(); } MouseJoint.prototype.setTarget = function(target) { if (this.m_bodyB.isAwake() == false) { this.m_bodyB.setAwake(true); } this.m_targetA = Vec2.clone(target); }; MouseJoint.prototype.getTarget = function() { return this.m_targetA; }; MouseJoint.prototype.setMaxForce = function(force) { this.m_maxForce = force; }; MouseJoint.getMaxForce = function() { return this.m_maxForce; }; MouseJoint.prototype.setFrequency = function(hz) { this.m_frequencyHz = hz; }; MouseJoint.prototype.getFrequency = function() { return this.m_frequencyHz; }; MouseJoint.prototype.setDampingRatio = function(ratio) { this.m_dampingRatio = ratio; }; MouseJoint.prototype.getDampingRatio = function() { return this.m_dampingRatio; }; MouseJoint.prototype.getAnchorA = function() { return Vec2.clone(this.m_targetA); }; MouseJoint.prototype.getAnchorB = function() { return this.m_bodyB.getWorldPoint(this.m_localAnchorB); }; MouseJoint.prototype.getReactionForce = function(inv_dt) { return Vec2.mul(inv_dt, this.m_impulse); }; MouseJoint.prototype.getReactionTorque = function(inv_dt) { return inv_dt * 0; }; MouseJoint.prototype.shiftOrigin = function(newOrigin) { this.m_targetA.sub(newOrigin); }; MouseJoint.prototype.initVelocityConstraints = function(step) { this.m_localCenterB = this.m_bodyB.m_sweep.localCenter; this.m_invMassB = this.m_bodyB.m_invMass; this.m_invIB = this.m_bodyB.m_invI; var position = this.m_bodyB.c_position; var velocity = this.m_bodyB.c_velocity; var cB = position.c; var aB = position.a; var vB = velocity.v; var wB = velocity.w; var qB = Rot.neo(aB); var mass = this.m_bodyB.getMass(); var omega = 2 * Math.PI * this.m_frequencyHz; var d = 2 * mass * this.m_dampingRatio * omega; var k = mass * (omega * omega); var h = step.dt; _ASSERT && common.assert(d + h * k > Math.EPSILON); this.m_gamma = h * (d + h * k); if (this.m_gamma != 0) { this.m_gamma = 1 / this.m_gamma; } this.m_beta = h * k * this.m_gamma; this.m_rB = Rot.mul(qB, Vec2.sub(this.m_localAnchorB, this.m_localCenterB)); var K = new Mat22(); K.ex.x = this.m_invMassB + this.m_invIB * this.m_rB.y * this.m_rB.y + this.m_gamma; K.ex.y = -this.m_invIB * this.m_rB.x * this.m_rB.y; K.ey.x = K.ex.y; K.ey.y = this.m_invMassB + this.m_invIB * this.m_rB.x * this.m_rB.x + this.m_gamma; this.m_mass = K.getInverse(); this.m_C.set(cB); this.m_C.addCombine(1, this.m_rB, -1, this.m_targetA); this.m_C.mul(this.m_beta); wB *= .98; if (step.warmStarting) { this.m_impulse.mul(step.dtRatio); vB.addMul(this.m_invMassB, this.m_impulse); wB += this.m_invIB * Vec2.cross(this.m_rB, this.m_impulse); } else { this.m_impulse.setZero(); } velocity.v.set(vB); velocity.w = wB; }; MouseJoint.prototype.solveVelocityConstraints = function(step) { var velocity = this.m_bodyB.c_velocity; var vB = Vec2.clone(velocity.v); var wB = velocity.w; var Cdot = Vec2.cross(wB, this.m_rB); Cdot.add(vB); Cdot.addCombine(1, this.m_C, this.m_gamma, this.m_impulse); Cdot.neg(); var impulse = Mat22.mul(this.m_mass, Cdot); var oldImpulse = Vec2.clone(this.m_impulse); this.m_impulse.add(impulse); var maxImpulse = step.dt * this.m_maxForce; this.m_impulse.clamp(maxImpulse); impulse = Vec2.sub(this.m_impulse, oldImpulse); vB.addMul(this.m_invMassB, impulse); wB += this.m_invIB * Vec2.cross(this.m_rB, impulse); velocity.v.set(vB); velocity.w = wB; }; MouseJoint.prototype.solvePositionConstraints = function(step) { return true; }; },{"../Joint":5,"../common/Mat22":16,"../common/Mat33":17,"../common/Math":18,"../common/Position":19,"../common/Rot":20,"../common/Sweep":21,"../common/Transform":22,"../common/Vec2":23,"../common/Vec3":24,"../common/Velocity":25,"../util/common":51,"../util/create":52,"../util/options":53}],33:[function(require,module,exports){ var _DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; var _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = PrismaticJoint; var common = require("../util/common"); var options = require("../util/options"); var create = require("../util/create"); var Settings = require("../Settings"); var Math = require("../common/Math"); var Vec2 = require("../common/Vec2"); var Vec3 = require("../common/Vec3"); var Mat22 = require("../common/Mat22"); var Mat33 = require("../common/Mat33"); var Rot = require("../common/Rot"); var Sweep = require("../common/Sweep"); var Transform = require("../common/Transform"); var Velocity = require("../common/Velocity"); var Position = require("../common/Position"); var Joint = require("../Joint"); var inactiveLimit = 0; var atLowerLimit = 1; var atUpperLimit = 2; var equalLimits = 3; PrismaticJoint.TYPE = "prismatic-joint"; PrismaticJoint._super = Joint; PrismaticJoint.prototype = create(PrismaticJoint._super.prototype); var PrismaticJointDef = { enableLimit: false, lowerTranslation: 0, upperTranslation: 0, enableMotor: false, maxMotorForce: 0, motorSpeed: 0 }; function PrismaticJoint(def, bodyA, bodyB, anchor, axis) { if (!(this instanceof PrismaticJoint)) { return new PrismaticJoint(def, bodyA, bodyB, anchor, axis); } def = options(def, PrismaticJointDef); Joint.call(this, def, bodyA, bodyB); this.m_type = PrismaticJoint.TYPE; this.m_localAnchorA = def.localAnchorA || bodyA.getLocalPoint(anchor); this.m_localAnchorB = def.localAnchorB || bodyB.getLocalPoint(anchor); this.m_localXAxisA = def.localAxisA || bodyA.getLocalVector(axis); this.m_localXAxisA.normalize(); this.m_localYAxisA = Vec2.cross(1, this.m_localXAxisA); this.m_referenceAngle = bodyB.getAngle() - bodyA.getAngle(); this.m_impulse = Vec3(); this.m_motorMass = 0; this.m_motorImpulse = 0; this.m_lowerTranslation = def.lowerTranslation; this.m_upperTranslation = def.upperTranslation; this.m_maxMotorForce = def.maxMotorForce; this.m_motorSpeed = def.motorSpeed; this.m_enableLimit = def.enableLimit; this.m_enableMotor = def.enableMotor; this.m_limitState = inactiveLimit; this.m_axis = Vec2.zero(); this.m_perp = Vec2.zero(); this.m_localCenterA; this.m_localCenterB; this.m_invMassA; this.m_invMassB; this.m_invIA; this.m_invIB; this.m_axis, this.m_perp; this.m_s1, this.m_s2; this.m_a1, this.m_a2; this.m_K = new Mat33(); this.m_motorMass; } PrismaticJoint.prototype.getLocalAnchorA = function() { return this.m_localAnchorA; }; PrismaticJoint.prototype.getLocalAnchorB = function() { return this.m_localAnchorB; }; PrismaticJoint.prototype.getLocalAxisA = function() { return this.m_localXAxisA; }; PrismaticJoint.prototype.getReferenceAngle = function() { return this.m_referenceAngle; }; PrismaticJoint.prototype.getJointTranslation = function() { var pA = this.m_bodyA.getWorldPoint(this.m_localAnchorA); var pB = this.m_bodyB.getWorldPoint(this.m_localAnchorB); var d = Vec2.sub(pB, pA); var axis = this.m_bodyA.getWorldVector(this.m_localXAxisA); var translation = Vec2.dot(d, axis); return translation; }; PrismaticJoint.prototype.getJointSpeed = function() { var bA = this.m_bodyA; var bB = this.m_bodyB; var rA = Rot.mul(bA.m_xf.q, Vec2.sub(this.m_localAnchorA, bA.m_sweep.localCenter)); var rB = Rot.mul(bB.m_xf.q, Vec2.sub(this.m_localAnchorB, bB.m_sweep.localCenter)); var p1 = Vec2.add(bA.m_sweep.c, rA); var p2 = Vec2.add(bB.m_sweep.c, rB); var d = Vec2.sub(p2, p1); var axis = Rot.mul(bA.m_xf.q, this.m_localXAxisA); var vA = bA.m_linearVelocity; var vB = bB.m_linearVelocity; var wA = bA.m_angularVelocity; var wB = bB.m_angularVelocity; var speed = Vec2.dot(d, Vec2.cross(wA, axis)) + Vec2.dot(axis, Vec2.sub(Vec2.addCross(vB, wB, rB), Vec2.addCross(vA, wA, rA))); return speed; }; PrismaticJoint.prototype.isLimitEnabled = function() { return this.m_enableLimit; }; PrismaticJoint.prototype.enableLimit = function(flag) { if (flag != this.m_enableLimit) { this.m_bodyA.setAwake(true); this.m_bodyB.setAwake(true); this.m_enableLimit = flag; this.m_impulse.z = 0; } }; PrismaticJoint.prototype.getLowerLimit = function() { return this.m_lowerTranslation; }; PrismaticJoint.prototype.getUpperLimit = function() { return this.m_upperTranslation; }; PrismaticJoint.prototype.setLimits = function(lower, upper) { _ASSERT && common.assert(lower <= upper); if (lower != this.m_lowerTranslation || upper != this.m_upperTranslation) { this.m_bodyA.setAwake(true); this.m_bodyB.setAwake(true); this.m_lowerTranslation = lower; this.m_upperTranslation = upper; this.m_impulse.z = 0; } }; PrismaticJoint.prototype.isMotorEnabled = function() { return this.m_enableMotor; }; PrismaticJoint.prototype.enableMotor = function(flag) { this.m_bodyA.setAwake(true); this.m_bodyB.setAwake(true); this.m_enableMotor = flag; }; PrismaticJoint.prototype.setMotorSpeed = function(speed) { this.m_bodyA.setAwake(true); this.m_bodyB.setAwake(true); this.m_motorSpeed = speed; }; PrismaticJoint.prototype.setMaxMotorForce = function(force) { this.m_bodyA.setAwake(true); this.m_bodyB.setAwake(true); this.m_maxMotorForce = force; }; PrismaticJoint.prototype.getMotorSpeed = function() { return this.m_motorSpeed; }; PrismaticJoint.prototype.getMotorForce = function(inv_dt) { return inv_dt * this.m_motorImpulse; }; PrismaticJoint.prototype.getAnchorA = function() { return this.m_bodyA.getWorldPoint(this.m_localAnchorA); }; PrismaticJoint.prototype.getAnchorB = function() { return this.m_bodyB.getWorldPoint(this.m_localAnchorB); }; PrismaticJoint.prototype.getReactionForce = function(inv_dt) { return Vec2.combine(this.m_impulse.x, this.m_perp, this.m_motorImpulse + this.m_impulse.z, this.m_axis).mul(inv_dt); }; PrismaticJoint.prototype.getReactionTorque = function(inv_dt) { return inv_dt * this.m_impulse.y; }; PrismaticJoint.prototype.initVelocityConstraints = function(step) { this.m_localCenterA = this.m_bodyA.m_sweep.localCenter; this.m_localCenterB = this.m_bodyB.m_sweep.localCenter; this.m_invMassA = this.m_bodyA.m_invMass; this.m_invMassB = this.m_bodyB.m_invMass; this.m_invIA = this.m_bodyA.m_invI; this.m_invIB = this.m_bodyB.m_invI; var cA = this.m_bodyA.c_position.c; var aA = this.m_bodyA.c_position.a; var vA = this.m_bodyA.c_velocity.v; var wA = this.m_bodyA.c_velocity.w; var cB = this.m_bodyB.c_position.c; var aB = this.m_bodyB.c_position.a; var vB = this.m_bodyB.c_velocity.v; var wB = this.m_bodyB.c_velocity.w; var qA = Rot.neo(aA); var qB = Rot.neo(aB); var rA = Rot.mul(qA, Vec2.sub(this.m_localAnchorA, this.m_localCenterA)); var rB = Rot.mul(qB, Vec2.sub(this.m_localAnchorB, this.m_localCenterB)); var d = Vec2.zero(); d.addCombine(1, cB, 1, rB); d.subCombine(1, cA, 1, rA); var mA = this.m_invMassA, mB = this.m_invMassB; var iA = this.m_invIA, iB = this.m_invIB; { this.m_axis = Rot.mul(qA, this.m_localXAxisA); this.m_a1 = Vec2.cross(Vec2.add(d, rA), this.m_axis); this.m_a2 = Vec2.cross(rB, this.m_axis); this.m_motorMass = mA + mB + iA * this.m_a1 * this.m_a1 + iB * this.m_a2 * this.m_a2; if (this.m_motorMass > 0) { this.m_motorMass = 1 / this.m_motorMass; } } { this.m_perp = Rot.mul(qA, this.m_localYAxisA); this.m_s1 = Vec2.cross(Vec2.add(d, rA), this.m_perp); this.m_s2 = Vec2.cross(rB, this.m_perp); var s1test = Vec2.cross(rA, this.m_perp); var k11 = mA + mB + iA * this.m_s1 * this.m_s1 + iB * this.m_s2 * this.m_s2; var k12 = iA * this.m_s1 + iB * this.m_s2; var k13 = iA * this.m_s1 * this.m_a1 + iB * this.m_s2 * this.m_a2; var k22 = iA + iB; if (k22 == 0) { k22 = 1; } var k23 = iA * this.m_a1 + iB * this.m_a2; var k33 = mA + mB + iA * this.m_a1 * this.m_a1 + iB * this.m_a2 * this.m_a2; this.m_K.ex.set(k11, k12, k13); this.m_K.ey.set(k12, k22, k23); this.m_K.ez.set(k13, k23, k33); } if (this.m_enableLimit) { var jointTranslation = Vec2.dot(this.m_axis, d); if (Math.abs(this.m_upperTranslation - this.m_lowerTranslation) < 2 * Settings.linearSlop) { this.m_limitState = equalLimits; } else if (jointTranslation <= this.m_lowerTranslation) { if (this.m_limitState != atLowerLimit) { this.m_limitState = atLowerLimit; this.m_impulse.z = 0; } } else if (jointTranslation >= this.m_upperTranslation) { if (this.m_limitState != atUpperLimit) { this.m_limitState = atUpperLimit; this.m_impulse.z = 0; } } else { this.m_limitState = inactiveLimit; this.m_impulse.z = 0; } } else { this.m_limitState = inactiveLimit; this.m_impulse.z = 0; } if (this.m_enableMotor == false) { this.m_motorImpulse = 0; } if (step.warmStarting) { this.m_impulse.mul(step.dtRatio); this.m_motorImpulse *= step.dtRatio; var P = Vec2.combine(this.m_impulse.x, this.m_perp, this.m_motorImpulse + this.m_impulse.z, this.m_axis); var LA = this.m_impulse.x * this.m_s1 + this.m_impulse.y + (this.m_motorImpulse + this.m_impulse.z) * this.m_a1; var LB = this.m_impulse.x * this.m_s2 + this.m_impulse.y + (this.m_motorImpulse + this.m_impulse.z) * this.m_a2; vA.subMul(mA, P); wA -= iA * LA; vB.addMul(mB, P); wB += iB * LB; } else { this.m_impulse.setZero(); this.m_motorImpulse = 0; } this.m_bodyA.c_velocity.v.set(vA); this.m_bodyA.c_velocity.w = wA; this.m_bodyB.c_velocity.v.set(vB); this.m_bodyB.c_velocity.w = wB; }; PrismaticJoint.prototype.solveVelocityConstraints = function(step) { var vA = this.m_bodyA.c_velocity.v; var wA = this.m_bodyA.c_velocity.w; var vB = this.m_bodyB.c_velocity.v; var wB = this.m_bodyB.c_velocity.w; var mA = this.m_invMassA; var mB = this.m_invMassB; var iA = this.m_invIA; var iB = this.m_invIB; if (this.m_enableMotor && this.m_limitState != equalLimits) { var Cdot = Vec2.dot(this.m_axis, Vec2.sub(vB, vA)) + this.m_a2 * wB - this.m_a1 * wA; var impulse = this.m_motorMass * (this.m_motorSpeed - Cdot); var oldImpulse = this.m_motorImpulse; var maxImpulse = step.dt * this.m_maxMotorForce; this.m_motorImpulse = Math.clamp(this.m_motorImpulse + impulse, -maxImpulse, maxImpulse); impulse = this.m_motorImpulse - oldImpulse; var P = Vec2.mul(impulse, this.m_axis); var LA = impulse * this.m_a1; var LB = impulse * this.m_a2; vA.subMul(mA, P); wA -= iA * LA; vB.addMul(mB, P); wB += iB * LB; } var Cdot1 = Vec2.zero(); Cdot1.x += Vec2.dot(this.m_perp, vB) + this.m_s2 * wB; Cdot1.x -= Vec2.dot(this.m_perp, vA) + this.m_s1 * wA; Cdot1.y = wB - wA; if (this.m_enableLimit && this.m_limitState != inactiveLimit) { var Cdot2 = 0; Cdot2 += Vec2.dot(this.m_axis, vB) + this.m_a2 * wB; Cdot2 -= Vec2.dot(this.m_axis, vA) + this.m_a1 * wA; var Cdot = Vec3(Cdot1.x, Cdot1.y, Cdot2); var f1 = Vec3(this.m_impulse); var df = this.m_K.solve33(Vec3.neg(Cdot)); this.m_impulse.add(df); if (this.m_limitState == atLowerLimit) { this.m_impulse.z = Math.max(this.m_impulse.z, 0); } else if (this.m_limitState == atUpperLimit) { this.m_impulse.z = Math.min(this.m_impulse.z, 0); } var b = Vec2.combine(-1, Cdot1, -(this.m_impulse.z - f1.z), Vec2.neo(this.m_K.ez.x, this.m_K.ez.y)); var f2r = Vec2.add(this.m_K.solve22(b), Vec2.neo(f1.x, f1.y)); this.m_impulse.x = f2r.x; this.m_impulse.y = f2r.y; df = Vec3.sub(this.m_impulse, f1); var P = Vec2.combine(df.x, this.m_perp, df.z, this.m_axis); var LA = df.x * this.m_s1 + df.y + df.z * this.m_a1; var LB = df.x * this.m_s2 + df.y + df.z * this.m_a2; vA.subMul(mA, P); wA -= iA * LA; vB.addMul(mB, P); wB += iB * LB; } else { var df = this.m_K.solve22(Vec2.neg(Cdot1)); this.m_impulse.x += df.x; this.m_impulse.y += df.y; var P = Vec2.mul(df.x, this.m_perp); var LA = df.x * this.m_s1 + df.y; var LB = df.x * this.m_s2 + df.y; vA.subMul(mA, P); wA -= iA * LA; vB.addMul(mB, P); wB += iB * LB; } this.m_bodyA.c_velocity.v = vA; this.m_bodyA.c_velocity.w = wA; this.m_bodyB.c_velocity.v = vB; this.m_bodyB.c_velocity.w = wB; }; PrismaticJoint.prototype.solvePositionConstraints = function(step) { var cA = this.m_bodyA.c_position.c; var aA = this.m_bodyA.c_position.a; var cB = this.m_bodyB.c_position.c; var aB = this.m_bodyB.c_position.a; var qA = Rot.neo(aA); var qB = Rot.neo(aB); var mA = this.m_invMassA; var mB = this.m_invMassB; var iA = this.m_invIA; var iB = this.m_invIB; var rA = Rot.mul(qA, Vec2.sub(this.m_localAnchorA, this.m_localCenterA)); var rB = Rot.mul(qB, Vec2.sub(this.m_localAnchorB, this.m_localCenterB)); var d = Vec2.sub(Vec2.add(cB, rB), Vec2.add(cA, rA)); var axis = Rot.mul(qA, this.m_localXAxisA); var a1 = Vec2.cross(Vec2.add(d, rA), axis); var a2 = Vec2.cross(rB, axis); var perp = Rot.mul(qA, this.m_localYAxisA); var s1 = Vec2.cross(Vec2.add(d, rA), perp); var s2 = Vec2.cross(rB, perp); var impulse = Vec3(); var C1 = Vec2.zero(); C1.x = Vec2.dot(perp, d); C1.y = aB - aA - this.m_referenceAngle; var linearError = Math.abs(C1.x); var angularError = Math.abs(C1.y); var linearSlop = Settings.linearSlop; var maxLinearCorrection = Settings.maxLinearCorrection; var active = false; var C2 = 0; if (this.m_enableLimit) { var translation = Vec2.dot(axis, d); if (Math.abs(this.m_upperTranslation - this.m_lowerTranslation) < 2 * linearSlop) { C2 = Math.clamp(translation, -maxLinearCorrection, maxLinearCorrection); linearError = Math.max(linearError, Math.abs(translation)); active = true; } else if (translation <= this.m_lowerTranslation) { C2 = Math.clamp(translation - this.m_lowerTranslation + linearSlop, -maxLinearCorrection, 0); linearError = Math.max(linearError, this.m_lowerTranslation - translation); active = true; } else if (translation >= this.m_upperTranslation) { C2 = Math.clamp(translation - this.m_upperTranslation - linearSlop, 0, maxLinearCorrection); linearError = Math.max(linearError, translation - this.m_upperTranslation); active = true; } } if (active) { var k11 = mA + mB + iA * s1 * s1 + iB * s2 * s2; var k12 = iA * s1 + iB * s2; var k13 = iA * s1 * a1 + iB * s2 * a2; var k22 = iA + iB; if (k22 == 0) { k22 = 1; } var k23 = iA * a1 + iB * a2; var k33 = mA + mB + iA * a1 * a1 + iB * a2 * a2; var K = new Mat33(); K.ex.set(k11, k12, k13); K.ey.set(k12, k22, k23); K.ez.set(k13, k23, k33); var C = Vec3(); C.x = C1.x; C.y = C1.y; C.z = C2; impulse = K.solve33(Vec3.neg(C)); } else { var k11 = mA + mB + iA * s1 * s1 + iB * s2 * s2; var k12 = iA * s1 + iB * s2; var k22 = iA + iB; if (k22 == 0) { k22 = 1; } var K = new Mat22(); K.ex.set(k11, k12); K.ey.set(k12, k22); var impulse1 = K.solve(Vec2.neg(C1)); impulse.x = impulse1.x; impulse.y = impulse1.y; impulse.z = 0; } var P = Vec2.combine(impulse.x, perp, impulse.z, axis); var LA = impulse.x * s1 + impulse.y + impulse.z * a1; var LB = impulse.x * s2 + impulse.y + impulse.z * a2; cA.subMul(mA, P); aA -= iA * LA; cB.addMul(mB, P); aB += iB * LB; this.m_bodyA.c_position.c = cA; this.m_bodyA.c_position.a = aA; this.m_bodyB.c_position.c = cB; this.m_bodyB.c_position.a = aB; return linearError <= Settings.linearSlop && angularError <= Settings.angularSlop; }; },{"../Joint":5,"../Settings":7,"../common/Mat22":16,"../common/Mat33":17,"../common/Math":18,"../common/Position":19,"../common/Rot":20,"../common/Sweep":21,"../common/Transform":22,"../common/Vec2":23,"../common/Vec3":24,"../common/Velocity":25,"../util/common":51,"../util/create":52,"../util/options":53}],34:[function(require,module,exports){ var _DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; var _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = PulleyJoint; var common = require("../util/common"); var options = require("../util/options"); var create = require("../util/create"); var Settings = require("../Settings"); var Math = require("../common/Math"); var Vec2 = require("../common/Vec2"); var Vec3 = require("../common/Vec3"); var Mat22 = require("../common/Mat22"); var Mat33 = require("../common/Mat33"); var Rot = require("../common/Rot"); var Sweep = require("../common/Sweep"); var Transform = require("../common/Transform"); var Velocity = require("../common/Velocity"); var Position = require("../common/Position"); var Joint = require("../Joint"); PulleyJoint.TYPE = "pulley-joint"; PulleyJoint.MIN_PULLEY_LENGTH = 2; PulleyJoint._super = Joint; PulleyJoint.prototype = create(PulleyJoint._super.prototype); var PulleyJointDef = { collideConnected: true }; function PulleyJoint(def, bodyA, bodyB, groundA, groundB, anchorA, anchorB, ratio) { if (!(this instanceof PulleyJoint)) { return new PulleyJoint(def, bodyA, bodyB, groundA, groundB, anchorA, anchorB, ratio); } def = options(def, PulleyJointDef); Joint.call(this, def, bodyA, bodyB); this.m_type = PulleyJoint.TYPE; this.m_groundAnchorA = groundA; this.m_groundAnchorB = groundB; this.m_localAnchorA = bodyA.getLocalPoint(anchorA); this.m_localAnchorB = bodyB.getLocalPoint(anchorB); this.m_lengthA = Vec2.distance(anchorA, groundA); this.m_lengthB = Vec2.distance(anchorB, groundB); this.m_ratio = def.ratio || ratio; _ASSERT && common.assert(ratio > Math.EPSILON); this.m_constant = this.m_lengthA + this.m_ratio * this.m_lengthB; this.m_impulse = 0; this.m_uA; this.m_uB; this.m_rA; this.m_rB; this.m_localCenterA; this.m_localCenterB; this.m_invMassA; this.m_invMassB; this.m_invIA; this.m_invIB; this.m_mass; } PulleyJoint.prototype.getGroundAnchorA = function() { return this.m_groundAnchorA; }; PulleyJoint.prototype.getGroundAnchorB = function() { return this.m_groundAnchorB; }; PulleyJoint.prototype.getLengthA = function() { return this.m_lengthA; }; PulleyJoint.prototype.getLengthB = function() { return this.m_lengthB; }; PulleyJoint.prototype.getRatio = function() { return this.m_ratio; }; PulleyJoint.prototype.getCurrentLengthA = function() { var p = this.m_bodyA.getWorldPoint(this.m_localAnchorA); var s = this.m_groundAnchorA; return Vec2.distance(p, s); }; PulleyJoint.prototype.getCurrentLengthB = function() { var p = this.m_bodyB.getWorldPoint(this.m_localAnchorB); var s = this.m_groundAnchorB; return Vec2.distance(p, s); }; PulleyJoint.prototype.shiftOrigin = function(newOrigin) { this.m_groundAnchorA.sub(newOrigin); this.m_groundAnchorB.sub(newOrigin); }; PulleyJoint.prototype.getAnchorA = function() { return this.m_bodyA.getWorldPoint(this.m_localAnchorA); }; PulleyJoint.prototype.getAnchorB = function() { return this.m_bodyB.getWorldPoint(this.m_localAnchorB); }; PulleyJoint.prototype.getReactionForce = function(inv_dt) { return Vec2.mul(this.m_impulse, this.m_uB).mul(inv_dt); }; PulleyJoint.prototype.getReactionTorque = function(inv_dt) { return 0; }; PulleyJoint.prototype.initVelocityConstraints = function(step) { this.m_localCenterA = this.m_bodyA.m_sweep.localCenter; this.m_localCenterB = this.m_bodyB.m_sweep.localCenter; this.m_invMassA = this.m_bodyA.m_invMass; this.m_invMassB = this.m_bodyB.m_invMass; this.m_invIA = this.m_bodyA.m_invI; this.m_invIB = this.m_bodyB.m_invI; var cA = this.m_bodyA.c_position.c; var aA = this.m_bodyA.c_position.a; var vA = this.m_bodyA.c_velocity.v; var wA = this.m_bodyA.c_velocity.w; var cB = this.m_bodyB.c_position.c; var aB = this.m_bodyB.c_position.a; var vB = this.m_bodyB.c_velocity.v; var wB = this.m_bodyB.c_velocity.w; var qA = Rot.neo(aA); var qB = Rot.neo(aB); this.m_rA = Rot.mul(qA, Vec2.sub(this.m_localAnchorA, this.m_localCenterA)); this.m_rB = Rot.mul(qB, Vec2.sub(this.m_localAnchorB, this.m_localCenterB)); this.m_uA = Vec2.sub(Vec2.add(cA, this.m_rA), this.m_groundAnchorA); this.m_uB = Vec2.sub(Vec2.add(cB, this.m_rB), this.m_groundAnchorB); var lengthA = this.m_uA.length(); var lengthB = this.m_uB.length(); if (lengthA > 10 * Settings.linearSlop) { this.m_uA.mul(1 / lengthA); } else { this.m_uA.setZero(); } if (lengthB > 10 * Settings.linearSlop) { this.m_uB.mul(1 / lengthB); } else { this.m_uB.setZero(); } var ruA = Vec2.cross(this.m_rA, this.m_uA); var ruB = Vec2.cross(this.m_rB, this.m_uB); var mA = this.m_invMassA + this.m_invIA * ruA * ruA; var mB = this.m_invMassB + this.m_invIB * ruB * ruB; this.m_mass = mA + this.m_ratio * this.m_ratio * mB; if (this.m_mass > 0) { this.m_mass = 1 / this.m_mass; } if (step.warmStarting) { this.m_impulse *= step.dtRatio; var PA = Vec2.mul(-this.m_impulse, this.m_uA); var PB = Vec2.mul(-this.m_ratio * this.m_impulse, this.m_uB); vA.addMul(this.m_invMassA, PA); wA += this.m_invIA * Vec2.cross(this.m_rA, PA); vB.addMul(this.m_invMassB, PB); wB += this.m_invIB * Vec2.cross(this.m_rB, PB); } else { this.m_impulse = 0; } this.m_bodyA.c_velocity.v = vA; this.m_bodyA.c_velocity.w = wA; this.m_bodyB.c_velocity.v = vB; this.m_bodyB.c_velocity.w = wB; }; PulleyJoint.prototype.solveVelocityConstraints = function(step) { var vA = this.m_bodyA.c_velocity.v; var wA = this.m_bodyA.c_velocity.w; var vB = this.m_bodyB.c_velocity.v; var wB = this.m_bodyB.c_velocity.w; var vpA = Vec2.add(vA, Vec2.cross(wA, this.m_rA)); var vpB = Vec2.add(vB, Vec2.cross(wB, this.m_rB)); var Cdot = -Vec2.dot(this.m_uA, vpA) - this.m_ratio * Vec2.dot(this.m_uB, vpB); var impulse = -this.m_mass * Cdot; this.m_impulse += impulse; var PA = Vec2.mul(-impulse, this.m_uA); var PB = Vec2.mul(-this.m_ratio * impulse, this.m_uB); vA.addMul(this.m_invMassA, PA); wA += this.m_invIA * Vec2.cross(this.m_rA, PA); vB.addMul(this.m_invMassB, PB); wB += this.m_invIB * Vec2.cross(this.m_rB, PB); this.m_bodyA.c_velocity.v = vA; this.m_bodyA.c_velocity.w = wA; this.m_bodyB.c_velocity.v = vB; this.m_bodyB.c_velocity.w = wB; }; PulleyJoint.prototype.solvePositionConstraints = function(step) { var cA = this.m_bodyA.c_position.c; var aA = this.m_bodyA.c_position.a; var cB = this.m_bodyB.c_position.c; var aB = this.m_bodyB.c_position.a; var qA = Rot.neo(aA), qB = Rot.neo(aB); var rA = Rot.mul(qA, Vec2.sub(this.m_localAnchorA, this.m_localCenterA)); var rB = Rot.mul(qB, Vec2.sub(this.m_localAnchorB, this.m_localCenterB)); var uA = Vec2.sub(Vec2.add(cA, this.m_rA), this.m_groundAnchorA); var uB = Vec2.sub(Vec2.add(cB, this.m_rB), this.m_groundAnchorB); var lengthA = uA.length(); var lengthB = uB.length(); if (lengthA > 10 * Settings.linearSlop) { uA.mul(1 / lengthA); } else { uA.setZero(); } if (lengthB > 10 * Settings.linearSlop) { uB.mul(1 / lengthB); } else { uB.setZero(); } var ruA = Vec2.cross(rA, uA); var ruB = Vec2.cross(rB, uB); var mA = this.m_invMassA + this.m_invIA * ruA * ruA; var mB = this.m_invMassB + this.m_invIB * ruB * ruB; var mass = mA + this.m_ratio * this.m_ratio * mB; if (mass > 0) { mass = 1 / mass; } var C = this.m_constant - lengthA - this.m_ratio * lengthB; var linearError = Math.abs(C); var impulse = -mass * C; var PA = Vec2.mul(-impulse, uA); var PB = Vec2.mul(-this.m_ratio * impulse, uB); cA.addMul(this.m_invMassA, PA); aA += this.m_invIA * Vec2.cross(rA, PA); cB.addMul(this.m_invMassB, PB); aB += this.m_invIB * Vec2.cross(rB, PB); this.m_bodyA.c_position.c = cA; this.m_bodyA.c_position.a = aA; this.m_bodyB.c_position.c = cB; this.m_bodyB.c_position.a = aB; return linearError < Settings.linearSlop; }; },{"../Joint":5,"../Settings":7,"../common/Mat22":16,"../common/Mat33":17,"../common/Math":18,"../common/Position":19,"../common/Rot":20,"../common/Sweep":21,"../common/Transform":22,"../common/Vec2":23,"../common/Vec3":24,"../common/Velocity":25,"../util/common":51,"../util/create":52,"../util/options":53}],35:[function(require,module,exports){ var _DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; var _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = RevoluteJoint; var common = require("../util/common"); var options = require("../util/options"); var create = require("../util/create"); var Settings = require("../Settings"); var Math = require("../common/Math"); var Vec2 = require("../common/Vec2"); var Vec3 = require("../common/Vec3"); var Mat22 = require("../common/Mat22"); var Mat33 = require("../common/Mat33"); var Rot = require("../common/Rot"); var Sweep = require("../common/Sweep"); var Transform = require("../common/Transform"); var Velocity = require("../common/Velocity"); var Position = require("../common/Position"); var Joint = require("../Joint"); var inactiveLimit = 0; var atLowerLimit = 1; var atUpperLimit = 2; var equalLimits = 3; RevoluteJoint.TYPE = "revolute-joint"; RevoluteJoint._super = Joint; RevoluteJoint.prototype = create(RevoluteJoint._super.prototype); var RevoluteJointDef = { lowerAngle: 0, upperAngle: 0, maxMotorTorque: 0, motorSpeed: 0, enableLimit: false, enableMotor: false }; function RevoluteJoint(def, bodyA, bodyB, anchor) { if (!(this instanceof RevoluteJoint)) { return new RevoluteJoint(def, bodyA, bodyB, anchor); } def = options(def, RevoluteJointDef); Joint.call(this, def, bodyA, bodyB); this.m_type = RevoluteJoint.TYPE; this.m_localAnchorA = def.localAnchorA || bodyA.getLocalPoint(anchor); this.m_localAnchorB = def.localAnchorB || bodyB.getLocalPoint(anchor); this.m_referenceAngle = bodyB.getAngle() - bodyA.getAngle(); this.m_impulse = Vec3(); this.m_motorImpulse = 0; this.m_lowerAngle = def.lowerAngle; this.m_upperAngle = def.upperAngle; this.m_maxMotorTorque = def.maxMotorTorque; this.m_motorSpeed = def.motorSpeed; this.m_enableLimit = def.enableLimit; this.m_enableMotor = def.enableMotor; this.m_rA; this.m_rB; this.m_localCenterA; this.m_localCenterB; this.m_invMassA; this.m_invMassB; this.m_invIA; this.m_invIB; this.m_mass = new Mat33(); this.m_motorMass; this.m_limitState = inactiveLimit; } RevoluteJoint.prototype.getLocalAnchorA = function() { return this.m_localAnchorA; }; RevoluteJoint.prototype.getLocalAnchorB = function() { return this.m_localAnchorB; }; RevoluteJoint.prototype.getReferenceAngle = function() { return this.m_referenceAngle; }; RevoluteJoint.prototype.getJointAngle = function() { var bA = this.m_bodyA; var bB = this.m_bodyB; return bB.m_sweep.a - bA.m_sweep.a - this.m_referenceAngle; }; RevoluteJoint.prototype.getJointSpeed = function() { var bA = this.m_bodyA; var bB = this.m_bodyB; return bB.m_angularVelocity - bA.m_angularVelocity; }; RevoluteJoint.prototype.isMotorEnabled = function() { return this.m_enableMotor; }; RevoluteJoint.prototype.enableMotor = function(flag) { this.m_bodyA.setAwake(true); this.m_bodyB.setAwake(true); this.m_enableMotor = flag; }; RevoluteJoint.prototype.getMotorTorque = function(inv_dt) { return inv_dt * this.m_motorImpulse; }; RevoluteJoint.prototype.setMotorSpeed = function(speed) { this.m_bodyA.setAwake(true); this.m_bodyB.setAwake(true); this.m_motorSpeed = speed; }; RevoluteJoint.prototype.getMotorSpeed = function() { return this.m_motorSpeed; }; RevoluteJoint.prototype.setMaxMotorTorque = function(torque) { this.m_bodyA.setAwake(true); this.m_bodyB.setAwake(true); this.m_maxMotorTorque = torque; }; RevoluteJoint.prototype.isLimitEnabled = function() { return this.m_enableLimit; }; RevoluteJoint.prototype.enableLimit = function(flag) { if (flag != this.m_enableLimit) { this.m_bodyA.setAwake(true); this.m_bodyB.setAwake(true); this.m_enableLimit = flag; this.m_impulse.z = 0; } }; RevoluteJoint.prototype.getLowerLimit = function() { return this.m_lowerAngle; }; RevoluteJoint.prototype.getUpperLimit = function() { return this.m_upperAngle; }; RevoluteJoint.prototype.setLimits = function(lower, upper) { _ASSERT && common.assert(lower <= upper); if (lower != this.m_lowerAngle || upper != this.m_upperAngle) { this.m_bodyA.setAwake(true); this.m_bodyB.setAwake(true); this.m_impulse.z = 0; this.m_lowerAngle = lower; this.m_upperAngle = upper; } }; RevoluteJoint.prototype.getAnchorA = function() { return this.m_bodyA.getWorldPoint(this.m_localAnchorA); }; RevoluteJoint.prototype.getAnchorB = function() { return this.m_bodyB.getWorldPoint(this.m_localAnchorB); }; RevoluteJoint.prototype.getReactionForce = function(inv_dt) { return Vec2.neo(this.m_impulse.x, this.m_impulse.y).mul(inv_dt); }; RevoluteJoint.prototype.getReactionTorque = function(inv_dt) { return inv_dt * this.m_impulse.z; }; RevoluteJoint.prototype.initVelocityConstraints = function(step) { this.m_localCenterA = this.m_bodyA.m_sweep.localCenter; this.m_localCenterB = this.m_bodyB.m_sweep.localCenter; this.m_invMassA = this.m_bodyA.m_invMass; this.m_invMassB = this.m_bodyB.m_invMass; this.m_invIA = this.m_bodyA.m_invI; this.m_invIB = this.m_bodyB.m_invI; var aA = this.m_bodyA.c_position.a; var vA = this.m_bodyA.c_velocity.v; var wA = this.m_bodyA.c_velocity.w; var aB = this.m_bodyB.c_position.a; var vB = this.m_bodyB.c_velocity.v; var wB = this.m_bodyB.c_velocity.w; var qA = Rot.neo(aA); var qB = Rot.neo(aB); this.m_rA = Rot.mul(qA, Vec2.sub(this.m_localAnchorA, this.m_localCenterA)); this.m_rB = Rot.mul(qB, Vec2.sub(this.m_localAnchorB, this.m_localCenterB)); var mA = this.m_invMassA; var mB = this.m_invMassB; var iA = this.m_invIA; var iB = this.m_invIB; var fixedRotation = iA + iB == 0; this.m_mass.ex.x = mA + mB + this.m_rA.y * this.m_rA.y * iA + this.m_rB.y * this.m_rB.y * iB; this.m_mass.ey.x = -this.m_rA.y * this.m_rA.x * iA - this.m_rB.y * this.m_rB.x * iB; this.m_mass.ez.x = -this.m_rA.y * iA - this.m_rB.y * iB; this.m_mass.ex.y = this.m_mass.ey.x; this.m_mass.ey.y = mA + mB + this.m_rA.x * this.m_rA.x * iA + this.m_rB.x * this.m_rB.x * iB; this.m_mass.ez.y = this.m_rA.x * iA + this.m_rB.x * iB; this.m_mass.ex.z = this.m_mass.ez.x; this.m_mass.ey.z = this.m_mass.ez.y; this.m_mass.ez.z = iA + iB; this.m_motorMass = iA + iB; if (this.m_motorMass > 0) { this.m_motorMass = 1 / this.m_motorMass; } if (this.m_enableMotor == false || fixedRotation) { this.m_motorImpulse = 0; } if (this.m_enableLimit && fixedRotation == false) { var jointAngle = aB - aA - this.m_referenceAngle; if (Math.abs(this.m_upperAngle - this.m_lowerAngle) < 2 * Settings.angularSlop) { this.m_limitState = equalLimits; } else if (jointAngle <= this.m_lowerAngle) { if (this.m_limitState != atLowerLimit) { this.m_impulse.z = 0; } this.m_limitState = atLowerLimit; } else if (jointAngle >= this.m_upperAngle) { if (this.m_limitState != atUpperLimit) { this.m_impulse.z = 0; } this.m_limitState = atUpperLimit; } else { this.m_limitState = inactiveLimit; this.m_impulse.z = 0; } } else { this.m_limitState = inactiveLimit; } if (step.warmStarting) { this.m_impulse.mul(step.dtRatio); this.m_motorImpulse *= step.dtRatio; var P = Vec2.neo(this.m_impulse.x, this.m_impulse.y); vA.subMul(mA, P); wA -= iA * (Vec2.cross(this.m_rA, P) + this.m_motorImpulse + this.m_impulse.z); vB.addMul(mB, P); wB += iB * (Vec2.cross(this.m_rB, P) + this.m_motorImpulse + this.m_impulse.z); } else { this.m_impulse.setZero(); this.m_motorImpulse = 0; } this.m_bodyA.c_velocity.v = vA; this.m_bodyA.c_velocity.w = wA; this.m_bodyB.c_velocity.v = vB; this.m_bodyB.c_velocity.w = wB; }; RevoluteJoint.prototype.solveVelocityConstraints = function(step) { var vA = this.m_bodyA.c_velocity.v; var wA = this.m_bodyA.c_velocity.w; var vB = this.m_bodyB.c_velocity.v; var wB = this.m_bodyB.c_velocity.w; var mA = this.m_invMassA; var mB = this.m_invMassB; var iA = this.m_invIA; var iB = this.m_invIB; var fixedRotation = iA + iB == 0; if (this.m_enableMotor && this.m_limitState != equalLimits && fixedRotation == false) { var Cdot = wB - wA - this.m_motorSpeed; var impulse = -this.m_motorMass * Cdot; var oldImpulse = this.m_motorImpulse; var maxImpulse = step.dt * this.m_maxMotorTorque; this.m_motorImpulse = Math.clamp(this.m_motorImpulse + impulse, -maxImpulse, maxImpulse); impulse = this.m_motorImpulse - oldImpulse; wA -= iA * impulse; wB += iB * impulse; } if (this.m_enableLimit && this.m_limitState != inactiveLimit && fixedRotation == false) { var Cdot1 = Vec2.zero(); Cdot1.addCombine(1, vB, 1, Vec2.cross(wB, this.m_rB)); Cdot1.subCombine(1, vA, 1, Vec2.cross(wA, this.m_rA)); var Cdot2 = wB - wA; var Cdot = Vec3(Cdot1.x, Cdot1.y, Cdot2); var impulse = Vec3.neg(this.m_mass.solve33(Cdot)); if (this.m_limitState == equalLimits) { this.m_impulse.add(impulse); } else if (this.m_limitState == atLowerLimit) { var newImpulse = this.m_impulse.z + impulse.z; if (newImpulse < 0) { var rhs = Vec2.combine(-1, Cdot1, this.m_impulse.z, Vec2.neo(this.m_mass.ez.x, this.m_mass.ez.y)); var reduced = this.m_mass.solve22(rhs); impulse.x = reduced.x; impulse.y = reduced.y; impulse.z = -this.m_impulse.z; this.m_impulse.x += reduced.x; this.m_impulse.y += reduced.y; this.m_impulse.z = 0; } else { this.m_impulse.add(impulse); } } else if (this.m_limitState == atUpperLimit) { var newImpulse = this.m_impulse.z + impulse.z; if (newImpulse > 0) { var rhs = Vec2.combine(-1, Cdot1, this.m_impulse.z, Vec2.neo(this.m_mass.ez.x, this.m_mass.ez.y)); var reduced = this.m_mass.solve22(rhs); impulse.x = reduced.x; impulse.y = reduced.y; impulse.z = -this.m_impulse.z; this.m_impulse.x += reduced.x; this.m_impulse.y += reduced.y; this.m_impulse.z = 0; } else { this.m_impulse.add(impulse); } } var P = Vec2.neo(impulse.x, impulse.y); vA.subMul(mA, P); wA -= iA * (Vec2.cross(this.m_rA, P) + impulse.z); vB.addMul(mB, P); wB += iB * (Vec2.cross(this.m_rB, P) + impulse.z); } else { var Cdot = Vec2.zero(); Cdot.addCombine(1, vB, 1, Vec2.cross(wB, this.m_rB)); Cdot.subCombine(1, vA, 1, Vec2.cross(wA, this.m_rA)); var impulse = this.m_mass.solve22(Vec2.neg(Cdot)); this.m_impulse.x += impulse.x; this.m_impulse.y += impulse.y; vA.subMul(mA, impulse); wA -= iA * Vec2.cross(this.m_rA, impulse); vB.addMul(mB, impulse); wB += iB * Vec2.cross(this.m_rB, impulse); } this.m_bodyA.c_velocity.v = vA; this.m_bodyA.c_velocity.w = wA; this.m_bodyB.c_velocity.v = vB; this.m_bodyB.c_velocity.w = wB; }; RevoluteJoint.prototype.solvePositionConstraints = function(step) { var cA = this.m_bodyA.c_position.c; var aA = this.m_bodyA.c_position.a; var cB = this.m_bodyB.c_position.c; var aB = this.m_bodyB.c_position.a; var qA = Rot.neo(aA); var qB = Rot.neo(aB); var angularError = 0; var positionError = 0; var fixedRotation = this.m_invIA + this.m_invIB == 0; if (this.m_enableLimit && this.m_limitState != inactiveLimit && fixedRotation == false) { var angle = aB - aA - this.m_referenceAngle; var limitImpulse = 0; if (this.m_limitState == equalLimits) { var C = Math.clamp(angle - this.m_lowerAngle, -Settings.maxAngularCorrection, Settings.maxAngularCorrection); limitImpulse = -this.m_motorMass * C; angularError = Math.abs(C); } else if (this.m_limitState == atLowerLimit) { var C = angle - this.m_lowerAngle; angularError = -C; C = Math.clamp(C + Settings.angularSlop, -Settings.maxAngularCorrection, 0); limitImpulse = -this.m_motorMass * C; } else if (this.m_limitState == atUpperLimit) { var C = angle - this.m_upperAngle; angularError = C; C = Math.clamp(C - Settings.angularSlop, 0, Settings.maxAngularCorrection); limitImpulse = -this.m_motorMass * C; } aA -= this.m_invIA * limitImpulse; aB += this.m_invIB * limitImpulse; } { qA.set(aA); qB.set(aB); var rA = Rot.mul(qA, Vec2.sub(this.m_localAnchorA, this.m_localCenterA)); var rB = Rot.mul(qB, Vec2.sub(this.m_localAnchorB, this.m_localCenterB)); var C = Vec2.zero(); C.addCombine(1, cB, 1, rB); C.subCombine(1, cA, 1, rA); positionError = C.length(); var mA = this.m_invMassA; var mB = this.m_invMassB; var iA = this.m_invIA; var iB = this.m_invIB; var K = new Mat22(); K.ex.x = mA + mB + iA * rA.y * rA.y + iB * rB.y * rB.y; K.ex.y = -iA * rA.x * rA.y - iB * rB.x * rB.y; K.ey.x = K.ex.y; K.ey.y = mA + mB + iA * rA.x * rA.x + iB * rB.x * rB.x; var impulse = Vec2.neg(K.solve(C)); cA.subMul(mA, impulse); aA -= iA * Vec2.cross(rA, impulse); cB.addMul(mB, impulse); aB += iB * Vec2.cross(rB, impulse); } this.m_bodyA.c_position.c.set(cA); this.m_bodyA.c_position.a = aA; this.m_bodyB.c_position.c.set(cB); this.m_bodyB.c_position.a = aB; return positionError <= Settings.linearSlop && angularError <= Settings.angularSlop; }; },{"../Joint":5,"../Settings":7,"../common/Mat22":16,"../common/Mat33":17,"../common/Math":18,"../common/Position":19,"../common/Rot":20,"../common/Sweep":21,"../common/Transform":22,"../common/Vec2":23,"../common/Vec3":24,"../common/Velocity":25,"../util/common":51,"../util/create":52,"../util/options":53}],36:[function(require,module,exports){ var _DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; var _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = RopeJoint; var options = require("../util/options"); var create = require("../util/create"); var Settings = require("../Settings"); var Math = require("../common/Math"); var Vec2 = require("../common/Vec2"); var Vec3 = require("../common/Vec3"); var Mat22 = require("../common/Mat22"); var Mat33 = require("../common/Mat33"); var Rot = require("../common/Rot"); var Sweep = require("../common/Sweep"); var Transform = require("../common/Transform"); var Velocity = require("../common/Velocity"); var Position = require("../common/Position"); var Joint = require("../Joint"); var inactiveLimit = 0; var atLowerLimit = 1; var atUpperLimit = 2; var equalLimits = 3; RopeJoint.TYPE = "rope-joint"; RopeJoint._super = Joint; RopeJoint.prototype = create(RopeJoint._super.prototype); var RopeJointDef = { maxLength: 0 }; function RopeJoint(def, bodyA, bodyB, anchor) { if (!(this instanceof RopeJoint)) { return new RopeJoint(def, bodyA, bodyB, anchor); } def = options(def, RopeJointDef); Joint.call(this, def, bodyA, bodyB); this.m_type = RopeJoint.TYPE; this.m_localAnchorA = def.localAnchorA || bodyA.getLocalPoint(anchor); this.m_localAnchorB = def.localAnchorB || bodyB.getLocalPoint(anchor); this.m_maxLength = def.maxLength; this.m_mass = 0; this.m_impulse = 0; this.m_length = 0; this.m_state = inactiveLimit; this.m_u; this.m_rA; this.m_rB; this.m_localCenterA; this.m_localCenterB; this.m_invMassA; this.m_invMassB; this.m_invIA; this.m_invIB; this.m_mass; } RopeJoint.prototype.getLocalAnchorA = function() { return this.m_localAnchorA; }; RopeJoint.prototype.getLocalAnchorB = function() { return this.m_localAnchorB; }; RopeJoint.prototype.setMaxLength = function(length) { this.m_maxLength = length; }; RopeJoint.prototype.getMaxLength = function() { return this.m_maxLength; }; RopeJoint.prototype.getLimitState = function() { return this.m_state; }; RopeJoint.prototype.getAnchorA = function() { return this.m_bodyA.getWorldPoint(this.m_localAnchorA); }; RopeJoint.prototype.getAnchorB = function() { return this.m_bodyB.getWorldPoint(this.m_localAnchorB); }; RopeJoint.prototype.getReactionForce = function(inv_dt) { return Vec2.mul(this.m_impulse, this.m_u).mul(inv_dt); }; RopeJoint.prototype.getReactionTorque = function(inv_dt) { return 0; }; RopeJoint.prototype.initVelocityConstraints = function(step) { this.m_localCenterA = this.m_bodyA.m_sweep.localCenter; this.m_localCenterB = this.m_bodyB.m_sweep.localCenter; this.m_invMassA = this.m_bodyA.m_invMass; this.m_invMassB = this.m_bodyB.m_invMass; this.m_invIA = this.m_bodyA.m_invI; this.m_invIB = this.m_bodyB.m_invI; var cA = this.m_bodyA.c_position.c; var aA = this.m_bodyA.c_position.a; var vA = this.m_bodyA.c_velocity.v; var wA = this.m_bodyA.c_velocity.w; var cB = this.m_bodyB.c_position.c; var aB = this.m_bodyB.c_position.a; var vB = this.m_bodyB.c_velocity.v; var wB = this.m_bodyB.c_velocity.w; var qA = Rot.neo(aA); var qB = Rot.neo(aB); this.m_rA = Rot.mulSub(qA, this.m_localAnchorA, this.m_localCenterA); this.m_rB = Rot.mulSub(qB, this.m_localAnchorB, this.m_localCenterB); this.m_u = Vec2.zero(); this.m_u.addCombine(1, cB, 1, this.m_rB); this.m_u.subCombine(1, cA, 1, this.m_rA); this.m_length = this.m_u.length(); var C = this.m_length - this.m_maxLength; if (C > 0) { this.m_state = atUpperLimit; } else { this.m_state = inactiveLimit; } if (this.m_length > Settings.linearSlop) { this.m_u.mul(1 / this.m_length); } else { this.m_u.setZero(); this.m_mass = 0; this.m_impulse = 0; return; } var crA = Vec2.cross(this.m_rA, this.m_u); var crB = Vec2.cross(this.m_rB, this.m_u); var invMass = this.m_invMassA + this.m_invIA * crA * crA + this.m_invMassB + this.m_invIB * crB * crB; this.m_mass = invMass != 0 ? 1 / invMass : 0; if (step.warmStarting) { this.m_impulse *= step.dtRatio; var P = Vec2.mul(this.m_impulse, this.m_u); vA.subMul(this.m_invMassA, P); wA -= this.m_invIA * Vec2.cross(this.m_rA, P); vB.addMul(this.m_invMassB, P); wB += this.m_invIB * Vec2.cross(this.m_rB, P); } else { this.m_impulse = 0; } this.m_bodyA.c_velocity.v.set(vA); this.m_bodyA.c_velocity.w = wA; this.m_bodyB.c_velocity.v.set(vB); this.m_bodyB.c_velocity.w = wB; }; RopeJoint.prototype.solveVelocityConstraints = function(step) { var vA = this.m_bodyA.c_velocity.v; var wA = this.m_bodyA.c_velocity.w; var vB = this.m_bodyB.c_velocity.v; var wB = this.m_bodyB.c_velocity.w; var vpA = Vec2.addCross(vA, wA, this.m_rA); var vpB = Vec2.addCross(vB, wB, this.m_rB); var C = this.m_length - this.m_maxLength; var Cdot = Vec2.dot(this.m_u, Vec2.sub(vpB, vpA)); if (C < 0) { Cdot += step.inv_dt * C; } var impulse = -this.m_mass * Cdot; var oldImpulse = this.m_impulse; this.m_impulse = Math.min(0, this.m_impulse + impulse); impulse = this.m_impulse - oldImpulse; var P = Vec2.mul(impulse, this.m_u); vA.subMul(this.m_invMassA, P); wA -= this.m_invIA * Vec2.cross(this.m_rA, P); vB.addMul(this.m_invMassB, P); wB += this.m_invIB * Vec2.cross(this.m_rB, P); this.m_bodyA.c_velocity.v = vA; this.m_bodyA.c_velocity.w = wA; this.m_bodyB.c_velocity.v = vB; this.m_bodyB.c_velocity.w = wB; }; RopeJoint.prototype.solvePositionConstraints = function(step) { var cA = this.m_bodyA.c_position.c; var aA = this.m_bodyA.c_position.a; var cB = this.m_bodyB.c_position.c; var aB = this.m_bodyB.c_position.a; var qA = Rot.neo(aA); var qB = Rot.neo(aB); var rA = Rot.mulSub(qA, this.m_localAnchorA, this.m_localCenterA); var rB = Rot.mulSub(qB, this.m_localAnchorB, this.m_localCenterB); var u = Vec2.zero(); u.addCombine(1, cB, 1, rB); u.subCombine(1, cA, 1, rA); var length = u.normalize(); var C = length - this.m_maxLength; C = Math.clamp(C, 0, Settings.maxLinearCorrection); var impulse = -this.m_mass * C; var P = Vec2.mul(impulse, u); cA.subMul(this.m_invMassA, P); aA -= this.m_invIA * Vec2.cross(rA, P); cB.addMul(this.m_invMassB, P); aB += this.m_invIB * Vec2.cross(rB, P); this.m_bodyA.c_position.c.set(cA); this.m_bodyA.c_position.a = aA; this.m_bodyB.c_position.c.set(cB); this.m_bodyB.c_position.a = aB; return length - this.m_maxLength < Settings.linearSlop; }; },{"../Joint":5,"../Settings":7,"../common/Mat22":16,"../common/Mat33":17,"../common/Math":18,"../common/Position":19,"../common/Rot":20,"../common/Sweep":21,"../common/Transform":22,"../common/Vec2":23,"../common/Vec3":24,"../common/Velocity":25,"../util/create":52,"../util/options":53}],37:[function(require,module,exports){ var _DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; var _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = WeldJoint; var options = require("../util/options"); var create = require("../util/create"); var Settings = require("../Settings"); var Math = require("../common/Math"); var Vec2 = require("../common/Vec2"); var Vec3 = require("../common/Vec3"); var Mat22 = require("../common/Mat22"); var Mat33 = require("../common/Mat33"); var Rot = require("../common/Rot"); var Sweep = require("../common/Sweep"); var Transform = require("../common/Transform"); var Velocity = require("../common/Velocity"); var Position = require("../common/Position"); var Joint = require("../Joint"); WeldJoint.TYPE = "weld-joint"; WeldJoint._super = Joint; WeldJoint.prototype = create(WeldJoint._super.prototype); var WeldJointDef = { frequencyHz: 0, dampingRatio: 0 }; function WeldJoint(def, bodyA, bodyB, anchor) { if (!(this instanceof WeldJoint)) { return new WeldJoint(def, bodyA, bodyB, anchor); } def = options(def, WeldJointDef); Joint.call(this, def, bodyA, bodyB); this.m_type = WeldJoint.TYPE; this.m_localAnchorA = bodyA.getLocalPoint(anchor); this.m_localAnchorB = bodyB.getLocalPoint(anchor); this.m_referenceAngle = bodyB.getAngle() - bodyA.getAngle(); this.m_frequencyHz = def.frequencyHz; this.m_dampingRatio = def.dampingRatio; this.m_impulse = Vec3(); this.m_bias = 0; this.m_gamma = 0; this.m_rA; this.m_rB; this.m_localCenterA; this.m_localCenterB; this.m_invMassA; this.m_invMassB; this.m_invIA; this.m_invIB; this.m_mass = new Mat33(); } WeldJoint.prototype.getLocalAnchorA = function() { return this.m_localAnchorA; }; WeldJoint.prototype.getLocalAnchorB = function() { return this.m_localAnchorB; }; WeldJoint.prototype.getReferenceAngle = function() { return this.m_referenceAngle; }; WeldJoint.prototype.setFrequency = function(hz) { this.m_frequencyHz = hz; }; WeldJoint.prototype.getFrequency = function() { return this.m_frequencyHz; }; WeldJoint.prototype.setDampingRatio = function(ratio) { this.m_dampingRatio = ratio; }; WeldJoint.prototype.getDampingRatio = function() { return this.m_dampingRatio; }; WeldJoint.prototype.getAnchorA = function() { return this.m_bodyA.getWorldPoint(this.m_localAnchorA); }; WeldJoint.prototype.getAnchorB = function() { return this.m_bodyB.getWorldPoint(this.m_localAnchorB); }; WeldJoint.prototype.getReactionForce = function(inv_dt) { return Vec2.neo(this.m_impulse.x, this.m_impulse.y).mul(inv_dt); }; WeldJoint.prototype.getReactionTorque = function(inv_dt) { return inv_dt * this.m_impulse.z; }; WeldJoint.prototype.initVelocityConstraints = function(step) { this.m_localCenterA = this.m_bodyA.m_sweep.localCenter; this.m_localCenterB = this.m_bodyB.m_sweep.localCenter; this.m_invMassA = this.m_bodyA.m_invMass; this.m_invMassB = this.m_bodyB.m_invMass; this.m_invIA = this.m_bodyA.m_invI; this.m_invIB = this.m_bodyB.m_invI; var aA = this.m_bodyA.c_position.a; var vA = this.m_bodyA.c_velocity.v; var wA = this.m_bodyA.c_velocity.w; var aB = this.m_bodyB.c_position.a; var vB = this.m_bodyB.c_velocity.v; var wB = this.m_bodyB.c_velocity.w; var qA = Rot.neo(aA), qB = Rot.neo(aB); this.m_rA = Rot.mul(qA, Vec2.sub(this.m_localAnchorA, this.m_localCenterA)); this.m_rB = Rot.mul(qB, Vec2.sub(this.m_localAnchorB, this.m_localCenterB)); var mA = this.m_invMassA; var mB = this.m_invMassB; var iA = this.m_invIA; var iB = this.m_invIB; var K = new Mat33(); K.ex.x = mA + mB + this.m_rA.y * this.m_rA.y * iA + this.m_rB.y * this.m_rB.y * iB; K.ey.x = -this.m_rA.y * this.m_rA.x * iA - this.m_rB.y * this.m_rB.x * iB; K.ez.x = -this.m_rA.y * iA - this.m_rB.y * iB; K.ex.y = K.ey.x; K.ey.y = mA + mB + this.m_rA.x * this.m_rA.x * iA + this.m_rB.x * this.m_rB.x * iB; K.ez.y = this.m_rA.x * iA + this.m_rB.x * iB; K.ex.z = K.ez.x; K.ey.z = K.ez.y; K.ez.z = iA + iB; if (this.m_frequencyHz > 0) { K.getInverse22(this.m_mass); var invM = iA + iB; var m = invM > 0 ? 1 / invM : 0; var C = aB - aA - this.m_referenceAngle; var omega = 2 * Math.PI * this.m_frequencyHz; var d = 2 * m * this.m_dampingRatio * omega; var k = m * omega * omega; var h = step.dt; this.m_gamma = h * (d + h * k); this.m_gamma = this.m_gamma != 0 ? 1 / this.m_gamma : 0; this.m_bias = C * h * k * this.m_gamma; invM += this.m_gamma; this.m_mass.ez.z = invM != 0 ? 1 / invM : 0; } else if (K.ez.z == 0) { K.getInverse22(this.m_mass); this.m_gamma = 0; this.m_bias = 0; } else { K.getSymInverse33(this.m_mass); this.m_gamma = 0; this.m_bias = 0; } if (step.warmStarting) { this.m_impulse.mul(step.dtRatio); var P = Vec2.neo(this.m_impulse.x, this.m_impulse.y); vA.subMul(mA, P); wA -= iA * (Vec2.cross(this.m_rA, P) + this.m_impulse.z); vB.addMul(mB, P); wB += iB * (Vec2.cross(this.m_rB, P) + this.m_impulse.z); } else { this.m_impulse.setZero(); } this.m_bodyA.c_velocity.v = vA; this.m_bodyA.c_velocity.w = wA; this.m_bodyB.c_velocity.v = vB; this.m_bodyB.c_velocity.w = wB; }; WeldJoint.prototype.solveVelocityConstraints = function(step) { var vA = this.m_bodyA.c_velocity.v; var wA = this.m_bodyA.c_velocity.w; var vB = this.m_bodyB.c_velocity.v; var wB = this.m_bodyB.c_velocity.w; var mA = this.m_invMassA; var mB = this.m_invMassB; var iA = this.m_invIA; var iB = this.m_invIB; if (this.m_frequencyHz > 0) { var Cdot2 = wB - wA; var impulse2 = -this.m_mass.ez.z * (Cdot2 + this.m_bias + this.m_gamma * this.m_impulse.z); this.m_impulse.z += impulse2; wA -= iA * impulse2; wB += iB * impulse2; var Cdot1 = Vec2.zero(); Cdot1.addCombine(1, vB, 1, Vec2.cross(wB, this.m_rB)); Cdot1.subCombine(1, vA, 1, Vec2.cross(wA, this.m_rA)); var impulse1 = Vec2.neg(Mat33.mul(this.m_mass, Cdot1)); this.m_impulse.x += impulse1.x; this.m_impulse.y += impulse1.y; var P = Vec2.clone(impulse1); vA.subMul(mA, P); wA -= iA * Vec2.cross(this.m_rA, P); vB.addMul(mB, P); wB += iB * Vec2.cross(this.m_rB, P); } else { var Cdot1 = Vec2.zero(); Cdot1.addCombine(1, vB, 1, Vec2.cross(wB, this.m_rB)); Cdot1.subCombine(1, vA, 1, Vec2.cross(wA, this.m_rA)); var Cdot2 = wB - wA; var Cdot = Vec3(Cdot1.x, Cdot1.y, Cdot2); var impulse = Vec3.neg(Mat33.mul(this.m_mass, Cdot)); this.m_impulse.add(impulse); var P = Vec2.neo(impulse.x, impulse.y); vA.subMul(mA, P); wA -= iA * (Vec2.cross(this.m_rA, P) + impulse.z); vB.addMul(mB, P); wB += iB * (Vec2.cross(this.m_rB, P) + impulse.z); } this.m_bodyA.c_velocity.v = vA; this.m_bodyA.c_velocity.w = wA; this.m_bodyB.c_velocity.v = vB; this.m_bodyB.c_velocity.w = wB; }; WeldJoint.prototype.solvePositionConstraints = function(step) { var cA = this.m_bodyA.c_position.c; var aA = this.m_bodyA.c_position.a; var cB = this.m_bodyB.c_position.c; var aB = this.m_bodyB.c_position.a; var qA = Rot.neo(aA), qB = Rot.neo(aB); var mA = this.m_invMassA, mB = this.m_invMassB; var iA = this.m_invIA, iB = this.m_invIB; var rA = Rot.mul(qA, Vec2.sub(this.m_localAnchorA, this.m_localCenterA)); var rB = Rot.mul(qB, Vec2.sub(this.m_localAnchorB, this.m_localCenterB)); var positionError, angularError; var K = new Mat33(); K.ex.x = mA + mB + rA.y * rA.y * iA + rB.y * rB.y * iB; K.ey.x = -rA.y * rA.x * iA - rB.y * rB.x * iB; K.ez.x = -rA.y * iA - rB.y * iB; K.ex.y = K.ey.x; K.ey.y = mA + mB + rA.x * rA.x * iA + rB.x * rB.x * iB; K.ez.y = rA.x * iA + rB.x * iB; K.ex.z = K.ez.x; K.ey.z = K.ez.y; K.ez.z = iA + iB; if (this.m_frequencyHz > 0) { var C1 = Vec2.zero(); C1.addCombine(1, cB, 1, rB); C1.subCombine(1, cA, 1, rA); positionError = C1.length(); angularError = 0; var P = Vec2.neg(K.solve22(C1)); cA.subMul(mA, P); aA -= iA * Vec2.cross(rA, P); cB.addMul(mB, P); aB += iB * Vec2.cross(rB, P); } else { var C1 = Vec2.zero(); C1.addCombine(1, cB, 1, rB); C1.subCombine(1, cA, 1, rA); var C2 = aB - aA - this.m_referenceAngle; positionError = C1.length(); angularError = Math.abs(C2); var C = Vec3(C1.x, C1.y, C2); var impulse = Vec3(); if (K.ez.z > 0) { impulse = Vec3.neg(K.solve33(C)); } else { var impulse2 = Vec2.neg(K.solve22(C1)); impulse.set(impulse2.x, impulse2.y, 0); } var P = Vec2.neo(impulse.x, impulse.y); cA.subMul(mA, P); aA -= iA * (Vec2.cross(rA, P) + impulse.z); cB.addMul(mB, P); aB += iB * (Vec2.cross(rB, P) + impulse.z); } this.m_bodyA.c_position.c = cA; this.m_bodyA.c_position.a = aA; this.m_bodyB.c_position.c = cB; this.m_bodyB.c_position.a = aB; return positionError <= Settings.linearSlop && angularError <= Settings.angularSlop; }; },{"../Joint":5,"../Settings":7,"../common/Mat22":16,"../common/Mat33":17,"../common/Math":18,"../common/Position":19,"../common/Rot":20,"../common/Sweep":21,"../common/Transform":22,"../common/Vec2":23,"../common/Vec3":24,"../common/Velocity":25,"../util/create":52,"../util/options":53}],38:[function(require,module,exports){ var _DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; var _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = WheelJoint; var options = require("../util/options"); var create = require("../util/create"); var Settings = require("../Settings"); var Math = require("../common/Math"); var Vec2 = require("../common/Vec2"); var Vec3 = require("../common/Vec3"); var Mat22 = require("../common/Mat22"); var Mat33 = require("../common/Mat33"); var Rot = require("../common/Rot"); var Sweep = require("../common/Sweep"); var Transform = require("../common/Transform"); var Velocity = require("../common/Velocity"); var Position = require("../common/Position"); var Joint = require("../Joint"); WheelJoint.TYPE = "wheel-joint"; WheelJoint._super = Joint; WheelJoint.prototype = create(WheelJoint._super.prototype); var WheelJointDef = { enableMotor: false, maxMotorTorque: 0, motorSpeed: 0, frequencyHz: 2, dampingRatio: .7 }; function WheelJoint(def, bodyA, bodyB, anchor, axis) { if (!(this instanceof WheelJoint)) { return new WheelJoint(def, bodyA, bodyB, anchor, axis); } def = options(def, WheelJointDef); Joint.call(this, def, bodyA, bodyB); this.m_type = WheelJoint.TYPE; this.m_localAnchorA = bodyA.getLocalPoint(anchor); this.m_localAnchorB = bodyB.getLocalPoint(anchor); this.m_localXAxisA = bodyA.getLocalVector(axis || Vec2.neo(1, 0)); this.m_localYAxisA = Vec2.cross(1, this.m_localXAxisA); this.m_mass = 0; this.m_impulse = 0; this.m_motorMass = 0; this.m_motorImpulse = 0; this.m_springMass = 0; this.m_springImpulse = 0; this.m_maxMotorTorque = def.maxMotorTorque; this.m_motorSpeed = def.motorSpeed; this.m_enableMotor = def.enableMotor; this.m_frequencyHz = def.frequencyHz; this.m_dampingRatio = def.dampingRatio; this.m_bias = 0; this.m_gamma = 0; this.m_localCenterA; this.m_localCenterB; this.m_invMassA; this.m_invMassB; this.m_invIA; this.m_invIB; this.m_ax = Vec2.zero(); this.m_ay = Vec2.zero(); this.m_sAx; this.m_sBx; this.m_sAy; this.m_sBy; } WheelJoint.prototype.getLocalAnchorA = function() { return this.m_localAnchorA; }; WheelJoint.prototype.getLocalAnchorB = function() { return this.m_localAnchorB; }; WheelJoint.prototype.getLocalAxisA = function() { return this.m_localXAxisA; }; WheelJoint.prototype.getJointTranslation = function() { var bA = this.m_bodyA; var bB = this.m_bodyB; var pA = bA.getWorldPoint(this.m_localAnchorA); var pB = bB.getWorldPoint(this.m_localAnchorB); var d = Vec2.sub(pB, pA); var axis = bA.getWorldVector(this.m_localXAxisA); var translation = Vec2.dot(d, axis); return translation; }; WheelJoint.prototype.getJointSpeed = function() { var wA = this.m_bodyA.m_angularVelocity; var wB = this.m_bodyB.m_angularVelocity; return wB - wA; }; WheelJoint.prototype.isMotorEnabled = function() { return this.m_enableMotor; }; WheelJoint.prototype.enableMotor = function(flag) { this.m_bodyA.setAwake(true); this.m_bodyB.setAwake(true); this.m_enableMotor = flag; }; WheelJoint.prototype.setMotorSpeed = function(speed) { this.m_bodyA.setAwake(true); this.m_bodyB.setAwake(true); this.m_motorSpeed = speed; }; WheelJoint.prototype.getMotorSpeed = function() { return this.m_motorSpeed; }; WheelJoint.prototype.setMaxMotorTorque = function(torque) { this.m_bodyA.setAwake(true); this.m_bodyB.setAwake(true); this.m_maxMotorTorque = torque; }; WheelJoint.prototype.getMaxMotorTorque = function() { return this.m_maxMotorTorque; }; WheelJoint.prototype.getMotorTorque = function(inv_dt) { return inv_dt * this.m_motorImpulse; }; WheelJoint.prototype.setSpringFrequencyHz = function(hz) { this.m_frequencyHz = hz; }; WheelJoint.prototype.getSpringFrequencyHz = function() { return this.m_frequencyHz; }; WheelJoint.prototype.setSpringDampingRatio = function(ratio) { this.m_dampingRatio = ratio; }; WheelJoint.prototype.getSpringDampingRatio = function() { return this.m_dampingRatio; }; WheelJoint.prototype.getAnchorA = function() { return this.m_bodyA.getWorldPoint(this.m_localAnchorA); }; WheelJoint.prototype.getAnchorB = function() { return this.m_bodyB.getWorldPoint(this.m_localAnchorB); }; WheelJoint.prototype.getReactionForce = function(inv_dt) { return Vec2.combine(this.m_impulse, this.m_ay, this.m_springImpulse, this.m_ax).mul(inv_dt); }; WheelJoint.prototype.getReactionTorque = function(inv_dt) { return inv_dt * this.m_motorImpulse; }; WheelJoint.prototype.initVelocityConstraints = function(step) { this.m_localCenterA = this.m_bodyA.m_sweep.localCenter; this.m_localCenterB = this.m_bodyB.m_sweep.localCenter; this.m_invMassA = this.m_bodyA.m_invMass; this.m_invMassB = this.m_bodyB.m_invMass; this.m_invIA = this.m_bodyA.m_invI; this.m_invIB = this.m_bodyB.m_invI; var mA = this.m_invMassA; var mB = this.m_invMassB; var iA = this.m_invIA; var iB = this.m_invIB; var cA = this.m_bodyA.c_position.c; var aA = this.m_bodyA.c_position.a; var vA = this.m_bodyA.c_velocity.v; var wA = this.m_bodyA.c_velocity.w; var cB = this.m_bodyB.c_position.c; var aB = this.m_bodyB.c_position.a; var vB = this.m_bodyB.c_velocity.v; var wB = this.m_bodyB.c_velocity.w; var qA = Rot.neo(aA); var qB = Rot.neo(aB); var rA = Rot.mul(qA, Vec2.sub(this.m_localAnchorA, this.m_localCenterA)); var rB = Rot.mul(qB, Vec2.sub(this.m_localAnchorB, this.m_localCenterB)); var d = Vec2.zero(); d.addCombine(1, cB, 1, rB); d.subCombine(1, cA, 1, rA); { this.m_ay = Rot.mul(qA, this.m_localYAxisA); this.m_sAy = Vec2.cross(Vec2.add(d, rA), this.m_ay); this.m_sBy = Vec2.cross(rB, this.m_ay); this.m_mass = mA + mB + iA * this.m_sAy * this.m_sAy + iB * this.m_sBy * this.m_sBy; if (this.m_mass > 0) { this.m_mass = 1 / this.m_mass; } } this.m_springMass = 0; this.m_bias = 0; this.m_gamma = 0; if (this.m_frequencyHz > 0) { this.m_ax = Rot.mul(qA, this.m_localXAxisA); this.m_sAx = Vec2.cross(Vec2.add(d, rA), this.m_ax); this.m_sBx = Vec2.cross(rB, this.m_ax); var invMass = mA + mB + iA * this.m_sAx * this.m_sAx + iB * this.m_sBx * this.m_sBx; if (invMass > 0) { this.m_springMass = 1 / invMass; var C = Vec2.dot(d, this.m_ax); var omega = 2 * Math.PI * this.m_frequencyHz; var d = 2 * this.m_springMass * this.m_dampingRatio * omega; var k = this.m_springMass * omega * omega; var h = step.dt; this.m_gamma = h * (d + h * k); if (this.m_gamma > 0) { this.m_gamma = 1 / this.m_gamma; } this.m_bias = C * h * k * this.m_gamma; this.m_springMass = invMass + this.m_gamma; if (this.m_springMass > 0) { this.m_springMass = 1 / this.m_springMass; } } } else { this.m_springImpulse = 0; } if (this.m_enableMotor) { this.m_motorMass = iA + iB; if (this.m_motorMass > 0) { this.m_motorMass = 1 / this.m_motorMass; } } else { this.m_motorMass = 0; this.m_motorImpulse = 0; } if (step.warmStarting) { this.m_impulse *= step.dtRatio; this.m_springImpulse *= step.dtRatio; this.m_motorImpulse *= step.dtRatio; var P = Vec2.combine(this.m_impulse, this.m_ay, this.m_springImpulse, this.m_ax); var LA = this.m_impulse * this.m_sAy + this.m_springImpulse * this.m_sAx + this.m_motorImpulse; var LB = this.m_impulse * this.m_sBy + this.m_springImpulse * this.m_sBx + this.m_motorImpulse; vA.subMul(this.m_invMassA, P); wA -= this.m_invIA * LA; vB.addMul(this.m_invMassB, P); wB += this.m_invIB * LB; } else { this.m_impulse = 0; this.m_springImpulse = 0; this.m_motorImpulse = 0; } this.m_bodyA.c_velocity.v.set(vA); this.m_bodyA.c_velocity.w = wA; this.m_bodyB.c_velocity.v.set(vB); this.m_bodyB.c_velocity.w = wB; }; WheelJoint.prototype.solveVelocityConstraints = function(step) { var mA = this.m_invMassA; var mB = this.m_invMassB; var iA = this.m_invIA; var iB = this.m_invIB; var vA = this.m_bodyA.c_velocity.v; var wA = this.m_bodyA.c_velocity.w; var vB = this.m_bodyB.c_velocity.v; var wB = this.m_bodyB.c_velocity.w; { var Cdot = Vec2.dot(this.m_ax, vB) - Vec2.dot(this.m_ax, vA) + this.m_sBx * wB - this.m_sAx * wA; var impulse = -this.m_springMass * (Cdot + this.m_bias + this.m_gamma * this.m_springImpulse); this.m_springImpulse += impulse; var P = Vec2.mul(impulse, this.m_ax); var LA = impulse * this.m_sAx; var LB = impulse * this.m_sBx; vA.subMul(mA, P); wA -= iA * LA; vB.addMul(mB, P); wB += iB * LB; } { var Cdot = wB - wA - this.m_motorSpeed; var impulse = -this.m_motorMass * Cdot; var oldImpulse = this.m_motorImpulse; var maxImpulse = step.dt * this.m_maxMotorTorque; this.m_motorImpulse = Math.clamp(this.m_motorImpulse + impulse, -maxImpulse, maxImpulse); impulse = this.m_motorImpulse - oldImpulse; wA -= iA * impulse; wB += iB * impulse; } { var Cdot = Vec2.dot(this.m_ay, vB) - Vec2.dot(this.m_ay, vA) + this.m_sBy * wB - this.m_sAy * wA; var impulse = -this.m_mass * Cdot; this.m_impulse += impulse; var P = Vec2.mul(impulse, this.m_ay); var LA = impulse * this.m_sAy; var LB = impulse * this.m_sBy; vA.subMul(mA, P); wA -= iA * LA; vB.addMul(mB, P); wB += iB * LB; } this.m_bodyA.c_velocity.v.set(vA); this.m_bodyA.c_velocity.w = wA; this.m_bodyB.c_velocity.v.set(vB); this.m_bodyB.c_velocity.w = wB; }; WheelJoint.prototype.solvePositionConstraints = function(step) { var cA = this.m_bodyA.c_position.c; var aA = this.m_bodyA.c_position.a; var cB = this.m_bodyB.c_position.c; var aB = this.m_bodyB.c_position.a; var qA = Rot.neo(aA); var qB = Rot.neo(aB); var rA = Rot.mul(qA, Vec2.sub(this.m_localAnchorA, this.m_localCenterA)); var rB = Rot.mul(qB, Vec2.sub(this.m_localAnchorB, this.m_localCenterB)); var d = Vec2.zero(); d.addCombine(1, cB, 1, rB); d.subCombine(1, cA, 1, rA); var ay = Rot.mul(qA, this.m_localYAxisA); var sAy = Vec2.cross(Vec2.add(d, rA), ay); var sBy = Vec2.cross(rB, ay); var C = Vec2.dot(d, ay); var k = this.m_invMassA + this.m_invMassB + this.m_invIA * this.m_sAy * this.m_sAy + this.m_invIB * this.m_sBy * this.m_sBy; var impulse; if (k != 0) { impulse = -C / k; } else { impulse = 0; } var P = Vec2.mul(impulse, ay); var LA = impulse * sAy; var LB = impulse * sBy; cA.subMul(this.m_invMassA, P); aA -= this.m_invIA * LA; cB.addMul(this.m_invMassB, P); aB += this.m_invIB * LB; this.m_bodyA.c_position.c.set(cA); this.m_bodyA.c_position.a = aA; this.m_bodyB.c_position.c.set(cB); this.m_bodyB.c_position.a = aB; return Math.abs(C) <= Settings.linearSlop; }; },{"../Joint":5,"../Settings":7,"../common/Mat22":16,"../common/Mat33":17,"../common/Math":18,"../common/Position":19,"../common/Rot":20,"../common/Sweep":21,"../common/Transform":22,"../common/Vec2":23,"../common/Vec3":24,"../common/Velocity":25,"../util/create":52,"../util/options":53}],39:[function(require,module,exports){ var _DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; var _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = BoxShape; var common = require("../util/common"); var create = require("../util/create"); var PolygonShape = require("./PolygonShape"); BoxShape._super = PolygonShape; BoxShape.prototype = create(BoxShape._super.prototype); BoxShape.TYPE = "polygon"; function BoxShape(hx, hy, center, angle) { if (!(this instanceof BoxShape)) { return new BoxShape(hx, hy, center, angle); } BoxShape._super.call(this); this._setAsBox(hx, hy, center, angle); } },{"../util/common":51,"../util/create":52,"./PolygonShape":48}],40:[function(require,module,exports){ var _DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; var _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = ChainShape; var common = require("../util/common"); var create = require("../util/create"); var options = require("../util/options"); var Math = require("../common/Math"); var Transform = require("../common/Transform"); var Rot = require("../common/Rot"); var Vec2 = require("../common/Vec2"); var AABB = require("../collision/AABB"); var Settings = require("../Settings"); var Shape = require("../Shape"); var EdgeShape = require("./EdgeShape"); ChainShape._super = Shape; ChainShape.prototype = create(ChainShape._super.prototype); ChainShape.TYPE = "chain"; function ChainShape(vertices, loop) { if (!(this instanceof ChainShape)) { return new ChainShape(vertices, loop); } ChainShape._super.call(this); this.m_type = ChainShape.TYPE; this.m_radius = Settings.polygonRadius; this.m_vertices = []; this.m_count = 0; this.m_prevVertex = null; this.m_nextVertex = null; this.m_hasPrevVertex = false; this.m_hasNextVertex = false; if (vertices && vertices.length) { if (loop) { this._createLoop(vertices); } else { this._createChain(vertices); } } } ChainShape.prototype._createLoop = function(vertices) { _ASSERT && common.assert(this.m_vertices.length == 0 && this.m_count == 0); _ASSERT && common.assert(vertices.length >= 3); for (var i = 1; i < vertices.length; ++i) { var v1 = vertices[i - 1]; var v2 = vertices[i]; _ASSERT && common.assert(Vec2.distanceSquared(v1, v2) > Settings.linearSlopSquared); } this.m_vertices.length = 0; this.m_count = vertices.length + 1; for (var i = 0; i < vertices.length; ++i) { this.m_vertices[i] = vertices[i].clone(); } this.m_vertices[vertices.length] = vertices[0].clone(); this.m_prevVertex = this.m_vertices[this.m_count - 2]; this.m_nextVertex = this.m_vertices[1]; this.m_hasPrevVertex = true; this.m_hasNextVertex = true; return this; }; ChainShape.prototype._createChain = function(vertices) { _ASSERT && common.assert(this.m_vertices.length == 0 && this.m_count == 0); _ASSERT && common.assert(vertices.length >= 2); for (var i = 1; i < vertices.length; ++i) { var v1 = vertices[i - 1]; var v2 = vertices[i]; _ASSERT && common.assert(Vec2.distanceSquared(v1, v2) > Settings.linearSlopSquared); } this.m_count = vertices.length; for (var i = 0; i < vertices.length; ++i) { this.m_vertices[i] = vertices[i].clone(); } this.m_hasPrevVertex = false; this.m_hasNextVertex = false; this.m_prevVertex = null; this.m_nextVertex = null; return this; }; ChainShape.prototype._setPrevVertex = function(prevVertex) { this.m_prevVertex = prevVertex; this.m_hasPrevVertex = true; }; ChainShape.prototype._setNextVertex = function(nextVertex) { this.m_nextVertex = nextVertex; this.m_hasNextVertex = true; }; ChainShape.prototype._clone = function() { var clone = new ChainShape(); clone.createChain(this.m_vertices); clone.m_type = this.m_type; clone.m_radius = this.m_radius; clone.m_prevVertex = this.m_prevVertex; clone.m_nextVertex = this.m_nextVertex; clone.m_hasPrevVertex = this.m_hasPrevVertex; clone.m_hasNextVertex = this.m_hasNextVertex; return clone; }; ChainShape.prototype.getChildCount = function() { return this.m_count - 1; }; ChainShape.prototype.getChildEdge = function(edge, childIndex) { _ASSERT && common.assert(0 <= childIndex && childIndex < this.m_count - 1); edge.m_type = EdgeShape.TYPE; edge.m_radius = this.m_radius; edge.m_vertex1 = this.m_vertices[childIndex]; edge.m_vertex2 = this.m_vertices[childIndex + 1]; if (childIndex > 0) { edge.m_vertex0 = this.m_vertices[childIndex - 1]; edge.m_hasVertex0 = true; } else { edge.m_vertex0 = this.m_prevVertex; edge.m_hasVertex0 = this.m_hasPrevVertex; } if (childIndex < this.m_count - 2) { edge.m_vertex3 = this.m_vertices[childIndex + 2]; edge.m_hasVertex3 = true; } else { edge.m_vertex3 = this.m_nextVertex; edge.m_hasVertex3 = this.m_hasNextVertex; } }; ChainShape.prototype.getVertex = function(index) { _ASSERT && common.assert(0 <= index && index <= this.m_count); if (index < this.m_count) { return this.m_vertices[index]; } else { return this.m_vertices[0]; } }; ChainShape.prototype.testPoint = function(xf, p) { return false; }; ChainShape.prototype.rayCast = function(output, input, xf, childIndex) { _ASSERT && common.assert(0 <= childIndex && childIndex < this.m_count); var edgeShape = new EdgeShape(this.getVertex(childIndex), this.getVertex(childIndex + 1)); return edgeShape.rayCast(output, input, xf, 0); }; ChainShape.prototype.computeAABB = function(aabb, xf, childIndex) { _ASSERT && common.assert(0 <= childIndex && childIndex < this.m_count); var v1 = Transform.mul(xf, this.getVertex(childIndex)); var v2 = Transform.mul(xf, this.getVertex(childIndex + 1)); aabb.combine(v1, v2); }; ChainShape.prototype.computeMass = function(massData, density) { massData.mass = 0; massData.center = Vec2.neo(); massData.I = 0; }; ChainShape.prototype.computeDistanceProxy = function(proxy, childIndex) { _ASSERT && common.assert(0 <= childIndex && childIndex < this.m_count); proxy.m_buffer[0] = this.getVertex(childIndex); proxy.m_buffer[1] = this.getVertex(childIndex + 1); proxy.m_vertices = proxy.m_buffer; proxy.m_count = 2; proxy.m_radius = this.m_radius; }; },{"../Settings":7,"../Shape":8,"../collision/AABB":11,"../common/Math":18,"../common/Rot":20,"../common/Transform":22,"../common/Vec2":23,"../util/common":51,"../util/create":52,"../util/options":53,"./EdgeShape":47}],41:[function(require,module,exports){ var _DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; var _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = CircleShape; var common = require("../util/common"); var create = require("../util/create"); var options = require("../util/options"); var Math = require("../common/Math"); var Transform = require("../common/Transform"); var Rot = require("../common/Rot"); var Vec2 = require("../common/Vec2"); var AABB = require("../collision/AABB"); var Settings = require("../Settings"); var Shape = require("../Shape"); CircleShape._super = Shape; CircleShape.prototype = create(CircleShape._super.prototype); CircleShape.TYPE = "circle"; function CircleShape(a, b) { if (!(this instanceof CircleShape)) { return new CircleShape(a, b); } CircleShape._super.call(this); this.m_type = CircleShape.TYPE; this.m_p = Vec2.zero(); this.m_radius = 1; if (typeof a === "object" && Vec2.isValid(a)) { this.m_p.set(a); if (typeof b === "number") { this.m_radius = b; } } else if (typeof a === "number") { this.m_radius = a; } } CircleShape.prototype.getRadius = function() { return this.m_radius; }; CircleShape.prototype.getCenter = function() { return this.m_p; }; CircleShape.prototype.getVertex = function(index) { _ASSERT && common.assert(index == 0); return this.m_p; }; CircleShape.prototype.getVertexCount = function(index) { return 1; }; CircleShape.prototype._clone = function() { var clone = new CircleShape(); clone.m_type = this.m_type; clone.m_radius = this.m_radius; clone.m_p = this.m_p.clone(); return clone; }; CircleShape.prototype.getChildCount = function() { return 1; }; CircleShape.prototype.testPoint = function(xf, p) { var center = Vec2.add(xf.p, Rot.mul(xf.q, this.m_p)); var d = Vec2.sub(p, center); return Vec2.dot(d, d) <= this.m_radius * this.m_radius; }; CircleShape.prototype.rayCast = function(output, input, xf, childIndex) { var position = Vec2.add(xf.p, Rot.mul(xf.q, this.m_p)); var s = Vec2.sub(input.p1, position); var b = Vec2.dot(s, s) - this.m_radius * this.m_radius; var r = Vec2.sub(input.p2, input.p1); var c = Vec2.dot(s, r); var rr = Vec2.dot(r, r); var sigma = c * c - rr * b; if (sigma < 0 || rr < Math.EPSILON) { return false; } var a = -(c + Math.sqrt(sigma)); if (0 <= a && a <= input.maxFraction * rr) { a /= rr; output.fraction = a; output.normal = Vec2.add(s, Vec2.mul(a, r)); output.normal.normalize(); return true; } return false; }; CircleShape.prototype.computeAABB = function(aabb, xf, childIndex) { var p = Vec2.add(xf.p, Rot.mul(xf.q, this.m_p)); aabb.lowerBound.set(p.x - this.m_radius, p.y - this.m_radius); aabb.upperBound.set(p.x + this.m_radius, p.y + this.m_radius); }; CircleShape.prototype.computeMass = function(massData, density) { massData.mass = density * Math.PI * this.m_radius * this.m_radius; massData.center = this.m_p; massData.I = massData.mass * (.5 * this.m_radius * this.m_radius + Vec2.dot(this.m_p, this.m_p)); }; CircleShape.prototype.computeDistanceProxy = function(proxy) { proxy.m_vertices.push(this.m_p); proxy.m_count = 1; proxy.m_radius = this.m_radius; }; },{"../Settings":7,"../Shape":8,"../collision/AABB":11,"../common/Math":18,"../common/Rot":20,"../common/Transform":22,"../common/Vec2":23,"../util/common":51,"../util/create":52,"../util/options":53}],42:[function(require,module,exports){ var _DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; var _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; var common = require("../util/common"); var create = require("../util/create"); var Math = require("../common/Math"); var Transform = require("../common/Transform"); var Vec2 = require("../common/Vec2"); var Settings = require("../Settings"); var Shape = require("../Shape"); var Contact = require("../Contact"); var Manifold = require("../Manifold"); var CircleShape = require("./CircleShape"); Contact.addType(CircleShape.TYPE, CircleShape.TYPE, CircleCircleContact); function CircleCircleContact(manifold, xfA, fixtureA, indexA, xfB, fixtureB, indexB) { _ASSERT && common.assert(fixtureA.getType() == CircleShape.TYPE); _ASSERT && common.assert(fixtureB.getType() == CircleShape.TYPE); CollideCircles(manifold, fixtureA.getShape(), xfA, fixtureB.getShape(), xfB); } function CollideCircles(manifold, circleA, xfA, circleB, xfB) { manifold.pointCount = 0; var pA = Transform.mul(xfA, circleA.m_p); var pB = Transform.mul(xfB, circleB.m_p); var distSqr = Vec2.distanceSquared(pB, pA); var rA = circleA.m_radius; var rB = circleB.m_radius; var radius = rA + rB; if (distSqr > radius * radius) { return; } manifold.type = Manifold.e_circles; manifold.localPoint.set(circleA.m_p); manifold.localNormal.setZero(); manifold.pointCount = 1; manifold.points[0].localPoint.set(circleB.m_p); manifold.points[0].id.key = 0; } exports.CollideCircles = CollideCircles; },{"../Contact":3,"../Manifold":6,"../Settings":7,"../Shape":8,"../common/Math":18,"../common/Transform":22,"../common/Vec2":23,"../util/common":51,"../util/create":52,"./CircleShape":41}],43:[function(require,module,exports){ var _DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; var _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; var common = require("../util/common"); var Math = require("../common/Math"); var Transform = require("../common/Transform"); var Rot = require("../common/Rot"); var Vec2 = require("../common/Vec2"); var AABB = require("../collision/AABB"); var Settings = require("../Settings"); var Manifold = require("../Manifold"); var Contact = require("../Contact"); var Shape = require("../Shape"); var CircleShape = require("./CircleShape"); var PolygonShape = require("./PolygonShape"); Contact.addType(PolygonShape.TYPE, CircleShape.TYPE, PolygonCircleContact); function PolygonCircleContact(manifold, xfA, fixtureA, indexA, xfB, fixtureB, indexB) { _ASSERT && common.assert(fixtureA.getType() == PolygonShape.TYPE); _ASSERT && common.assert(fixtureB.getType() == CircleShape.TYPE); CollidePolygonCircle(manifold, fixtureA.getShape(), xfA, fixtureB.getShape(), xfB); } function CollidePolygonCircle(manifold, polygonA, xfA, circleB, xfB) { manifold.pointCount = 0; var c = Transform.mul(xfB, circleB.m_p); var cLocal = Transform.mulT(xfA, c); var normalIndex = 0; var separation = -Infinity; var radius = polygonA.m_radius + circleB.m_radius; var vertexCount = polygonA.m_count; var vertices = polygonA.m_vertices; var normals = polygonA.m_normals; for (var i = 0; i < vertexCount; ++i) { var s = Vec2.dot(normals[i], Vec2.sub(cLocal, vertices[i])); if (s > radius) { return; } if (s > separation) { separation = s; normalIndex = i; } } var vertIndex1 = normalIndex; var vertIndex2 = vertIndex1 + 1 < vertexCount ? vertIndex1 + 1 : 0; var v1 = vertices[vertIndex1]; var v2 = vertices[vertIndex2]; if (separation < Math.EPSILON) { manifold.pointCount = 1; manifold.type = Manifold.e_faceA; manifold.localNormal.set(normals[normalIndex]); manifold.localPoint.setCombine(.5, v1, .5, v2); manifold.points[0].localPoint = circleB.m_p; manifold.points[0].id.key = 0; return; } var u1 = Vec2.dot(Vec2.sub(cLocal, v1), Vec2.sub(v2, v1)); var u2 = Vec2.dot(Vec2.sub(cLocal, v2), Vec2.sub(v1, v2)); if (u1 <= 0) { if (Vec2.distanceSquared(cLocal, v1) > radius * radius) { return; } manifold.pointCount = 1; manifold.type = Manifold.e_faceA; manifold.localNormal.setCombine(1, cLocal, -1, v1); manifold.localNormal.normalize(); manifold.localPoint = v1; manifold.points[0].localPoint.set(circleB.m_p); manifold.points[0].id.key = 0; } else if (u2 <= 0) { if (Vec2.distanceSquared(cLocal, v2) > radius * radius) { return; } manifold.pointCount = 1; manifold.type = Manifold.e_faceA; manifold.localNormal.setCombine(1, cLocal, -1, v2); manifold.localNormal.normalize(); manifold.localPoint.set(v2); manifold.points[0].localPoint.set(circleB.m_p); manifold.points[0].id.key = 0; } else { var faceCenter = Vec2.mid(v1, v2); var separation = Vec2.dot(cLocal, normals[vertIndex1]) - Vec2.dot(faceCenter, normals[vertIndex1]); if (separation > radius) { return; } manifold.pointCount = 1; manifold.type = Manifold.e_faceA; manifold.localNormal.set(normals[vertIndex1]); manifold.localPoint.set(faceCenter); manifold.points[0].localPoint.set(circleB.m_p); manifold.points[0].id.key = 0; } } },{"../Contact":3,"../Manifold":6,"../Settings":7,"../Shape":8,"../collision/AABB":11,"../common/Math":18,"../common/Rot":20,"../common/Transform":22,"../common/Vec2":23,"../util/common":51,"./CircleShape":41,"./PolygonShape":48}],44:[function(require,module,exports){ var _DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; var _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; var common = require("../util/common"); var create = require("../util/create"); var Math = require("../common/Math"); var Transform = require("../common/Transform"); var Vec2 = require("../common/Vec2"); var Rot = require("../common/Rot"); var Settings = require("../Settings"); var Shape = require("../Shape"); var Contact = require("../Contact"); var Manifold = require("../Manifold"); var EdgeShape = require("./EdgeShape"); var ChainShape = require("./ChainShape"); var CircleShape = require("./CircleShape"); Contact.addType(EdgeShape.TYPE, CircleShape.TYPE, EdgeCircleContact); Contact.addType(ChainShape.TYPE, CircleShape.TYPE, ChainCircleContact); function EdgeCircleContact(manifold, xfA, fixtureA, indexA, xfB, fixtureB, indexB) { _ASSERT && common.assert(fixtureA.getType() == EdgeShape.TYPE); _ASSERT && common.assert(fixtureB.getType() == CircleShape.TYPE); var shapeA = fixtureA.getShape(); var shapeB = fixtureB.getShape(); CollideEdgeCircle(manifold, shapeA, xfA, shapeB, xfB); } function ChainCircleContact(manifold, xfA, fixtureA, indexA, xfB, fixtureB, indexB) { _ASSERT && common.assert(fixtureA.getType() == ChainShape.TYPE); _ASSERT && common.assert(fixtureB.getType() == CircleShape.TYPE); var chain = fixtureA.getShape(); var edge = new EdgeShape(); chain.getChildEdge(edge, indexA); var shapeA = edge; var shapeB = fixtureB.getShape(); CollideEdgeCircle(manifold, shapeA, xfA, shapeB, xfB); } function CollideEdgeCircle(manifold, edgeA, xfA, circleB, xfB) { manifold.pointCount = 0; var Q = Transform.mulT(xfA, Transform.mul(xfB, circleB.m_p)); var A = edgeA.m_vertex1; var B = edgeA.m_vertex2; var e = Vec2.sub(B, A); var u = Vec2.dot(e, Vec2.sub(B, Q)); var v = Vec2.dot(e, Vec2.sub(Q, A)); var radius = edgeA.m_radius + circleB.m_radius; if (v <= 0) { var P = Vec2.clone(A); var d = Vec2.sub(Q, P); var dd = Vec2.dot(d, d); if (dd > radius * radius) { return; } if (edgeA.m_hasVertex0) { var A1 = edgeA.m_vertex0; var B1 = A; var e1 = Vec2.sub(B1, A1); var u1 = Vec2.dot(e1, Vec2.sub(B1, Q)); if (u1 > 0) { return; } } manifold.type = Manifold.e_circles; manifold.localNormal.setZero(); manifold.localPoint.set(P); manifold.pointCount = 1; manifold.points[0].localPoint.set(circleB.m_p); manifold.points[0].id.key = 0; manifold.points[0].id.cf.indexA = 0; manifold.points[0].id.cf.typeA = Manifold.e_vertex; manifold.points[0].id.cf.indexB = 0; manifold.points[0].id.cf.typeB = Manifold.e_vertex; return; } if (u <= 0) { var P = Vec2.clone(B); var d = Vec2.sub(Q, P); var dd = Vec2.dot(d, d); if (dd > radius * radius) { return; } if (edgeA.m_hasVertex3) { var B2 = edgeA.m_vertex3; var A2 = B; var e2 = Vec2.sub(B2, A2); var v2 = Vec2.dot(e2, Vec2.sub(Q, A2)); if (v2 > 0) { return; } } manifold.type = Manifold.e_circles; manifold.localNormal.setZero(); manifold.localPoint.set(P); manifold.pointCount = 1; manifold.points[0].localPoint.set(circleB.m_p); manifold.points[0].id.key = 0; manifold.points[0].id.cf.indexA = 1; manifold.points[0].id.cf.typeA = Manifold.e_vertex; manifold.points[0].id.cf.indexB = 0; manifold.points[0].id.cf.typeB = Manifold.e_vertex; return; } var den = Vec2.dot(e, e); _ASSERT && common.assert(den > 0); var P = Vec2.combine(u / den, A, v / den, B); var d = Vec2.sub(Q, P); var dd = Vec2.dot(d, d); if (dd > radius * radius) { return; } var n = Vec2.neo(-e.y, e.x); if (Vec2.dot(n, Vec2.sub(Q, A)) < 0) { n.set(-n.x, -n.y); } n.normalize(); manifold.type = Manifold.e_faceA; manifold.localNormal = n; manifold.localPoint.set(A); manifold.pointCount = 1; manifold.points[0].localPoint.set(circleB.m_p); manifold.points[0].id.key = 0; manifold.points[0].id.cf.indexA = 0; manifold.points[0].id.cf.typeA = Manifold.e_face; manifold.points[0].id.cf.indexB = 0; manifold.points[0].id.cf.typeB = Manifold.e_vertex; } },{"../Contact":3,"../Manifold":6,"../Settings":7,"../Shape":8,"../common/Math":18,"../common/Rot":20,"../common/Transform":22,"../common/Vec2":23,"../util/common":51,"../util/create":52,"./ChainShape":40,"./CircleShape":41,"./EdgeShape":47}],45:[function(require,module,exports){ var _DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; var _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; var common = require("../util/common"); var create = require("../util/create"); var Math = require("../common/Math"); var Transform = require("../common/Transform"); var Vec2 = require("../common/Vec2"); var Rot = require("../common/Rot"); var Settings = require("../Settings"); var Shape = require("../Shape"); var Contact = require("../Contact"); var Manifold = require("../Manifold"); var EdgeShape = require("./EdgeShape"); var ChainShape = require("./ChainShape"); var PolygonShape = require("./PolygonShape"); Contact.addType(EdgeShape.TYPE, PolygonShape.TYPE, EdgePolygonContact); Contact.addType(ChainShape.TYPE, PolygonShape.TYPE, ChainPolygonContact); function EdgePolygonContact(manifold, xfA, fA, indexA, xfB, fB, indexB) { _ASSERT && common.assert(fA.getType() == EdgeShape.TYPE); _ASSERT && common.assert(fB.getType() == PolygonShape.TYPE); CollideEdgePolygon(manifold, fA.getShape(), xfA, fB.getShape(), xfB); } function ChainPolygonContact(manifold, xfA, fA, indexA, xfB, fB, indexB) { _ASSERT && common.assert(fA.getType() == ChainShape.TYPE); _ASSERT && common.assert(fB.getType() == PolygonShape.TYPE); var chain = fA.getShape(); var edge = new EdgeShape(); chain.getChildEdge(edge, indexA); CollideEdgePolygon(manifold, edge, xfA, fB.getShape(), xfB); } var e_unknown = -1; var e_edgeA = 1; var e_edgeB = 2; var e_isolated = 0; var e_concave = 1; var e_convex = 2; function EPAxis() { this.type; this.index; this.separation; } function TempPolygon() { this.vertices = []; this.normals = []; this.count = 0; } function ReferenceFace() { this.i1, this.i2; this.v1, this.v2; this.normal = Vec2.zero(); this.sideNormal1 = Vec2.zero(); this.sideOffset1; this.sideNormal2 = Vec2.zero(); this.sideOffset2; } var edgeAxis = new EPAxis(); var polygonAxis = new EPAxis(); var polygonBA = new TempPolygon(); var rf = new ReferenceFace(); function CollideEdgePolygon(manifold, edgeA, xfA, polygonB, xfB) { var m_type1, m_type2; var xf = Transform.mulT(xfA, xfB); var centroidB = Transform.mul(xf, polygonB.m_centroid); var v0 = edgeA.m_vertex0; var v1 = edgeA.m_vertex1; var v2 = edgeA.m_vertex2; var v3 = edgeA.m_vertex3; var hasVertex0 = edgeA.m_hasVertex0; var hasVertex3 = edgeA.m_hasVertex3; var edge1 = Vec2.sub(v2, v1); edge1.normalize(); var normal1 = Vec2.neo(edge1.y, -edge1.x); var offset1 = Vec2.dot(normal1, Vec2.sub(centroidB, v1)); var offset0 = 0; var offset2 = 0; var convex1 = false; var convex2 = false; if (hasVertex0) { var edge0 = Vec2.sub(v1, v0); edge0.normalize(); var normal0 = Vec2.neo(edge0.y, -edge0.x); convex1 = Vec2.cross(edge0, edge1) >= 0; offset0 = Vec2.dot(normal0, centroidB) - Vec2.dot(normal0, v0); } if (hasVertex3) { var edge2 = Vec2.sub(v3, v2); edge2.normalize(); var normal2 = Vec2.neo(edge2.y, -edge2.x); convex2 = Vec2.cross(edge1, edge2) > 0; offset2 = Vec2.dot(normal2, centroidB) - Vec2.dot(normal2, v2); } var front; var normal = Vec2.zero(); var lowerLimit = Vec2.zero(); var upperLimit = Vec2.zero(); if (hasVertex0 && hasVertex3) { if (convex1 && convex2) { front = offset0 >= 0 || offset1 >= 0 || offset2 >= 0; if (front) { normal.set(normal1); lowerLimit.set(normal0); upperLimit.set(normal2); } else { normal.setMul(-1, normal1); lowerLimit.setMul(-1, normal1); upperLimit.setMul(-1, normal1); } } else if (convex1) { front = offset0 >= 0 || offset1 >= 0 && offset2 >= 0; if (front) { normal.set(normal1); lowerLimit.set(normal0); upperLimit.set(normal1); } else { normal.setMul(-1, normal1); lowerLimit.setMul(-1, normal2); upperLimit.setMul(-1, normal1); } } else if (convex2) { front = offset2 >= 0 || offset0 >= 0 && offset1 >= 0; if (front) { normal.set(normal1); lowerLimit.set(normal1); upperLimit.set(normal2); } else { normal.setMul(-1, normal1); lowerLimit.setMul(-1, normal1); upperLimit.setMul(-1, normal0); } } else { front = offset0 >= 0 && offset1 >= 0 && offset2 >= 0; if (front) { normal.set(normal1); lowerLimit.set(normal1); upperLimit.set(normal1); } else { normal.setMul(-1, normal1); lowerLimit.setMul(-1, normal2); upperLimit.setMul(-1, normal0); } } } else if (hasVertex0) { if (convex1) { front = offset0 >= 0 || offset1 >= 0; if (front) { normal.set(normal1); lowerLimit.set(normal0); upperLimit.setMul(-1, normal1); } else { normal.setMul(-1, normal1); lowerLimit.set(normal1); upperLimit.setMul(-1, normal1); } } else { front = offset0 >= 0 && offset1 >= 0; if (front) { normal.set(normal1); lowerLimit.set(normal1); upperLimit.setMul(-1, normal1); } else { normal.setMul(-1, normal1); lowerLimit.set(normal1); upperLimit.setMul(-1, normal0); } } } else if (hasVertex3) { if (convex2) { front = offset1 >= 0 || offset2 >= 0; if (front) { normal.set(normal1); lowerLimit.setMul(-1, normal1); upperLimit.set(normal2); } else { normal.setMul(-1, normal1); lowerLimit.setMul(-1, normal1); upperLimit.set(normal1); } } else { front = offset1 >= 0 && offset2 >= 0; if (front) { normal.set(normal1); lowerLimit.setMul(-1, normal1); upperLimit.set(normal1); } else { normal.setMul(-1, normal1); lowerLimit.setMul(-1, normal2); upperLimit.set(normal1); } } } else { front = offset1 >= 0; if (front) { normal.set(normal1); lowerLimit.setMul(-1, normal1); upperLimit.setMul(-1, normal1); } else { normal.setMul(-1, normal1); lowerLimit.set(normal1); upperLimit.set(normal1); } } polygonBA.count = polygonB.m_count; for (var i = 0; i < polygonB.m_count; ++i) { polygonBA.vertices[i] = Transform.mul(xf, polygonB.m_vertices[i]); polygonBA.normals[i] = Rot.mul(xf.q, polygonB.m_normals[i]); } var radius = 2 * Settings.polygonRadius; manifold.pointCount = 0; { edgeAxis.type = e_edgeA; edgeAxis.index = front ? 0 : 1; edgeAxis.separation = Infinity; for (var i = 0; i < polygonBA.count; ++i) { var s = Vec2.dot(normal, Vec2.sub(polygonBA.vertices[i], v1)); if (s < edgeAxis.separation) { edgeAxis.separation = s; } } } if (edgeAxis.type == e_unknown) { return; } if (edgeAxis.separation > radius) { return; } { polygonAxis.type = e_unknown; polygonAxis.index = -1; polygonAxis.separation = -Infinity; var perp = Vec2.neo(-normal.y, normal.x); for (var i = 0; i < polygonBA.count; ++i) { var n = Vec2.neg(polygonBA.normals[i]); var s1 = Vec2.dot(n, Vec2.sub(polygonBA.vertices[i], v1)); var s2 = Vec2.dot(n, Vec2.sub(polygonBA.vertices[i], v2)); var s = Math.min(s1, s2); if (s > radius) { polygonAxis.type = e_edgeB; polygonAxis.index = i; polygonAxis.separation = s; break; } if (Vec2.dot(n, perp) >= 0) { if (Vec2.dot(Vec2.sub(n, upperLimit), normal) < -Settings.angularSlop) { continue; } } else { if (Vec2.dot(Vec2.sub(n, lowerLimit), normal) < -Settings.angularSlop) { continue; } } if (s > polygonAxis.separation) { polygonAxis.type = e_edgeB; polygonAxis.index = i; polygonAxis.separation = s; } } } if (polygonAxis.type != e_unknown && polygonAxis.separation > radius) { return; } var k_relativeTol = .98; var k_absoluteTol = .001; var primaryAxis; if (polygonAxis.type == e_unknown) { primaryAxis = edgeAxis; } else if (polygonAxis.separation > k_relativeTol * edgeAxis.separation + k_absoluteTol) { primaryAxis = polygonAxis; } else { primaryAxis = edgeAxis; } var ie = [ new Manifold.clipVertex(), new Manifold.clipVertex() ]; if (primaryAxis.type == e_edgeA) { manifold.type = Manifold.e_faceA; var bestIndex = 0; var bestValue = Vec2.dot(normal, polygonBA.normals[0]); for (var i = 1; i < polygonBA.count; ++i) { var value = Vec2.dot(normal, polygonBA.normals[i]); if (value < bestValue) { bestValue = value; bestIndex = i; } } var i1 = bestIndex; var i2 = i1 + 1 < polygonBA.count ? i1 + 1 : 0; ie[0].v = polygonBA.vertices[i1]; ie[0].id.cf.indexA = 0; ie[0].id.cf.indexB = i1; ie[0].id.cf.typeA = Manifold.e_face; ie[0].id.cf.typeB = Manifold.e_vertex; ie[1].v = polygonBA.vertices[i2]; ie[1].id.cf.indexA = 0; ie[1].id.cf.indexB = i2; ie[1].id.cf.typeA = Manifold.e_face; ie[1].id.cf.typeB = Manifold.e_vertex; if (front) { rf.i1 = 0; rf.i2 = 1; rf.v1 = v1; rf.v2 = v2; rf.normal.set(normal1); } else { rf.i1 = 1; rf.i2 = 0; rf.v1 = v2; rf.v2 = v1; rf.normal.setMul(-1, normal1); } } else { manifold.type = Manifold.e_faceB; ie[0].v = v1; ie[0].id.cf.indexA = 0; ie[0].id.cf.indexB = primaryAxis.index; ie[0].id.cf.typeA = Manifold.e_vertex; ie[0].id.cf.typeB = Manifold.e_face; ie[1].v = v2; ie[1].id.cf.indexA = 0; ie[1].id.cf.indexB = primaryAxis.index; ie[1].id.cf.typeA = Manifold.e_vertex; ie[1].id.cf.typeB = Manifold.e_face; rf.i1 = primaryAxis.index; rf.i2 = rf.i1 + 1 < polygonBA.count ? rf.i1 + 1 : 0; rf.v1 = polygonBA.vertices[rf.i1]; rf.v2 = polygonBA.vertices[rf.i2]; rf.normal.set(polygonBA.normals[rf.i1]); } rf.sideNormal1.set(rf.normal.y, -rf.normal.x); rf.sideNormal2.setMul(-1, rf.sideNormal1); rf.sideOffset1 = Vec2.dot(rf.sideNormal1, rf.v1); rf.sideOffset2 = Vec2.dot(rf.sideNormal2, rf.v2); var clipPoints1 = [ new Manifold.clipVertex(), new Manifold.clipVertex() ]; var clipPoints2 = [ new Manifold.clipVertex(), new Manifold.clipVertex() ]; var np; np = Manifold.clipSegmentToLine(clipPoints1, ie, rf.sideNormal1, rf.sideOffset1, rf.i1); if (np < Settings.maxManifoldPoints) { return; } np = Manifold.clipSegmentToLine(clipPoints2, clipPoints1, rf.sideNormal2, rf.sideOffset2, rf.i2); if (np < Settings.maxManifoldPoints) { return; } if (primaryAxis.type == e_edgeA) { manifold.localNormal = Vec2.clone(rf.normal); manifold.localPoint = Vec2.clone(rf.v1); } else { manifold.localNormal = Vec2.clone(polygonB.m_normals[rf.i1]); manifold.localPoint = Vec2.clone(polygonB.m_vertices[rf.i1]); } var pointCount = 0; for (var i = 0; i < Settings.maxManifoldPoints; ++i) { var separation = Vec2.dot(rf.normal, Vec2.sub(clipPoints2[i].v, rf.v1)); if (separation <= radius) { var cp = manifold.points[pointCount]; if (primaryAxis.type == e_edgeA) { cp.localPoint = Transform.mulT(xf, clipPoints2[i].v); cp.id = clipPoints2[i].id; } else { cp.localPoint = clipPoints2[i].v; cp.id.cf.typeA = clipPoints2[i].id.cf.typeB; cp.id.cf.typeB = clipPoints2[i].id.cf.typeA; cp.id.cf.indexA = clipPoints2[i].id.cf.indexB; cp.id.cf.indexB = clipPoints2[i].id.cf.indexA; } ++pointCount; } } manifold.pointCount = pointCount; } },{"../Contact":3,"../Manifold":6,"../Settings":7,"../Shape":8,"../common/Math":18,"../common/Rot":20,"../common/Transform":22,"../common/Vec2":23,"../util/common":51,"../util/create":52,"./ChainShape":40,"./EdgeShape":47,"./PolygonShape":48}],46:[function(require,module,exports){ var _DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; var _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; var common = require("../util/common"); var Math = require("../common/Math"); var Transform = require("../common/Transform"); var Rot = require("../common/Rot"); var Vec2 = require("../common/Vec2"); var AABB = require("../collision/AABB"); var Settings = require("../Settings"); var Manifold = require("../Manifold"); var Contact = require("../Contact"); var Shape = require("../Shape"); var PolygonShape = require("./PolygonShape"); module.exports = CollidePolygons; Contact.addType(PolygonShape.TYPE, PolygonShape.TYPE, PolygonContact); function PolygonContact(manifold, xfA, fixtureA, indexA, xfB, fixtureB, indexB) { _ASSERT && common.assert(fixtureA.getType() == PolygonShape.TYPE); _ASSERT && common.assert(fixtureB.getType() == PolygonShape.TYPE); CollidePolygons(manifold, fixtureA.getShape(), xfA, fixtureB.getShape(), xfB); } function FindMaxSeparation(poly1, xf1, poly2, xf2) { var count1 = poly1.m_count; var count2 = poly2.m_count; var n1s = poly1.m_normals; var v1s = poly1.m_vertices; var v2s = poly2.m_vertices; var xf = Transform.mulT(xf2, xf1); var bestIndex = 0; var maxSeparation = -Infinity; for (var i = 0; i < count1; ++i) { var n = Rot.mul(xf.q, n1s[i]); var v1 = Transform.mul(xf, v1s[i]); var si = Infinity; for (var j = 0; j < count2; ++j) { var sij = Vec2.dot(n, v2s[j]) - Vec2.dot(n, v1); if (sij < si) { si = sij; } } if (si > maxSeparation) { maxSeparation = si; bestIndex = i; } } FindMaxSeparation._maxSeparation = maxSeparation; FindMaxSeparation._bestIndex = bestIndex; } function FindIncidentEdge(c, poly1, xf1, edge1, poly2, xf2) { var normals1 = poly1.m_normals; var count2 = poly2.m_count; var vertices2 = poly2.m_vertices; var normals2 = poly2.m_normals; _ASSERT && common.assert(0 <= edge1 && edge1 < poly1.m_count); var normal1 = Rot.mulT(xf2.q, Rot.mul(xf1.q, normals1[edge1])); var index = 0; var minDot = Infinity; for (var i = 0; i < count2; ++i) { var dot = Vec2.dot(normal1, normals2[i]); if (dot < minDot) { minDot = dot; index = i; } } var i1 = index; var i2 = i1 + 1 < count2 ? i1 + 1 : 0; c[0].v = Transform.mul(xf2, vertices2[i1]); c[0].id.cf.indexA = edge1; c[0].id.cf.indexB = i1; c[0].id.cf.typeA = Manifold.e_face; c[0].id.cf.typeB = Manifold.e_vertex; c[1].v = Transform.mul(xf2, vertices2[i2]); c[1].id.cf.indexA = edge1; c[1].id.cf.indexB = i2; c[1].id.cf.typeA = Manifold.e_face; c[1].id.cf.typeB = Manifold.e_vertex; } function CollidePolygons(manifold, polyA, xfA, polyB, xfB) { manifold.pointCount = 0; var totalRadius = polyA.m_radius + polyB.m_radius; FindMaxSeparation(polyA, xfA, polyB, xfB); var edgeA = FindMaxSeparation._bestIndex; var separationA = FindMaxSeparation._maxSeparation; if (separationA > totalRadius) return; FindMaxSeparation(polyB, xfB, polyA, xfA); var edgeB = FindMaxSeparation._bestIndex; var separationB = FindMaxSeparation._maxSeparation; if (separationB > totalRadius) return; var poly1; var poly2; var xf1; var xf2; var edge1; var flip; var k_tol = .1 * Settings.linearSlop; if (separationB > separationA + k_tol) { poly1 = polyB; poly2 = polyA; xf1 = xfB; xf2 = xfA; edge1 = edgeB; manifold.type = Manifold.e_faceB; flip = 1; } else { poly1 = polyA; poly2 = polyB; xf1 = xfA; xf2 = xfB; edge1 = edgeA; manifold.type = Manifold.e_faceA; flip = 0; } var incidentEdge = [ new Manifold.clipVertex(), new Manifold.clipVertex() ]; FindIncidentEdge(incidentEdge, poly1, xf1, edge1, poly2, xf2); var count1 = poly1.m_count; var vertices1 = poly1.m_vertices; var iv1 = edge1; var iv2 = edge1 + 1 < count1 ? edge1 + 1 : 0; var v11 = vertices1[iv1]; var v12 = vertices1[iv2]; var localTangent = Vec2.sub(v12, v11); localTangent.normalize(); var localNormal = Vec2.cross(localTangent, 1); var planePoint = Vec2.combine(.5, v11, .5, v12); var tangent = Rot.mul(xf1.q, localTangent); var normal = Vec2.cross(tangent, 1); v11 = Transform.mul(xf1, v11); v12 = Transform.mul(xf1, v12); var frontOffset = Vec2.dot(normal, v11); var sideOffset1 = -Vec2.dot(tangent, v11) + totalRadius; var sideOffset2 = Vec2.dot(tangent, v12) + totalRadius; var clipPoints1 = [ new Manifold.clipVertex(), new Manifold.clipVertex() ]; var clipPoints2 = [ new Manifold.clipVertex(), new Manifold.clipVertex() ]; var np; np = Manifold.clipSegmentToLine(clipPoints1, incidentEdge, Vec2.neg(tangent), sideOffset1, iv1); if (np < 2) { return; } np = Manifold.clipSegmentToLine(clipPoints2, clipPoints1, tangent, sideOffset2, iv2); if (np < 2) { return; } manifold.localNormal = localNormal; manifold.localPoint = planePoint; var pointCount = 0; for (var i = 0; i < clipPoints2.length; ++i) { var separation = Vec2.dot(normal, clipPoints2[i].v) - frontOffset; if (separation <= totalRadius) { var cp = manifold.points[pointCount]; cp.localPoint.set(Transform.mulT(xf2, clipPoints2[i].v)); cp.id = clipPoints2[i].id; if (flip) { var cf = cp.id.cf; var indexA = cf.indexA; var indexB = cf.indexB; var typeA = cf.typeA; var typeB = cf.typeB; cf.indexA = indexB; cf.indexB = indexA; cf.typeA = typeB; cf.typeB = typeA; } ++pointCount; } } manifold.pointCount = pointCount; } },{"../Contact":3,"../Manifold":6,"../Settings":7,"../Shape":8,"../collision/AABB":11,"../common/Math":18,"../common/Rot":20,"../common/Transform":22,"../common/Vec2":23,"../util/common":51,"./PolygonShape":48}],47:[function(require,module,exports){ var _DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; var _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = EdgeShape; var create = require("../util/create"); var options = require("../util/options"); var Settings = require("../Settings"); var Shape = require("../Shape"); var Math = require("../common/Math"); var Transform = require("../common/Transform"); var Rot = require("../common/Rot"); var Vec2 = require("../common/Vec2"); var AABB = require("../collision/AABB"); EdgeShape._super = Shape; EdgeShape.prototype = create(EdgeShape._super.prototype); EdgeShape.TYPE = "edge"; function EdgeShape(v1, v2) { if (!(this instanceof EdgeShape)) { return new EdgeShape(v1, v2); } EdgeShape._super.call(this); this.m_type = EdgeShape.TYPE; this.m_radius = Settings.polygonRadius; this.m_vertex1 = v1 ? Vec2.clone(v1) : Vec2.zero(); this.m_vertex2 = v2 ? Vec2.clone(v2) : Vec2.zero(); this.m_vertex0 = Vec2.zero(); this.m_vertex3 = Vec2.zero(); this.m_hasVertex0 = false; this.m_hasVertex3 = false; } EdgeShape.prototype.setNext = function(v3) { if (v3) { this.m_vertex3.set(v3); this.m_hasVertex3 = true; } else { this.m_vertex3.setZero(); this.m_hasVertex3 = false; } return this; }; EdgeShape.prototype.setPrev = function(v0) { if (v0) { this.m_vertex0.set(v0); this.m_hasVertex0 = true; } else { this.m_vertex0.setZero(); this.m_hasVertex0 = false; } return this; }; EdgeShape.prototype._set = function(v1, v2) { this.m_vertex1.set(v1); this.m_vertex2.set(v2); this.m_hasVertex0 = false; this.m_hasVertex3 = false; return this; }; EdgeShape.prototype._clone = function() { var clone = new EdgeShape(); clone.m_type = this.m_type; clone.m_radius = this.m_radius; clone.m_vertex1.set(this.m_vertex1); clone.m_vertex2.set(this.m_vertex2); clone.m_vertex0.set(this.m_vertex0); clone.m_vertex3.set(this.m_vertex3); clone.m_hasVertex0 = this.m_hasVertex0; clone.m_hasVertex3 = this.m_hasVertex3; return clone; }; EdgeShape.prototype.getChildCount = function() { return 1; }; EdgeShape.prototype.testPoint = function(xf, p) { return false; }; EdgeShape.prototype.rayCast = function(output, input, xf, childIndex) { var p1 = Rot.mulT(xf.q, Vec2.sub(input.p1, xf.p)); var p2 = Rot.mulT(xf.q, Vec2.sub(input.p2, xf.p)); var d = Vec2.sub(p2, p1); var v1 = this.m_vertex1; var v2 = this.m_vertex2; var e = Vec2.sub(v2, v1); var normal = Vec2.neo(e.y, -e.x); normal.normalize(); var numerator = Vec2.dot(normal, Vec2.sub(v1, p1)); var denominator = Vec2.dot(normal, d); if (denominator == 0) { return false; } var t = numerator / denominator; if (t < 0 || input.maxFraction < t) { return false; } var q = Vec2.add(p1, Vec2.mul(t, d)); var r = Vec2.sub(v2, v1); var rr = Vec2.dot(r, r); if (rr == 0) { return false; } var s = Vec2.dot(Vec2.sub(q, v1), r) / rr; if (s < 0 || 1 < s) { return false; } output.fraction = t; if (numerator > 0) { output.normal = Rot.mul(xf.q, normal).neg(); } else { output.normal = Rot.mul(xf.q, normal); } return true; }; EdgeShape.prototype.computeAABB = function(aabb, xf, childIndex) { var v1 = Transform.mul(xf, this.m_vertex1); var v2 = Transform.mul(xf, this.m_vertex2); aabb.combine(v1, v2); aabb.extend(this.m_radius); }; EdgeShape.prototype.computeMass = function(massData, density) { massData.mass = 0; massData.center.setCombine(.5, this.m_vertex1, .5, this.m_vertex2); massData.I = 0; }; EdgeShape.prototype.computeDistanceProxy = function(proxy) { proxy.m_vertices.push(this.m_vertex1); proxy.m_vertices.push(this.m_vertex2); proxy.m_count = 2; proxy.m_radius = this.m_radius; }; },{"../Settings":7,"../Shape":8,"../collision/AABB":11,"../common/Math":18,"../common/Rot":20,"../common/Transform":22,"../common/Vec2":23,"../util/create":52,"../util/options":53}],48:[function(require,module,exports){ var _DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; var _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = PolygonShape; var common = require("../util/common"); var create = require("../util/create"); var options = require("../util/options"); var Math = require("../common/Math"); var Transform = require("../common/Transform"); var Rot = require("../common/Rot"); var Vec2 = require("../common/Vec2"); var AABB = require("../collision/AABB"); var Settings = require("../Settings"); var Shape = require("../Shape"); PolygonShape._super = Shape; PolygonShape.prototype = create(PolygonShape._super.prototype); PolygonShape.TYPE = "polygon"; function PolygonShape(vertices) { if (!(this instanceof PolygonShape)) { return new PolygonShape(vertices); } PolygonShape._super.call(this); this.m_type = PolygonShape.TYPE; this.m_radius = Settings.polygonRadius; this.m_centroid = Vec2.zero(); this.m_vertices = []; this.m_normals = []; this.m_count = 0; if (vertices && vertices.length) { this._set(vertices); } } PolygonShape.prototype.getVertex = function(index) { _ASSERT && common.assert(0 <= index && index < this.m_count); return this.m_vertices[index]; }; PolygonShape.prototype._clone = function() { var clone = new PolygonShape(); clone.m_type = this.m_type; clone.m_radius = this.m_radius; clone.m_count = this.m_count; clone.m_centroid.set(this.m_centroid); for (var i = 0; i < this.m_count; i++) { clone.m_vertices.push(this.m_vertices[i].clone()); } for (var i = 0; i < this.m_normals.length; i++) { clone.m_normals.push(this.m_normals[i].clone()); } return clone; }; PolygonShape.prototype.getChildCount = function() { return 1; }; function ComputeCentroid(vs, count) { _ASSERT && common.assert(count >= 3); var c = Vec2.zero(); var area = 0; var pRef = Vec2.zero(); if (false) { for (var i = 0; i < count; ++i) { pRef.add(vs[i]); } pRef.mul(1 / count); } var inv3 = 1 / 3; for (var i = 0; i < count; ++i) { var p1 = pRef; var p2 = vs[i]; var p3 = i + 1 < count ? vs[i + 1] : vs[0]; var e1 = Vec2.sub(p2, p1); var e2 = Vec2.sub(p3, p1); var D = Vec2.cross(e1, e2); var triangleArea = .5 * D; area += triangleArea; c.addMul(triangleArea * inv3, p1); c.addMul(triangleArea * inv3, p2); c.addMul(triangleArea * inv3, p3); } _ASSERT && common.assert(area > Math.EPSILON); c.mul(1 / area); return c; } PolygonShape.prototype._set = function(vertices) { _ASSERT && common.assert(3 <= vertices.length && vertices.length <= Settings.maxPolygonVertices); if (vertices.length < 3) { this._setAsBox(1, 1); return; } var n = Math.min(vertices.length, Settings.maxPolygonVertices); var ps = []; var tempCount = 0; for (var i = 0; i < n; ++i) { var v = vertices[i]; var unique = true; for (var j = 0; j < tempCount; ++j) { if (Vec2.distanceSquared(v, ps[j]) < .25 * Settings.linearSlopSquared) { unique = false; break; } } if (unique) { ps[tempCount++] = v; } } n = tempCount; if (n < 3) { _ASSERT && common.assert(false); this._setAsBox(1, 1); return; } var i0 = 0; var x0 = ps[0].x; for (var i = 1; i < n; ++i) { var x = ps[i].x; if (x > x0 || x == x0 && ps[i].y < ps[i0].y) { i0 = i; x0 = x; } } var hull = []; var m = 0; var ih = i0; for (;;) { hull[m] = ih; var ie = 0; for (var j = 1; j < n; ++j) { if (ie == ih) { ie = j; continue; } var r = Vec2.sub(ps[ie], ps[hull[m]]); var v = Vec2.sub(ps[j], ps[hull[m]]); var c = Vec2.cross(r, v); if (c < 0) { ie = j; } if (c == 0 && v.lengthSquared() > r.lengthSquared()) { ie = j; } } ++m; ih = ie; if (ie == i0) { break; } } if (m < 3) { _ASSERT && common.assert(false); this._setAsBox(1, 1); return; } this.m_count = m; for (var i = 0; i < m; ++i) { this.m_vertices[i] = ps[hull[i]]; } for (var i = 0; i < m; ++i) { var i1 = i; var i2 = i + 1 < m ? i + 1 : 0; var edge = Vec2.sub(this.m_vertices[i2], this.m_vertices[i1]); _ASSERT && common.assert(edge.lengthSquared() > Math.EPSILON * Math.EPSILON); this.m_normals[i] = Vec2.cross(edge, 1); this.m_normals[i].normalize(); } this.m_centroid = ComputeCentroid(this.m_vertices, m); }; PolygonShape.prototype._setAsBox = function(hx, hy, center, angle) { this.m_vertices[0] = Vec2.neo(-hx, -hy); this.m_vertices[1] = Vec2.neo(hx, -hy); this.m_vertices[2] = Vec2.neo(hx, hy); this.m_vertices[3] = Vec2.neo(-hx, hy); this.m_normals[0] = Vec2.neo(0, -1); this.m_normals[1] = Vec2.neo(1, 0); this.m_normals[2] = Vec2.neo(0, 1); this.m_normals[3] = Vec2.neo(-1, 0); this.m_count = 4; if (Vec2.isValid(center)) { angle = angle || 0; this.m_centroid.set(center); var xf = Transform.identity(); xf.p.set(center); xf.q.set(angle); for (var i = 0; i < this.m_count; ++i) { this.m_vertices[i] = Transform.mul(xf, this.m_vertices[i]); this.m_normals[i] = Rot.mul(xf.q, this.m_normals[i]); } } }; PolygonShape.prototype.testPoint = function(xf, p) { var pLocal = Rot.mulT(xf.q, Vec2.sub(p, xf.p)); for (var i = 0; i < this.m_count; ++i) { var dot = Vec2.dot(this.m_normals[i], Vec2.sub(pLocal, this.m_vertices[i])); if (dot > 0) { return false; } } return true; }; PolygonShape.prototype.rayCast = function(output, input, xf, childIndex) { var p1 = Rot.mulT(xf.q, Vec2.sub(input.p1, xf.p)); var p2 = Rot.mulT(xf.q, Vec2.sub(input.p2, xf.p)); var d = Vec2.sub(p2, p1); var lower = 0; var upper = input.maxFraction; var index = -1; for (var i = 0; i < this.m_count; ++i) { var numerator = Vec2.dot(this.m_normals[i], Vec2.sub(this.m_vertices[i], p1)); var denominator = Vec2.dot(this.m_normals[i], d); if (denominator == 0) { if (numerator < 0) { return false; } } else { if (denominator < 0 && numerator < lower * denominator) { lower = numerator / denominator; index = i; } else if (denominator > 0 && numerator < upper * denominator) { upper = numerator / denominator; } } if (upper < lower) { return false; } } _ASSERT && common.assert(0 <= lower && lower <= input.maxFraction); if (index >= 0) { output.fraction = lower; output.normal = Rot.mul(xf.q, this.m_normals[index]); return true; } return false; }; PolygonShape.prototype.computeAABB = function(aabb, xf, childIndex) { var minX = Infinity, minY = Infinity; var maxX = -Infinity, maxY = -Infinity; for (var i = 0; i < this.m_count; ++i) { var v = Transform.mul(xf, this.m_vertices[i]); minX = Math.min(minX, v.x); maxX = Math.max(maxX, v.x); minY = Math.min(minY, v.y); maxY = Math.max(maxY, v.y); } aabb.lowerBound.set(minX, minY); aabb.upperBound.set(maxX, maxY); aabb.extend(this.m_radius); }; PolygonShape.prototype.computeMass = function(massData, density) { _ASSERT && common.assert(this.m_count >= 3); var center = Vec2.zero(); var area = 0; var I = 0; var s = Vec2.zero(); for (var i = 0; i < this.m_count; ++i) { s.add(this.m_vertices[i]); } s.mul(1 / this.m_count); var k_inv3 = 1 / 3; for (var i = 0; i < this.m_count; ++i) { var e1 = Vec2.sub(this.m_vertices[i], s); var e2 = i + 1 < this.m_count ? Vec2.sub(this.m_vertices[i + 1], s) : Vec2.sub(this.m_vertices[0], s); var D = Vec2.cross(e1, e2); var triangleArea = .5 * D; area += triangleArea; center.addCombine(triangleArea * k_inv3, e1, triangleArea * k_inv3, e2); var ex1 = e1.x; var ey1 = e1.y; var ex2 = e2.x; var ey2 = e2.y; var intx2 = ex1 * ex1 + ex2 * ex1 + ex2 * ex2; var inty2 = ey1 * ey1 + ey2 * ey1 + ey2 * ey2; I += .25 * k_inv3 * D * (intx2 + inty2); } massData.mass = density * area; _ASSERT && common.assert(area > Math.EPSILON); center.mul(1 / area); massData.center.setCombine(1, center, 1, s); massData.I = density * I; massData.I += massData.mass * (Vec2.dot(massData.center, massData.center) - Vec2.dot(center, center)); }; PolygonShape.prototype.validate = function() { for (var i = 0; i < this.m_count; ++i) { var i1 = i; var i2 = i < this.m_count - 1 ? i1 + 1 : 0; var p = this.m_vertices[i1]; var e = Vec2.sub(this.m_vertices[i2], p); for (var j = 0; j < this.m_count; ++j) { if (j == i1 || j == i2) { continue; } var v = Vec2.sub(this.m_vertices[j], p); var c = Vec2.cross(e, v); if (c < 0) { return false; } } } return true; }; PolygonShape.prototype.computeDistanceProxy = function(proxy) { proxy.m_vertices = this.m_vertices; proxy.m_count = this.m_count; proxy.m_radius = this.m_radius; }; },{"../Settings":7,"../Shape":8,"../collision/AABB":11,"../common/Math":18,"../common/Rot":20,"../common/Transform":22,"../common/Vec2":23,"../util/common":51,"../util/create":52,"../util/options":53}],49:[function(require,module,exports){ var _DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; var _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = Pool; function Pool(opts) { var _list = []; var _max = opts.max || Infinity; var _createFn = opts.create; var _outFn = opts.allocate; var _inFn = opts.release; var _discardFn = opts.discard; var _createCount = 0; var _outCount = 0; var _inCount = 0; var _discardCount = 0; this.max = function(n) { if (typeof n === "number") { _max = n; return this; } return _max; }; this.size = function() { return _list.length; }; this.allocate = function() { var item; if (_list.length > 0) { item = _list.shift(); } else { _createCount++; if (typeof _createFn === "function") { item = _createFn(); } else { item = {}; } } _outCount++; if (typeof _outFn === "function") { _outFn(item); } return item; }; this.release = function(item) { if (_list.length < _max) { _inCount++; if (typeof _inFn === "function") { _inFn(item); } _list.push(item); } else { _discardCount++; if (typeof _discardFn === "function") { item = _discardFn(item); } } }; this.toString = function() { return " +" + _createCount + " >" + _outCount + " <" + _inCount + " -" + _discardCount + " =" + _list.length + "/" + _max; }; } },{}],50:[function(require,module,exports){ var _DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; var _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports.now = function() { return Date.now(); }; module.exports.diff = function(time) { return Date.now() - time; }; },{}],51:[function(require,module,exports){ var _DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; var _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; exports.debug = function() { if (!_DEBUG) return; console.log.apply(console, arguments); }; exports.assert = function(statement, err, log) { if (!_ASSERT) return; if (statement) return; log && console.log(log); throw new Error(err); }; },{}],52:[function(require,module,exports){ if (typeof Object.create == "function") { module.exports = function(proto, props) { return Object.create.call(Object, proto, props); }; } else { module.exports = function(proto, props) { if (props) throw Error("Second argument is not supported!"); if (typeof proto !== "object" || proto === null) throw Error("Invalid prototype!"); noop.prototype = proto; return new noop(); }; function noop() {} } },{}],53:[function(require,module,exports){ var _DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; var _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; var propIsEnumerable = Object.prototype.propertyIsEnumerable; module.exports = function(to, from) { if (to === null || typeof to === "undefined") { to = {}; } for (var key in from) { if (from.hasOwnProperty(key) && typeof to[key] === "undefined") { to[key] = from[key]; } } if (typeof Object.getOwnPropertySymbols === "function") { var symbols = Object.getOwnPropertySymbols(from); for (var i = 0; i < symbols.length; i++) { var symbol = symbols[i]; if (from.propertyIsEnumerable(symbol) && typeof to[key] === "undefined") { to[symbol] = from[symbol]; } } } return to; }; },{}],54:[function(require,module,exports){ function _identity(x) { return x; }; var _cache = {}; var _modes = {}; var _easings = {}; function Easing(token) { if (typeof token === 'function') { return token; } if (typeof token !== 'string') { return _identity; } var fn = _cache[token]; if (fn) { return fn; } var match = /^(\w+)(-(in|out|in-out|out-in))?(\((.*)\))?$/i.exec(token); if (!match || !match.length) { return _identity; } var easing = _easings[match[1]]; var mode = _modes[match[3]]; var params = match[5]; if (easing && easing.fn) { fn = easing.fn; } else if (easing && easing.fc) { fn = easing.fc.apply(easing.fc, params && params.replace(/\s+/, '').split(',')); } else { fn = _identity; } if (mode) { fn = mode.fn(fn); } // TODO: It can be a memory leak with different `params`. _cache[token] = fn; return fn; }; Easing.add = function(data) { // TODO: create a map of all { name-mode : data } var names = (data.name || data.mode).split(/\s+/); for (var i = 0; i < names.length; i++) { var name = names[i]; if (name) { (data.name ? _easings : _modes)[name] = data; } } }; Easing.add({ mode : 'in', fn : function(f) { return f; } }); Easing.add({ mode : 'out', fn : function(f) { return function(t) { return 1 - f(1 - t); }; } }); Easing.add({ mode : 'in-out', fn : function(f) { return function(t) { return (t < 0.5) ? (f(2 * t) / 2) : (1 - f(2 * (1 - t)) / 2); }; } }); Easing.add({ mode : 'out-in', fn : function(f) { return function(t) { return (t < 0.5) ? (1 - f(2 * (1 - t)) / 2) : (f(2 * t) / 2); }; } }); Easing.add({ name : 'linear', fn : function(t) { return t; } }); Easing.add({ name : 'quad', fn : function(t) { return t * t; } }); Easing.add({ name : 'cubic', fn : function(t) { return t * t * t; } }); Easing.add({ name : 'quart', fn : function(t) { return t * t * t * t; } }); Easing.add({ name : 'quint', fn : function(t) { return t * t * t * t * t; } }); Easing.add({ name : 'sin sine', fn : function(t) { return 1 - Math.cos(t * Math.PI / 2); } }); Easing.add({ name : 'exp expo', fn : function(t) { return t == 0 ? 0 : Math.pow(2, 10 * (t - 1)); } }); Easing.add({ name : 'circle circ', fn : function(t) { return 1 - Math.sqrt(1 - t * t); } }); Easing.add({ name : 'bounce', fn : function(t) { return t < 1 / 2.75 ? 7.5625 * t * t : t < 2 / 2.75 ? 7.5625 * (t -= 1.5 / 2.75) * t + .75 : t < 2.5 / 2.75 ? 7.5625 * (t -= 2.25 / 2.75) * t + .9375 : 7.5625 * (t -= 2.625 / 2.75) * t + .984375; } }); Easing.add({ name : 'poly', fc : function(e) { return function(t) { return Math.pow(t, e); }; } }); Easing.add({ name : 'elastic', fc : function(a, p) { p = p || 0.45; a = a || 1; var s = p / (2 * Math.PI) * Math.asin(1 / a); return function(t) { return 1 + a * Math.pow(2, -10 * t) * Math.sin((t - s) * (2 * Math.PI) / p); }; } }); Easing.add({ name : 'back', fc : function(s) { s = typeof s !== 'undefined' ? s : 1.70158; return function(t) { return t * t * ((s + 1) * t - s); }; } }); module.exports = Easing; },{}],55:[function(require,module,exports){ if (typeof DEBUG === 'undefined') DEBUG = true; require('../core')._load(function(stage, elem) { Mouse.subscribe(stage, elem); }); // TODO: capture mouse Mouse.CLICK = 'click'; Mouse.START = 'touchstart mousedown'; Mouse.MOVE = 'touchmove mousemove'; Mouse.END = 'touchend mouseup'; Mouse.CANCEL = 'touchcancel mousecancel'; Mouse.subscribe = function(stage, elem) { if (stage.mouse) { return; } stage.mouse = new Mouse(stage, elem); // `click` events are synthesized from start/end events on same nodes // `mousecancel` events are synthesized on blur or mouseup outside element elem.addEventListener('touchstart', handleStart); elem.addEventListener('touchend', handleEnd); elem.addEventListener('touchmove', handleMove); elem.addEventListener('touchcancel', handleCancel); elem.addEventListener('mousedown', handleStart); elem.addEventListener('mouseup', handleEnd); elem.addEventListener('mousemove', handleMove); document.addEventListener('mouseup', handleCancel); window.addEventListener("blur", handleCancel); var clicklist = [], cancellist = []; function handleStart(event) { event.preventDefault(); stage.mouse.locate(event); // DEBUG && console.log('Mouse Start: ' + event.type + ' ' + mouse); stage.mouse.publish(event.type, event); stage.mouse.lookup('click', clicklist); stage.mouse.lookup('mousecancel', cancellist); } function handleMove(event) { event.preventDefault(); stage.mouse.locate(event); stage.mouse.publish(event.type, event); } function handleEnd(event) { event.preventDefault(); // up/end location is not available, last one is used instead // DEBUG && console.log('Mouse End: ' + event.type + ' ' + mouse); stage.mouse.publish(event.type, event); if (clicklist.length) { // DEBUG && console.log('Mouse Click: ' + clicklist.length); stage.mouse.publish('click', event, clicklist); } cancellist.length = 0; } function handleCancel(event) { if (cancellist.length) { // DEBUG && console.log('Mouse Cancel: ' + event.type); stage.mouse.publish('mousecancel', event, cancellist); } clicklist.length = 0; } }; function Mouse(stage, elem) { if (!(this instanceof Mouse)) { // old-style mouse subscription return; } var ratio = stage.viewport().ratio || 1; stage.on('viewport', function(size) { ratio = size.ratio || ratio; }); this.x = 0; this.y = 0; this.toString = function() { return (this.x | 0) + 'x' + (this.y | 0); }; this.locate = function(event) { locateElevent(elem, event, this); this.x *= ratio; this.y *= ratio; }; this.lookup = function(type, collect) { this.type = type; this.root = stage; this.event = null; collect.length = 0; this.collect = collect; this.root.visit(this.visitor, this); }; this.publish = function(type, event, targets) { this.type = type; this.root = stage; this.event = event; this.collect = false; this.timeStamp = Date.now(); if (type !== 'mousemove' && type !== 'touchmove') { DEBUG && console.log(this.type + ' ' + this); } if (targets) { while (targets.length) if (this.visitor.end(targets.shift(), this)) break; targets.length = 0; } else { this.root.visit(this.visitor, this); } }; this.visitor = { reverse : true, visible : true, start : function(node, mouse) { return !node._flag(mouse.type); }, end : function(node, mouse) { // mouse: event/collect, type, root rel.raw = mouse.event; rel.type = mouse.type; rel.timeStamp = mouse.timeStamp; rel.abs.x = mouse.x; rel.abs.y = mouse.y; var listeners = node.listeners(mouse.type); if (!listeners) { return; } node.matrix().inverse().map(mouse, rel); if (!(node === mouse.root || node.hitTest(rel))) { return; } if (mouse.collect) { mouse.collect.push(node); } if (mouse.event) { var cancel = false; for (var l = 0; l < listeners.length; l++) { cancel = listeners[l].call(node, rel) ? true : cancel; } return cancel; } } }; }; // TODO: define per mouse object with get-only x and y var rel = {}, abs = {}; defineValue(rel, 'clone', function(obj) { obj = obj || {}, obj.x = this.x, obj.y = this.y; return obj; }); defineValue(rel, 'toString', function() { return (this.x | 0) + 'x' + (this.y | 0) + ' (' + this.abs + ')'; }); defineValue(rel, 'abs', abs); defineValue(abs, 'clone', function(obj) { obj = obj || {}, obj.x = this.x, obj.y = this.y; return obj; }); defineValue(abs, 'toString', function() { return (this.x | 0) + 'x' + (this.y | 0); }); function defineValue(obj, name, value) { Object.defineProperty(obj, name, { value : value }); } function locateElevent(el, ev, loc) { // pageX/Y if available? if (ev.touches && ev.touches.length) { loc.x = ev.touches[0].clientX; loc.y = ev.touches[0].clientY; } else { loc.x = ev.clientX; loc.y = ev.clientY; } var rect = el.getBoundingClientRect(); loc.x -= rect.left; loc.y -= rect.top; loc.x -= el.clientLeft | 0; loc.y -= el.clientTop | 0; return loc; }; module.exports = Mouse; },{"../core":60}],56:[function(require,module,exports){ var Easing = require('./easing'); var Class = require('../core'); var Pin = require('../pin'); Class.prototype.tween = function(duration, delay, append) { if (typeof duration !== 'number') { append = duration, delay = 0, duration = 0; } else if (typeof delay !== 'number') { append = delay, delay = 0; } if (!this._tweens) { this._tweens = []; var ticktime = 0; this.tick(function(elapsed, now, last) { if (!this._tweens.length) { return; } // ignore old elapsed var ignore = ticktime != last; ticktime = now; if (ignore) { return true; } var head = this._tweens[0]; var next = head.tick(this, elapsed, now, last); if (next && head === this._tweens[0]) { this._tweens.shift(); } if (typeof next === 'function') { try { next.call(this); } catch (e) { console.log(e); } } if (typeof next === 'object') { this._tweens.unshift(next); } return true; }, true); } this.touch(); if (!append) { this._tweens.length = 0; } var tween = new Tween(this, duration, delay); this._tweens.push(tween); return tween; }; function Tween(owner, duration, delay) { this._end = {}; this._duration = duration || 400; this._delay = delay || 0; this._owner = owner; this._time = 0; }; Tween.prototype.tick = function(node, elapsed, now, last) { this._time += elapsed; if (this._time < this._delay) { return; } var time = this._time - this._delay; if (!this._start) { this._start = {}; for ( var key in this._end) { this._start[key] = this._owner.pin(key); } } var p, over; if (time < this._duration) { p = time / this._duration; over = false; } else { p = 1; over = true; } if (typeof this._easing == 'function') { p = this._easing(p); } var q = 1 - p; for ( var key in this._end) { this._owner.pin(key, this._start[key] * q + this._end[key] * p); } if (over) { return this._next || this._done || true; } }; Tween.prototype.tween = function(duration, delay) { return this._next = new Tween(this._owner, duration, delay); }; Tween.prototype.duration = function(duration) { this._duration = duration; return this; }; Tween.prototype.delay = function(delay) { this._delay = delay; return this; }; Tween.prototype.ease = function(easing) { this._easing = Easing(easing); return this; }; Tween.prototype.done = function(fn) { this._done = fn; return this; }; Tween.prototype.hide = function() { this.done(function() { this.hide(); }); return this; }; Tween.prototype.remove = function() { this.done(function() { this.remove(); }); return this; }; Tween.prototype.pin = function(a, b) { if (typeof a === 'object') { for ( var attr in a) { pinning(this._owner, this._end, attr, a[attr]); } } else if (typeof b !== 'undefined') { pinning(this._owner, this._end, a, b); } return this; }; function pinning(node, map, key, value) { if (typeof node.pin(key) === 'number') { map[key] = value; } else if (typeof node.pin(key + 'X') === 'number' && typeof node.pin(key + 'Y') === 'number') { map[key + 'X'] = value; map[key + 'Y'] = value; } } Pin._add_shortcuts(Tween); /** * @deprecated Use .done(fn) instead. */ Tween.prototype.then = function(fn) { this.done(fn); return this; }; /** * @deprecated NOOP */ Tween.prototype.clear = function(forward) { return this; }; module.exports = Tween; },{"../core":60,"../pin":68,"./easing":54}],57:[function(require,module,exports){ var Class = require('./core'); require('./pin'); require('./loop'); var create = require('./util/create'); var math = require('./util/math'); Class.anim = function(frames, fps) { var anim = new Anim(); anim.frames(frames).gotoFrame(0); fps && anim.fps(fps); return anim; }; Anim._super = Class; Anim.prototype = create(Anim._super.prototype); // TODO: replace with atlas fps or texture time Class.Anim = { FPS : 15 }; function Anim() { Anim._super.call(this); this.label('Anim'); this._textures = []; this._fps = Class.Anim.FPS; this._ft = 1000 / this._fps; this._time = -1; this._repeat = 0; this._index = 0; this._frames = []; var lastTime = 0; this.tick(function(t, now, last) { if (this._time < 0 || this._frames.length <= 1) { return; } // ignore old elapsed var ignore = lastTime != last; lastTime = now; if (ignore) { return true; } this._time += t; if (this._time < this._ft) { return true; } var n = this._time / this._ft | 0; this._time -= n * this._ft; this.moveFrame(n); if (this._repeat > 0 && (this._repeat -= n) <= 0) { this.stop(); this._callback && this._callback(); return false; } return true; }, false); }; Anim.prototype.fps = function(fps) { if (typeof fps === 'undefined') { return this._fps; } this._fps = fps > 0 ? fps : Class.Anim.FPS; this._ft = 1000 / this._fps; return this; }; /** * @deprecated Use frames */ Anim.prototype.setFrames = function(a, b, c) { return this.frames(a, b, c); }; Anim.prototype.frames = function(frames) { this._index = 0; this._frames = Class.texture(frames).array(); this.touch(); return this; }; Anim.prototype.length = function() { return this._frames ? this._frames.length : 0; }; Anim.prototype.gotoFrame = function(frame, resize) { this._index = math.rotate(frame, this._frames.length) | 0; resize = resize || !this._textures[0]; this._textures[0] = this._frames[this._index]; if (resize) { this.pin('width', this._textures[0].width); this.pin('height', this._textures[0].height); } this.touch(); return this; }; Anim.prototype.moveFrame = function(move) { return this.gotoFrame(this._index + move); }; Anim.prototype.repeat = function(repeat, callback) { this._repeat = repeat * this._frames.length - 1; this._callback = callback; this.play(); return this; }; Anim.prototype.play = function(frame) { if (typeof frame !== 'undefined') { this.gotoFrame(frame); this._time = 0; } else if (this._time < 0) { this._time = 0; } this.touch(); return this; }; Anim.prototype.stop = function(frame) { this._time = -1; if (typeof frame !== 'undefined') { this.gotoFrame(frame); } return this; }; },{"./core":60,"./loop":66,"./pin":68,"./util/create":74,"./util/math":78}],58:[function(require,module,exports){ if (typeof DEBUG === 'undefined') DEBUG = true; var Class = require('./core'); var Texture = require('./texture'); var extend = require('./util/extend'); var create = require('./util/create'); var is = require('./util/is'); var string = require('./util/string'); // name : atlas var _atlases_map = {}; // [atlas] var _atlases_arr = []; // TODO: print subquery not found error // TODO: index textures Class.atlas = function(def) { var atlas = is.fn(def.draw) ? def : new Atlas(def); if (def.name) { _atlases_map[def.name] = atlas; } _atlases_arr.push(atlas); deprecated(def, 'imagePath'); deprecated(def, 'imageRatio'); var url = def.imagePath; var ratio = def.imageRatio || 1; if (is.string(def.image)) { url = def.image; } else if (is.hash(def.image)) { url = def.image.src || def.image.url; ratio = def.image.ratio || ratio; } url && Class.preload(function(done) { url = Class.resolve(url); DEBUG && console.log('Loading atlas: ' + url); var imageloader = Class.config('image-loader'); imageloader(url, function(image) { DEBUG && console.log('Image loaded: ' + url); atlas.src(image, ratio); done(); }, function(err) { DEBUG && console.log('Error loading atlas: ' + url, err); done(); }); }); return atlas; }; Atlas._super = Texture; Atlas.prototype = create(Atlas._super.prototype); function Atlas(def) { Atlas._super.call(this); var atlas = this; deprecated(def, 'filter'); deprecated(def, 'cutouts'); deprecated(def, 'sprites'); deprecated(def, 'factory'); var map = def.map || def.filter; var ppu = def.ppu || def.ratio || 1; var trim = def.trim || 0; var textures = def.textures; var factory = def.factory; var cutouts = def.cutouts || def.sprites; function make(def) { if (!def || is.fn(def.draw)) { return def; } def = extend({}, def); if (is.fn(map)) { def = map(def); } if (ppu != 1) { def.x *= ppu, def.y *= ppu; def.width *= ppu, def.height *= ppu; def.top *= ppu, def.bottom *= ppu; def.left *= ppu, def.right *= ppu; } if (trim != 0) { def.x += trim, def.y += trim; def.width -= 2 * trim, def.height -= 2 * trim; def.top -= trim, def.bottom -= trim; def.left -= trim, def.right -= trim; } var texture = atlas.pipe(); texture.top = def.top, texture.bottom = def.bottom; texture.left = def.left, texture.right = def.right; texture.src(def.x, def.y, def.width, def.height); return texture; } function find(query) { if (textures) { if (is.fn(textures)) { return textures(query); } else if (is.hash(textures)) { return textures[query]; } } if (cutouts) { // deprecated var result = null, n = 0; for (var i = 0; i < cutouts.length; i++) { if (string.startsWith(cutouts[i].name, query)) { if (n === 0) { result = cutouts[i]; } else if (n === 1) { result = [ result, cutouts[i] ]; } else { result.push(cutouts[i]); } n++; } } if (n === 0 && is.fn(factory)) { result = function(subquery) { return factory(query + (subquery ? subquery : '')); }; } return result; } } this.select = function(query) { if (!query) { // TODO: if `textures` is texture def, map or fn? return new Selection(this.pipe()); } var found = find(query); if (found) { return new Selection(found, find, make); } }; }; var nfTexture = new Texture(); nfTexture.x = nfTexture.y = nfTexture.width = nfTexture.height = 0; nfTexture.pipe = nfTexture.src = nfTexture.dest = function() { return this; }; nfTexture.draw = function() { }; var nfSelection = new Selection(nfTexture); function Selection(result, find, make) { function link(result, subquery) { if (!result) { return nfTexture; } else if (is.fn(result.draw)) { return result; } else if (is.hash(result) && is.number(result.width) && is.number(result.height) && is.fn(make)) { return make(result); } else if (is.hash(result) && is.defined(subquery)) { return link(result[subquery]); } else if (is.fn(result)) { return link(result(subquery)); } else if (is.array(result)) { return link(result[0]); } else if (is.string(result) && is.fn(find)) { return link(find(result)); } } this.one = function(subquery) { return link(result, subquery); }; this.array = function(arr) { var array = is.array(arr) ? arr : []; if (is.array(result)) { for (var i = 0; i < result.length; i++) { array[i] = link(result[i]); } } else { array[0] = link(result); } return array; }; } Class.texture = function(query) { if (!is.string(query)) { return new Selection(query); } var result = null, atlas, i; if ((i = query.indexOf(':')) > 0 && query.length > i + 1) { atlas = _atlases_map[query.slice(0, i)]; result = atlas && atlas.select(query.slice(i + 1)); } if (!result && (atlas = _atlases_map[query])) { result = atlas.select(); } for (i = 0; !result && i < _atlases_arr.length; i++) { result = _atlases_arr[i].select(query); } if (!result) { console.error('Texture not found: ' + query); result = nfSelection; } return result; }; function deprecated(hash, name, msg) { if (name in hash) console.log(msg ? msg.replace('%name', name) : '\'' + name + '\' field of texture atlas is deprecated.'); }; module.exports = Atlas; },{"./core":60,"./texture":71,"./util/create":74,"./util/extend":76,"./util/is":77,"./util/string":81}],59:[function(require,module,exports){ var Class = require('./core'); var Texture = require('./texture'); Class.canvas = function(type, attributes, callback) { if (typeof type === 'string') { if (typeof attributes === 'object') { } else { if (typeof attributes === 'function') { callback = attributes; } attributes = {}; } } else { if (typeof type === 'function') { callback = type; } attributes = {}; type = '2d'; } var canvas = document.createElement('canvas'); var context = canvas.getContext(type, attributes); var texture = new Texture(canvas); texture.context = function() { return context; }; texture.size = function(width, height, ratio) { ratio = ratio || 1; canvas.width = width * ratio; canvas.height = height * ratio; this.src(canvas, ratio); return this; }; texture.canvas = function(fn) { if (typeof fn === 'function') { fn.call(this, context); } else if (typeof fn === 'undefined' && typeof callback === 'function') { callback.call(this, context); } return this; }; if (typeof callback === 'function') { callback.call(texture, context); } return texture; }; },{"./core":60,"./texture":71}],60:[function(require,module,exports){ if (typeof DEBUG === 'undefined') DEBUG = true; var stats = require('./util/stats'); var extend = require('./util/extend'); var is = require('./util/is'); var _await = require('./util/await'); stats.create = 0; function Class(arg) { if (!(this instanceof Class)) { if (is.fn(arg)) { return Class.app.apply(Class, arguments); } else if (is.object(arg)) { return Class.atlas.apply(Class, arguments); } else { return arg; } } stats.create++; for (var i = 0; i < _init.length; i++) { _init[i].call(this); } } var _init = []; Class._init = function(fn) { _init.push(fn); }; var _load = []; Class._load = function(fn) { _load.push(fn); }; var _config = {}; Class.config = function() { if (arguments.length === 1 && is.string(arguments[0])) { return _config[arguments[0]]; } if (arguments.length === 1 && is.object(arguments[0])) { extend(_config, arguments[0]); } if (arguments.length === 2 && is.string(arguments[0])) { _config[arguments[0], arguments[1]]; } }; var _app_queue = []; var _preload_queue = []; var _stages = []; var _loaded = false; var _paused = false; Class.app = function(app, opts) { if (!_loaded) { _app_queue.push(arguments); return; } DEBUG && console.log('Creating app...'); var loader = Class.config('app-loader'); loader(function(stage, canvas) { DEBUG && console.log('Initing app...'); for (var i = 0; i < _load.length; i++) { _load[i].call(this, stage, canvas); } app(stage, canvas); _stages.push(stage); DEBUG && console.log('Starting app...'); stage.start(); }, opts); }; var loading = _await(); Class.preload = function(load) { if (typeof load === 'string') { var url = Class.resolve(load); if (/\.js($|\?|\#)/.test(url)) { DEBUG && console.log('Loading script: ' + url); load = function(callback) { loadScript(url, callback); }; } } if (typeof load !== 'function') { return; } // if (!_started) { // _preload_queue.push(load); // return; // } load(loading()); }; Class.start = function(config) { DEBUG && console.log('Starting...'); Class.config(config); // DEBUG && console.log('Preloading...'); // _started = true; // while (_preload_queue.length) { // var load = _preload_queue.shift(); // load(loading()); // } loading.then(function() { DEBUG && console.log('Loading apps...'); _loaded = true; while (_app_queue.length) { var args = _app_queue.shift(); Class.app.apply(Class, args); } }); }; Class.pause = function() { if (!_paused) { _paused = true; for (var i = _stages.length - 1; i >= 0; i--) { _stages[i].pause(); } } }; Class.resume = function() { if (_paused) { _paused = false; for (var i = _stages.length - 1; i >= 0; i--) { _stages[i].resume(); } } }; Class.create = function() { return new Class(); }; Class.resolve = (function() { if (typeof window === 'undefined' || typeof document === 'undefined') { return function(url) { return url; }; } var scripts = document.getElementsByTagName('script'); function getScriptSrc() { // HTML5 if (document.currentScript) { return document.currentScript.src; } // IE>=10 var stack; try { var err = new Error(); if (err.stack) { stack = err.stack; } else { throw err; } } catch (err) { stack = err.stack; } if (typeof stack === 'string') { stack = stack.split('\n'); // Uses the last line, where the call started for (var i = stack.length; i--;) { var url = stack[i].match(/(\w+\:\/\/[^/]*?\/.+?)(:\d+)(:\d+)?/); if (url) { return url[1]; } } } // IE<11 if (scripts.length && 'readyState' in scripts[0]) { for (var i = scripts.length; i--;) { if (scripts[i].readyState === 'interactive') { return scripts[i].src; } } } return location.href; } return function(url) { if (/^\.\//.test(url)) { var src = getScriptSrc(); var base = src.substring(0, src.lastIndexOf('/') + 1); url = base + url.substring(2); // } else if (/^\.\.\//.test(url)) { // url = base + url; } return url; }; })(); module.exports = Class; function loadScript(src, callback) { var el = document.createElement('script'); el.addEventListener('load', function() { callback(); }); el.addEventListener('error', function(err) { callback(err || 'Error loading script: ' + src); }); el.src = src; el.id = 'preload-' + Date.now(); document.body.appendChild(el); }; },{"./util/await":73,"./util/extend":76,"./util/is":77,"./util/stats":80}],61:[function(require,module,exports){ require('./util/event')(require('./core').prototype, function(obj, name, on) { obj._flag(name, on); }); },{"./core":60,"./util/event":75}],62:[function(require,module,exports){ var Class = require('./core'); require('./pin'); require('./loop'); var repeat = require('./util/repeat'); var create = require('./util/create'); module.exports = Image; Class.image = function(image) { var img = new Image(); image && img.image(image); return img; }; Image._super = Class; Image.prototype = create(Image._super.prototype); function Image() { Image._super.call(this); this.label('Image'); this._textures = []; this._image = null; }; /** * @deprecated Use image */ Image.prototype.setImage = function(a, b, c) { return this.image(a, b, c); }; Image.prototype.image = function(image) { this._image = Class.texture(image).one(); this.pin('width', this._image ? this._image.width : 0); this.pin('height', this._image ? this._image.height : 0); this._textures[0] = this._image.pipe(); this._textures.length = 1; return this; }; Image.prototype.tile = function(inner) { this._repeat(false, inner); return this; }; Image.prototype.stretch = function(inner) { this._repeat(true, inner); return this; }; Image.prototype._repeat = function(stretch, inner) { var self = this; this.untick(this._repeatTicker); this.tick(this._repeatTicker = function() { if (this._mo_stretch == this._pin._ts_transform) { return; } this._mo_stretch = this._pin._ts_transform; var width = this.pin('width'); var height = this.pin('height'); this._textures.length = repeat(this._image, width, height, stretch, inner, insert); }); function insert(i, sx, sy, sw, sh, dx, dy, dw, dh) { var repeat = self._textures.length > i ? self._textures[i] : self._textures[i] = self._image.pipe(); repeat.src(sx, sy, sw, sh); repeat.dest(dx, dy, dw, dh); } }; },{"./core":60,"./loop":66,"./pin":68,"./util/create":74,"./util/repeat":79}],63:[function(require,module,exports){ module.exports = require('./core'); module.exports.Matrix = require('./matrix'); module.exports.Texture = require('./texture'); require('./atlas'); require('./tree'); require('./event'); require('./pin'); require('./loop'); require('./root'); },{"./atlas":58,"./core":60,"./event":61,"./loop":66,"./matrix":67,"./pin":68,"./root":69,"./texture":71,"./tree":72}],64:[function(require,module,exports){ var Class = require('./core'); require('./pin'); require('./loop'); var create = require('./util/create'); Class.row = function(align) { return Class.create().row(align).label('Row'); }; Class.prototype.row = function(align) { this.sequence('row', align); return this; }; Class.column = function(align) { return Class.create().column(align).label('Row'); }; Class.prototype.column = function(align) { this.sequence('column', align); return this; }; Class.sequence = function(type, align) { return Class.create().sequence(type, align).label('Sequence'); }; Class.prototype.sequence = function(type, align) { this._padding = this._padding || 0; this._spacing = this._spacing || 0; this.untick(this._layoutTiker); this.tick(this._layoutTiker = function() { if (this._mo_seq == this._ts_touch) { return; } this._mo_seq = this._ts_touch; var alignChildren = (this._mo_seqAlign != this._ts_children); this._mo_seqAlign = this._ts_children; var width = 0, height = 0; var child, next = this.first(true); var first = true; while (child = next) { next = child.next(true); child.matrix(true); var w = child.pin('boxWidth'); var h = child.pin('boxHeight'); if (type == 'column') { !first && (height += this._spacing); child.pin('offsetY') != height && child.pin('offsetY', height); width = Math.max(width, w); height = height + h; alignChildren && child.pin('alignX', align); } else if (type == 'row') { !first && (width += this._spacing); child.pin('offsetX') != width && child.pin('offsetX', width); width = width + w; height = Math.max(height, h); alignChildren && child.pin('alignY', align); } first = false; } width += 2 * this._padding; height += 2 * this._padding; this.pin('width') != width && this.pin('width', width); this.pin('height') != height && this.pin('height', height); }); return this; }; Class.box = function() { return Class.create().box().label('Box'); }; Class.prototype.box = function() { this._padding = this._padding || 0; this.untick(this._layoutTiker); this.tick(this._layoutTiker = function() { if (this._mo_box == this._ts_touch) { return; } this._mo_box = this._ts_touch; var width = 0, height = 0; var child, next = this.first(true); while (child = next) { next = child.next(true); child.matrix(true); var w = child.pin('boxWidth'); var h = child.pin('boxHeight'); width = Math.max(width, w); height = Math.max(height, h); } width += 2 * this._padding; height += 2 * this._padding; this.pin('width') != width && this.pin('width', width); this.pin('height') != height && this.pin('height', height); }); return this; }; Class.layer = function() { return Class.create().layer().label('Layer'); }; Class.prototype.layer = function() { this.untick(this._layoutTiker); this.tick(this._layoutTiker = function() { var parent = this.parent(); if (parent) { var width = parent.pin('width'); if (this.pin('width') != width) { this.pin('width', width); } var height = parent.pin('height'); if (this.pin('height') != height) { this.pin('height', height); } } }, true); return this; }; // TODO: move padding to pin Class.prototype.padding = function(pad) { this._padding = pad; return this; }; Class.prototype.spacing = function(space) { this._spacing = space; return this; }; },{"./core":60,"./loop":66,"./pin":68,"./util/create":74}],65:[function(require,module,exports){ /** * Default loader for web. */ if (typeof DEBUG === 'undefined') DEBUG = true; var Class = require('../core'); Class._supported = (function() { var elem = document.createElement('canvas'); return (elem.getContext && elem.getContext('2d')) ? true : false; })(); window.addEventListener('load', function() { DEBUG && console.log('On load.'); if (Class._supported) { Class.start(); } // TODO if not supported }, false); Class.config({ 'app-loader' : AppLoader, 'image-loader' : ImageLoader }); function AppLoader(app, configs) { configs = configs || {}; var canvas = configs.canvas, context = null, full = false; var width = 0, height = 0, ratio = 1; if (typeof canvas === 'string') { canvas = document.getElementById(canvas); } if (!canvas) { canvas = document.getElementById('cutjs') || document.getElementById('stage'); } if (!canvas) { full = true; DEBUG && console.log('Creating Canvas...'); canvas = document.createElement('canvas'); canvas.style.position = 'absolute'; canvas.style.top = '0'; canvas.style.left = '0'; var body = document.body; body.insertBefore(canvas, body.firstChild); } context = canvas.getContext('2d'); var devicePixelRatio = window.devicePixelRatio || 1; var backingStoreRatio = context.webkitBackingStorePixelRatio || context.mozBackingStorePixelRatio || context.msBackingStorePixelRatio || context.oBackingStorePixelRatio || context.backingStorePixelRatio || 1; ratio = devicePixelRatio / backingStoreRatio; var requestAnimationFrame = window.requestAnimationFrame || window.msRequestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || window.oRequestAnimationFrame || function(callback) { return window.setTimeout(callback, 1000 / 60); }; DEBUG && console.log('Creating stage...'); var root = Class.root(requestAnimationFrame, render); function render() { context.setTransform(1, 0, 0, 1, 0, 0); context.clearRect(0, 0, width, height); root.render(context); } root.background = function(color) { canvas.style.backgroundColor = color; return this; }; app(root, canvas); resize(); window.addEventListener('resize', resize, false); window.addEventListener('orientationchange', resize, false); function resize() { if (full) { // screen.availWidth/Height? width = (window.innerWidth > 0 ? window.innerWidth : screen.width); height = (window.innerHeight > 0 ? window.innerHeight : screen.height); canvas.style.width = width + 'px'; canvas.style.height = height + 'px'; } else { width = canvas.clientWidth; height = canvas.clientHeight; } width *= ratio; height *= ratio; if (canvas.width === width && canvas.height === height) { return; } canvas.width = width; canvas.height = height; DEBUG && console.log('Resize: ' + width + ' x ' + height + ' / ' + ratio); root.viewport(width, height, ratio); render(); } } function ImageLoader(src, success, error) { DEBUG && console.log('Loading image: ' + src); var image = new Image(); image.onload = function() { success(image); }; image.onerror = error; image.src = src; } },{"../core":60}],66:[function(require,module,exports){ var Class = require('./core'); require('./pin'); var stats = require('./util/stats'); Class.prototype._textures = null; Class.prototype._alpha = 1; Class.prototype.render = function(context) { if (!this._visible) { return; } stats.node++; var m = this.matrix(); context.setTransform(m.a, m.b, m.c, m.d, m.e, m.f); // move this elsewhere! this._alpha = this._pin._alpha * (this._parent ? this._parent._alpha : 1); var alpha = this._pin._textureAlpha * this._alpha; if (context.globalAlpha != alpha) { context.globalAlpha = alpha; } if (this._textures !== null) { for (var i = 0, n = this._textures.length; i < n; i++) { this._textures[i].draw(context); } } if (context.globalAlpha != this._alpha) { context.globalAlpha = this._alpha; } var child, next = this._first; while (child = next) { next = child._next; child.render(context); } }; Class.prototype._tickBefore = null; Class.prototype._tickAfter = null; Class.prototype.MAX_ELAPSE = Infinity; Class.prototype._tick = function(elapsed, now, last) { if (!this._visible) { return; } if (elapsed > this.MAX_ELAPSE) { elapsed = this.MAX_ELAPSE; } var ticked = false; if (this._tickBefore !== null) { for (var i = 0; i < this._tickBefore.length; i++) { stats.tick++; var tickFn = this._tickBefore[i]; ticked = tickFn.call(this, elapsed, now, last) === true || ticked; } } var child, next = this._first; while (child = next) { next = child._next; if (child._flag('_tick')) { ticked = child._tick(elapsed, now, last) === true ? true : ticked; } } if (this._tickAfter !== null) { for (var i = 0; i < this._tickAfter.length; i++) { stats.tick++; var tickFn = this._tickAfter[i]; ticked = tickFn.call(this, elapsed, now, last) === true || ticked; } } return ticked; }; Class.prototype.tick = function(ticker, before) { if (typeof ticker !== 'function') { return; } if (before) { if (this._tickBefore === null) { this._tickBefore = []; } this._tickBefore.push(ticker); } else { if (this._tickAfter === null) { this._tickAfter = []; } this._tickAfter.push(ticker); } this._flag('_tick', this._tickAfter !== null && this._tickAfter.length > 0 || this._tickBefore !== null && this._tickBefore.length > 0); }; Class.prototype.untick = function(ticker) { if (typeof ticker !== 'function') { return; } var i; if (this._tickBefore !== null && (i = this._tickBefore.indexOf(ticker)) >= 0) { this._tickBefore.splice(i, 1); } if (this._tickAfter !== null && (i = this._tickAfter.indexOf(ticker)) >= 0) { this._tickAfter.splice(i, 1); } }; Class.prototype.timeout = function(fn, time) { this.setTimeout(fn, time); }; Class.prototype.setTimeout = function(fn, time) { function timer(t) { if ((time -= t) < 0) { this.untick(timer); fn.call(this); } else { return true; } } this.tick(timer); return timer; }; Class.prototype.clearTimeout = function(timer) { this.untick(timer); }; },{"./core":60,"./pin":68,"./util/stats":80}],67:[function(require,module,exports){ function Matrix(a, b, c, d, e, f) { this.reset(a, b, c, d, e, f); }; Matrix.prototype.toString = function() { return '[' + this.a + ', ' + this.b + ', ' + this.c + ', ' + this.d + ', ' + this.e + ', ' + this.f + ']'; }; Matrix.prototype.clone = function() { return new Matrix(this.a, this.b, this.c, this.d, this.e, this.f); }; Matrix.prototype.reset = function(a, b, c, d, e, f) { this._dirty = true; if (typeof a === 'object') { this.a = a.a, this.d = a.d; this.b = a.b, this.c = a.c; this.e = a.e, this.f = a.f; } else { this.a = a || 1, this.d = d || 1; this.b = b || 0, this.c = c || 0; this.e = e || 0, this.f = f || 0; } return this; }; Matrix.prototype.identity = function() { this._dirty = true; this.a = 1; this.b = 0; this.c = 0; this.d = 1; this.e = 0; this.f = 0; return this; }; Matrix.prototype.rotate = function(angle) { if (!angle) { return this; } this._dirty = true; var u = angle ? Math.cos(angle) : 1; // android bug may give bad 0 values var v = angle ? Math.sin(angle) : 0; var a = u * this.a - v * this.b; var b = u * this.b + v * this.a; var c = u * this.c - v * this.d; var d = u * this.d + v * this.c; var e = u * this.e - v * this.f; var f = u * this.f + v * this.e; this.a = a; this.b = b; this.c = c; this.d = d; this.e = e; this.f = f; return this; }; Matrix.prototype.translate = function(x, y) { if (!x && !y) { return this; } this._dirty = true; this.e += x; this.f += y; return this; }; Matrix.prototype.scale = function(x, y) { if (!(x - 1) && !(y - 1)) { return this; } this._dirty = true; this.a *= x; this.b *= y; this.c *= x; this.d *= y; this.e *= x; this.f *= y; return this; }; Matrix.prototype.skew = function(x, y) { if (!x && !y) { return this; } this._dirty = true; var a = this.a + this.b * x; var b = this.b + this.a * y; var c = this.c + this.d * x; var d = this.d + this.c * y; var e = this.e + this.f * x; var f = this.f + this.e * y; this.a = a; this.b = b; this.c = c; this.d = d; this.e = e; this.f = f; return this; }; Matrix.prototype.concat = function(m) { this._dirty = true; var n = this; var a = n.a * m.a + n.b * m.c; var b = n.b * m.d + n.a * m.b; var c = n.c * m.a + n.d * m.c; var d = n.d * m.d + n.c * m.b; var e = n.e * m.a + m.e + n.f * m.c; var f = n.f * m.d + m.f + n.e * m.b; this.a = a; this.b = b; this.c = c; this.d = d; this.e = e; this.f = f; return this; }; Matrix.prototype.inverse = Matrix.prototype.reverse = function() { if (this._dirty) { this._dirty = false; this.inversed = this.inversed || new Matrix(); var z = this.a * this.d - this.b * this.c; this.inversed.a = this.d / z; this.inversed.b = -this.b / z; this.inversed.c = -this.c / z; this.inversed.d = this.a / z; this.inversed.e = (this.c * this.f - this.e * this.d) / z; this.inversed.f = (this.e * this.b - this.a * this.f) / z; } return this.inversed; }; Matrix.prototype.map = function(p, q) { q = q || {}; q.x = this.a * p.x + this.c * p.y + this.e; q.y = this.b * p.x + this.d * p.y + this.f; return q; }; Matrix.prototype.mapX = function(x, y) { if (typeof x === 'object') y = x.y, x = x.x; return this.a * x + this.c * y + this.e; }; Matrix.prototype.mapY = function(x, y) { if (typeof x === 'object') y = x.y, x = x.x; return this.b * x + this.d * y + this.f; }; module.exports = Matrix; },{}],68:[function(require,module,exports){ var Class = require('./core'); var Matrix = require('./matrix'); var iid = 0; Class._init(function() { this._pin = new Pin(this); }); Class.prototype.matrix = function(relative) { if (relative === true) { return this._pin.relativeMatrix(); } return this._pin.absoluteMatrix(); }; Class.prototype.pin = function(a, b) { if (typeof a === 'object') { this._pin.set(a); return this; } else if (typeof a === 'string') { if (typeof b === 'undefined') { return this._pin.get(a); } else { this._pin.set(a, b); return this; } } else if (typeof a === 'undefined') { return this._pin; } }; function Pin(owner) { this._owner = owner; this._parent = null; // relative to parent this._relativeMatrix = new Matrix(); // relative to stage this._absoluteMatrix = new Matrix(); this.reset(); }; Pin.prototype.reset = function() { this._textureAlpha = 1; this._alpha = 1; this._width = 0; this._height = 0; this._scaleX = 1; this._scaleY = 1; this._skewX = 0; this._skewY = 0; this._rotation = 0; // scale/skew/rotate center this._pivoted = false; this._pivotX = null; this._pivotY = null; // self pin point this._handled = false; this._handleX = 0; this._handleY = 0; // parent pin point this._aligned = false; this._alignX = 0; this._alignY = 0; // as seen by parent px this._offsetX = 0; this._offsetY = 0; this._boxX = 0; this._boxY = 0; this._boxWidth = this._width; this._boxHeight = this._height; // TODO: also set for owner this._ts_translate = ++iid; this._ts_transform = ++iid; this._ts_matrix = ++iid; }; Pin.prototype._update = function() { this._parent = this._owner._parent && this._owner._parent._pin; // if handled and transformed then be translated if (this._handled && this._mo_handle != this._ts_transform) { this._mo_handle = this._ts_transform; this._ts_translate = ++iid; } if (this._aligned && this._parent && this._mo_align != this._parent._ts_transform) { this._mo_align = this._parent._ts_transform; this._ts_translate = ++iid; } return this; }; Pin.prototype.toString = function() { return this._owner + ' (' + (this._parent ? this._parent._owner : null) + ')'; }; // TODO: ts fields require refactoring Pin.prototype.absoluteMatrix = function() { this._update(); var ts = Math.max(this._ts_transform, this._ts_translate, this._parent ? this._parent._ts_matrix : 0); if (this._mo_abs == ts) { return this._absoluteMatrix; } this._mo_abs = ts; var abs = this._absoluteMatrix; abs.reset(this.relativeMatrix()); this._parent && abs.concat(this._parent._absoluteMatrix); this._ts_matrix = ++iid; return abs; }; Pin.prototype.relativeMatrix = function() { this._update(); var ts = Math.max(this._ts_transform, this._ts_translate, this._parent ? this._parent._ts_transform : 0); if (this._mo_rel == ts) { return this._relativeMatrix; } this._mo_rel = ts; var rel = this._relativeMatrix; rel.identity(); if (this._pivoted) { rel.translate(-this._pivotX * this._width, -this._pivotY * this._height); } rel.scale(this._scaleX, this._scaleY); rel.skew(this._skewX, this._skewY); rel.rotate(this._rotation); if (this._pivoted) { rel.translate(this._pivotX * this._width, this._pivotY * this._height); } // calculate effective box if (this._pivoted) { // origin this._boxX = 0; this._boxY = 0; this._boxWidth = this._width; this._boxHeight = this._height; } else { // aabb var p, q; if (rel.a > 0 && rel.c > 0 || rel.a < 0 && rel.c < 0) { p = 0, q = rel.a * this._width + rel.c * this._height; } else { p = rel.a * this._width, q = rel.c * this._height; } if (p > q) { this._boxX = q; this._boxWidth = p - q; } else { this._boxX = p; this._boxWidth = q - p; } if (rel.b > 0 && rel.d > 0 || rel.b < 0 && rel.d < 0) { p = 0, q = rel.b * this._width + rel.d * this._height; } else { p = rel.b * this._width, q = rel.d * this._height; } if (p > q) { this._boxY = q; this._boxHeight = p - q; } else { this._boxY = p; this._boxHeight = q - p; } } this._x = this._offsetX; this._y = this._offsetY; this._x -= this._boxX + this._handleX * this._boxWidth; this._y -= this._boxY + this._handleY * this._boxHeight; if (this._aligned && this._parent) { this._parent.relativeMatrix(); this._x += this._alignX * this._parent._width; this._y += this._alignY * this._parent._height; } rel.translate(this._x, this._y); return this._relativeMatrix; }; Pin.prototype.get = function(key) { if (typeof getters[key] === 'function') { return getters[key](this); } }; // TODO: Use defineProperty instead? What about multi-field pinning? Pin.prototype.set = function(a, b) { if (typeof a === 'string') { if (typeof setters[a] === 'function' && typeof b !== 'undefined') { setters[a](this, b); } } else if (typeof a === 'object') { for (b in a) { if (typeof setters[b] === 'function' && typeof a[b] !== 'undefined') { setters[b](this, a[b], a); } } } if (this._owner) { this._owner._ts_pin = ++iid; this._owner.touch(); } return this; }; var getters = { alpha : function(pin) { return pin._alpha; }, textureAlpha : function(pin) { return pin._textureAlpha; }, width : function(pin) { return pin._width; }, height : function(pin) { return pin._height; }, boxWidth : function(pin) { return pin._boxWidth; }, boxHeight : function(pin) { return pin._boxHeight; }, // scale : function(pin) { // }, scaleX : function(pin) { return pin._scaleX; }, scaleY : function(pin) { return pin._scaleY; }, // skew : function(pin) { // }, skewX : function(pin) { return pin._skewX; }, skewY : function(pin) { return pin._skewY; }, rotation : function(pin) { return pin._rotation; }, // pivot : function(pin) { // }, pivotX : function(pin) { return pin._pivotX; }, pivotY : function(pin) { return pin._pivotY; }, // offset : function(pin) { // }, offsetX : function(pin) { return pin._offsetX; }, offsetY : function(pin) { return pin._offsetY; }, // align : function(pin) { // }, alignX : function(pin) { return pin._alignX; }, alignY : function(pin) { return pin._alignY; }, // handle : function(pin) { // }, handleX : function(pin) { return pin._handleX; }, handleY : function(pin) { return pin._handleY; } }; var setters = { alpha : function(pin, value) { pin._alpha = value; }, textureAlpha : function(pin, value) { pin._textureAlpha = value; }, width : function(pin, value) { pin._width_ = value; pin._width = value; pin._ts_transform = ++iid; }, height : function(pin, value) { pin._height_ = value; pin._height = value; pin._ts_transform = ++iid; }, scale : function(pin, value) { pin._scaleX = value; pin._scaleY = value; pin._ts_transform = ++iid; }, scaleX : function(pin, value) { pin._scaleX = value; pin._ts_transform = ++iid; }, scaleY : function(pin, value) { pin._scaleY = value; pin._ts_transform = ++iid; }, skew : function(pin, value) { pin._skewX = value; pin._skewY = value; pin._ts_transform = ++iid; }, skewX : function(pin, value) { pin._skewX = value; pin._ts_transform = ++iid; }, skewY : function(pin, value) { pin._skewY = value; pin._ts_transform = ++iid; }, rotation : function(pin, value) { pin._rotation = value; pin._ts_transform = ++iid; }, pivot : function(pin, value) { pin._pivotX = value; pin._pivotY = value; pin._pivoted = true; pin._ts_transform = ++iid; }, pivotX : function(pin, value) { pin._pivotX = value; pin._pivoted = true; pin._ts_transform = ++iid; }, pivotY : function(pin, value) { pin._pivotY = value; pin._pivoted = true; pin._ts_transform = ++iid; }, offset : function(pin, value) { pin._offsetX = value; pin._offsetY = value; pin._ts_translate = ++iid; }, offsetX : function(pin, value) { pin._offsetX = value; pin._ts_translate = ++iid; }, offsetY : function(pin, value) { pin._offsetY = value; pin._ts_translate = ++iid; }, align : function(pin, value) { this.alignX(pin, value); this.alignY(pin, value); }, alignX : function(pin, value) { pin._alignX = value; pin._aligned = true; pin._ts_translate = ++iid; this.handleX(pin, value); }, alignY : function(pin, value) { pin._alignY = value; pin._aligned = true; pin._ts_translate = ++iid; this.handleY(pin, value); }, handle : function(pin, value) { this.handleX(pin, value); this.handleY(pin, value); }, handleX : function(pin, value) { pin._handleX = value; pin._handled = true; pin._ts_translate = ++iid; }, handleY : function(pin, value) { pin._handleY = value; pin._handled = true; pin._ts_translate = ++iid; }, resizeMode : function(pin, value, all) { if (all) { if (value == 'in') { value = 'in-pad'; } else if (value == 'out') { value = 'out-crop'; } scaleTo(pin, all.resizeWidth, all.resizeHeight, value); } }, resizeWidth : function(pin, value, all) { if (!all || !all.resizeMode) { scaleTo(pin, value, null); } }, resizeHeight : function(pin, value, all) { if (!all || !all.resizeMode) { scaleTo(pin, null, value); } }, scaleMode : function(pin, value, all) { if (all) { scaleTo(pin, all.scaleWidth, all.scaleHeight, value); } }, scaleWidth : function(pin, value, all) { if (!all || !all.scaleMode) { scaleTo(pin, value, null); } }, scaleHeight : function(pin, value, all) { if (!all || !all.scaleMode) { scaleTo(pin, null, value); } }, matrix : function(pin, value) { this.scaleX(pin, value.a); this.skewX(pin, value.c / value.d); this.skewY(pin, value.b / value.a); this.scaleY(pin, value.d); this.offsetX(pin, value.e); this.offsetY(pin, value.f); this.rotation(pin, 0); } }; function scaleTo(pin, width, height, mode) { var w = typeof width === 'number'; var h = typeof height === 'number'; var m = typeof mode === 'string'; pin._ts_transform = ++iid; if (w) { pin._scaleX = width / pin._width_; pin._width = pin._width_; } if (h) { pin._scaleY = height / pin._height_; pin._height = pin._height_; } if (w && h && m) { if (mode == 'out' || mode == 'out-crop') { pin._scaleX = pin._scaleY = Math.max(pin._scaleX, pin._scaleY); } else if (mode == 'in' || mode == 'in-pad') { pin._scaleX = pin._scaleY = Math.min(pin._scaleX, pin._scaleY); } if (mode == 'out-crop' || mode == 'in-pad') { pin._width = width / pin._scaleX; pin._height = height / pin._scaleY; } } }; Class.prototype.scaleTo = function(a, b, c) { if (typeof a === 'object') c = b, b = a.y, a = a.x; scaleTo(this._pin, a, b, c); return this; }; // Used by Tween class Pin._add_shortcuts = function(Class) { Class.prototype.size = function(w, h) { this.pin('width', w); this.pin('height', h); return this; }; Class.prototype.width = function(w) { if (typeof w === 'undefined') { return this.pin('width'); } this.pin('width', w); return this; }; Class.prototype.height = function(h) { if (typeof h === 'undefined') { return this.pin('height'); } this.pin('height', h); return this; }; Class.prototype.offset = function(a, b) { if (typeof a === 'object') b = a.y, a = a.x; this.pin('offsetX', a); this.pin('offsetY', b); return this; }; Class.prototype.rotate = function(a) { this.pin('rotation', a); return this; }; Class.prototype.skew = function(a, b) { if (typeof a === 'object') b = a.y, a = a.x; else if (typeof b === 'undefined') b = a; this.pin('skewX', a); this.pin('skewY', b); return this; }; Class.prototype.scale = function(a, b) { if (typeof a === 'object') b = a.y, a = a.x; else if (typeof b === 'undefined') b = a; this.pin('scaleX', a); this.pin('scaleY', b); return this; }; Class.prototype.alpha = function(a, ta) { this.pin('alpha', a); if (typeof ta !== 'undefined') { this.pin('textureAlpha', ta); } return this; }; }; Pin._add_shortcuts(Class); module.exports = Pin; },{"./core":60,"./matrix":67}],69:[function(require,module,exports){ var Class = require('./core'); require('./pin'); require('./loop'); var stats = require('./util/stats'); var create = require('./util/create'); var extend = require('./util/extend'); Root._super = Class; Root.prototype = create(Root._super.prototype); Class.root = function(request, render) { return new Root(request, render); }; function Root(request, render) { Root._super.call(this); this.label('Root'); var paused = true; var self = this; var lastTime = 0; var loop = function(now) { if (paused === true) { return; } stats.tick = stats.node = stats.draw = 0; var last = lastTime || now; var elapsed = now - last; lastTime = now; var ticked = self._tick(elapsed, now, last); if (self._mo_touch != self._ts_touch) { self._mo_touch = self._ts_touch; render(self); request(loop); } else if (ticked) { request(loop); } else { paused = true; } stats.fps = elapsed ? 1000 / elapsed : 0; }; this.start = function() { return this.resume(); }; this.resume = function() { if (paused) { this.publish('resume'); paused = false; request(loop); } return this; }; this.pause = function() { if (!paused) { this.publish('pause'); } paused = true; return this; }; this.touch_root = this.touch; this.touch = function() { this.resume(); return this.touch_root(); }; }; Root.prototype.background = function(color) { // to be implemented by loaders return this; }; Root.prototype.viewport = function(width, height, ratio) { if (typeof width === 'undefined') { return extend({}, this._viewport); } this._viewport = { width : width, height : height, ratio : ratio || 1 }; this.viewbox(); var data = extend({}, this._viewport); this.visit({ start : function(node) { if (!node._flag('viewport')) { return true; } node.publish('viewport', [ data ]); } }); return this; }; // TODO: static/fixed viewbox Root.prototype.viewbox = function(width, height, mode) { if (typeof width === 'number' && typeof height === 'number') { this._viewbox = { width : width, height : height, mode : /^(in|out|in-pad|out-crop)$/.test(mode) ? mode : 'in-pad' }; } var box = this._viewbox; var size = this._viewport; if (size && box) { this.pin({ width : box.width, height : box.height }); this.scaleTo(size.width, size.height, box.mode); } else if (size) { this.pin({ width : size.width, height : size.height }); } return this; }; },{"./core":60,"./loop":66,"./pin":68,"./util/create":74,"./util/extend":76,"./util/stats":80}],70:[function(require,module,exports){ var Class = require('./core'); require('./pin'); require('./loop'); var create = require('./util/create'); var is = require('./util/is'); Class.string = function(frames) { return new Str().frames(frames); }; Str._super = Class; Str.prototype = create(Str._super.prototype); function Str() { Str._super.call(this); this.label('String'); this._textures = []; }; /** * @deprecated Use frames */ Str.prototype.setFont = function(a, b, c) { return this.frames(a, b, c); }; Str.prototype.frames = function(frames) { this._textures = []; if (typeof frames == 'string') { frames = Class.texture(frames); this._item = function(value) { return frames.one(value); }; } else if (typeof frames === 'object') { this._item = function(value) { return frames[value]; }; } else if (typeof frames === 'function') { this._item = frames; } return this; }; /** * @deprecated Use value */ Str.prototype.setValue = function(a, b, c) { return this.value(a, b, c); }; Str.prototype.value = function(value) { if (typeof value === 'undefined') { return this._value; } if (this._value === value) { return this; } this._value = value; if (value === null) { value = ''; } else if (typeof value !== 'string' && !is.array(value)) { value = value.toString(); } this._spacing = this._spacing || 0; var width = 0, height = 0; for (var i = 0; i < value.length; i++) { var image = this._textures[i] = this._item(value[i]); width += i > 0 ? this._spacing : 0; image.dest(width, 0); width = width + image.width; height = Math.max(height, image.height); } this.pin('width', width); this.pin('height', height); this._textures.length = value.length; return this; }; },{"./core":60,"./loop":66,"./pin":68,"./util/create":74,"./util/is":77}],71:[function(require,module,exports){ var stats = require('./util/stats'); var math = require('./util/math'); function Texture(image, ratio) { if (typeof image === 'object') { this.src(image, ratio); } } Texture.prototype.pipe = function() { return new Texture(this); }; /** * Signatures: (image), (x, y, w, h), (w, h) */ Texture.prototype.src = function(x, y, w, h) { if (typeof x === 'object') { var image = x, ratio = y || 1; this._image = image; this._sx = this._dx = 0; this._sy = this._dy = 0; this._sw = this._dw = image.width / ratio; this._sh = this._dh = image.height / ratio; this.width = image.width / ratio; this.height = image.height / ratio; this.ratio = ratio; } else { if (typeof w === 'undefined') { w = x, h = y; } else { this._sx = x, this._sy = y; } this._sw = this._dw = w; this._sh = this._dh = h; this.width = w; this.height = h; } return this; }; /** * Signatures: (x, y, w, h), (x, y) */ Texture.prototype.dest = function(x, y, w, h) { this._dx = x, this._dy = y; this._dx = x, this._dy = y; if (typeof w !== 'undefined') { this._dw = w, this._dh = h; this.width = w, this.height = h; } return this; }; Texture.prototype.draw = function(context, x1, y1, x2, y2, x3, y3, x4, y4) { var image = this._image; if (image === null || typeof image !== 'object') { return; } var sx = this._sx, sy = this._sy; var sw = this._sw, sh = this._sh; var dx = this._dx, dy = this._dy; var dw = this._dw, dh = this._dh; if (typeof x3 !== 'undefined') { x1 = math.limit(x1, 0, this._sw), x2 = math.limit(x2, 0, this._sw - x1); y1 = math.limit(y1, 0, this._sh), y2 = math.limit(y2, 0, this._sh - y1); sx += x1, sy += y1, sw = x2, sh = y2; dx = x3, dy = y3, dw = x4, dh = y4; } else if (typeof x2 !== 'undefined') { dx = x1, dy = y1, dw = x2, dh = y2; } else if (typeof x1 !== 'undefined') { dw = x1, dh = y1; } var ratio = this.ratio || 1; sx *= ratio, sy *= ratio, sw *= ratio, sh *= ratio; try { if (typeof image.draw === 'function') { image.draw(context, sx, sy, sw, sh, dx, dy, dw, dh); } else { stats.draw++; context.drawImage(image, sx, sy, sw, sh, dx, dy, dw, dh); } } catch (ex) { if (!image._draw_failed) { console.log('Unable to draw: ', image); console.log(ex); image._draw_failed = true; } } }; module.exports = Texture; },{"./util/math":78,"./util/stats":80}],72:[function(require,module,exports){ var Class = require('./core'); var is = require('./util/is'); var iid = 0; // TODO: do not clear next/prev/parent on remove Class.prototype._label = ''; Class.prototype._visible = true; Class.prototype._parent = null; Class.prototype._next = null; Class.prototype._prev = null; Class.prototype._first = null; Class.prototype._last = null; Class.prototype._attrs = null; Class.prototype._flags = null; Class.prototype.toString = function() { return '[' + this._label + ']'; }; /** * @deprecated Use label() */ Class.prototype.id = function(id) { return this.label(id); }; Class.prototype.label = function(label) { if (typeof label === 'undefined') { return this._label; } this._label = label; return this; }; Class.prototype.attr = function(name, value) { if (typeof value === 'undefined') { return this._attrs !== null ? this._attrs[name] : undefined; } (this._attrs !== null ? this._attrs : this._attrs = {})[name] = value; return this; }; Class.prototype.visible = function(visible) { if (typeof visible === 'undefined') { return this._visible; } this._visible = visible; this._parent && (this._parent._ts_children = ++iid); this._ts_pin = ++iid; this.touch(); return this; }; Class.prototype.hide = function() { return this.visible(false); }; Class.prototype.show = function() { return this.visible(true); }; Class.prototype.parent = function() { return this._parent; }; Class.prototype.next = function(visible) { var next = this._next; while (next && visible && !next._visible) { next = next._next; } return next; }; Class.prototype.prev = function(visible) { var prev = this._prev; while (prev && visible && !prev._visible) { prev = prev._prev; } return prev; }; Class.prototype.first = function(visible) { var next = this._first; while (next && visible && !next._visible) { next = next._next; } return next; }; Class.prototype.last = function(visible) { var prev = this._last; while (prev && visible && !prev._visible) { prev = prev._prev; } return prev; }; Class.prototype.visit = function(visitor, data) { var reverse = visitor.reverse; var visible = visitor.visible; if (visitor.start && visitor.start(this, data)) { return; } var child, next = reverse ? this.last(visible) : this.first(visible); while (child = next) { next = reverse ? child.prev(visible) : child.next(visible); if (child.visit(visitor, data)) { return true; } } return visitor.end && visitor.end(this, data); }; Class.prototype.append = function(child, more) { if (is.array(child)) for (var i = 0; i < child.length; i++) append(this, child[i]); else if (typeof more !== 'undefined') // deprecated for (var i = 0; i < arguments.length; i++) append(this, arguments[i]); else if (typeof child !== 'undefined') append(this, child); return this; }; Class.prototype.prepend = function(child, more) { if (is.array(child)) for (var i = child.length - 1; i >= 0; i--) prepend(this, child[i]); else if (typeof more !== 'undefined') // deprecated for (var i = arguments.length - 1; i >= 0; i--) prepend(this, arguments[i]); else if (typeof child !== 'undefined') prepend(this, child); return this; }; Class.prototype.appendTo = function(parent) { append(parent, this); return this; }; Class.prototype.prependTo = function(parent) { prepend(parent, this); return this; }; Class.prototype.insertNext = function(sibling, more) { if (is.array(sibling)) for (var i = 0; i < sibling.length; i++) insertAfter(sibling[i], this); else if (typeof more !== 'undefined') // deprecated for (var i = 0; i < arguments.length; i++) insertAfter(arguments[i], this); else if (typeof sibling !== 'undefined') insertAfter(sibling, this); return this; }; Class.prototype.insertPrev = function(sibling, more) { if (is.array(sibling)) for (var i = sibling.length - 1; i >= 0; i--) insertBefore(sibling[i], this); else if (typeof more !== 'undefined') // deprecated for (var i = arguments.length - 1; i >= 0; i--) insertBefore(arguments[i], this); else if (typeof sibling !== 'undefined') insertBefore(sibling, this); return this; }; Class.prototype.insertAfter = function(prev) { insertAfter(this, prev); return this; }; Class.prototype.insertBefore = function(next) { insertBefore(this, next); return this; }; function append(parent, child) { _ensure(child); _ensure(parent); child.remove(); if (parent._last) { parent._last._next = child; child._prev = parent._last; } child._parent = parent; parent._last = child; if (!parent._first) { parent._first = child; } child._parent._flag(child, true); child._ts_parent = ++iid; parent._ts_children = ++iid; parent.touch(); } function prepend(parent, child) { _ensure(child); _ensure(parent); child.remove(); if (parent._first) { parent._first._prev = child; child._next = parent._first; } child._parent = parent; parent._first = child; if (!parent._last) { parent._last = child; } child._parent._flag(child, true); child._ts_parent = ++iid; parent._ts_children = ++iid; parent.touch(); }; function insertBefore(self, next) { _ensure(self); _ensure(next); self.remove(); var parent = next._parent; var prev = next._prev; next._prev = self; prev && (prev._next = self) || parent && (parent._first = self); self._parent = parent; self._prev = prev; self._next = next; self._parent._flag(self, true); self._ts_parent = ++iid; self.touch(); }; function insertAfter(self, prev) { _ensure(self); _ensure(prev); self.remove(); var parent = prev._parent; var next = prev._next; prev._next = self; next && (next._prev = self) || parent && (parent._last = self); self._parent = parent; self._prev = prev; self._next = next; self._parent._flag(self, true); self._ts_parent = ++iid; self.touch(); }; Class.prototype.remove = function(child, more) { if (typeof child !== 'undefined') { if (is.array(child)) { for (var i = 0; i < child.length; i++) _ensure(child[i]).remove(); } else if (typeof more !== 'undefined') { for (var i = 0; i < arguments.length; i++) _ensure(arguments[i]).remove(); } else { _ensure(child).remove(); } return this; } if (this._prev) { this._prev._next = this._next; } if (this._next) { this._next._prev = this._prev; } if (this._parent) { if (this._parent._first === this) { this._parent._first = this._next; } if (this._parent._last === this) { this._parent._last = this._prev; } this._parent._flag(this, false); this._parent._ts_children = ++iid; this._parent.touch(); } this._prev = this._next = this._parent = null; this._ts_parent = ++iid; // this._parent.touch(); return this; }; Class.prototype.empty = function() { var child, next = this._first; while (child = next) { next = child._next; child._prev = child._next = child._parent = null; this._flag(child, false); } this._first = this._last = null; this._ts_children = ++iid; this.touch(); return this; }; Class.prototype.touch = function() { this._ts_touch = ++iid; this._parent && this._parent.touch(); return this; }; /** * Deep flags used for optimizing event distribution. */ Class.prototype._flag = function(obj, name) { if (typeof name === 'undefined') { return this._flags !== null && this._flags[obj] || 0; } if (typeof obj === 'string') { if (name) { this._flags = this._flags || {}; if (!this._flags[obj] && this._parent) { this._parent._flag(obj, true); } this._flags[obj] = (this._flags[obj] || 0) + 1; } else if (this._flags && this._flags[obj] > 0) { if (this._flags[obj] == 1 && this._parent) { this._parent._flag(obj, false); } this._flags[obj] = this._flags[obj] - 1; } } if (typeof obj === 'object') { if (obj._flags) { for ( var type in obj._flags) { if (obj._flags[type] > 0) { this._flag(type, name); } } } } return this; }; /** * @private */ Class.prototype.hitTest = function(hit) { if (this.attr('spy')) { return true; } return hit.x >= 0 && hit.x <= this._pin._width && hit.y >= 0 && hit.y <= this._pin._height; }; function _ensure(obj) { if (obj && obj instanceof Class) { return obj; } throw 'Invalid node: ' + obj; }; module.exports = Class; },{"./core":60,"./util/is":77}],73:[function(require,module,exports){ module.exports = function() { var count = 0; function fork(fn, n) { count += n = (typeof n === 'number' && n >= 1 ? n : 1); return function() { fn && fn.apply(this, arguments); if (n > 0) { n--, count--, call(); } }; } var then = []; function call() { if (count === 0) { while (then.length) { setTimeout(then.shift(), 0); } } } fork.then = function(fn) { if (count === 0) { setTimeout(fn, 0); } else { then.push(fn); } }; return fork; }; },{}],74:[function(require,module,exports){ if (typeof Object.create == 'function') { module.exports = function(proto, props) { return Object.create.call(Object, proto, props); }; } else { module.exports = function(proto, props) { if (props) throw Error('Second argument is not supported!'); if (typeof proto !== 'object' || proto === null) throw Error('Invalid prototype!'); noop.prototype = proto; return new noop; }; function noop() { } } },{}],75:[function(require,module,exports){ module.exports = function(prototype, callback) { prototype._listeners = null; prototype.on = prototype.listen = function(types, listener) { if (!types || !types.length || typeof listener !== 'function') { return this; } if (this._listeners === null) { this._listeners = {}; } var isarray = typeof types !== 'string' && typeof types.join === 'function'; if (types = (isarray ? types.join(' ') : types).match(/\S+/g)) { for (var i = 0; i < types.length; i++) { var type = types[i]; this._listeners[type] = this._listeners[type] || []; this._listeners[type].push(listener); if (typeof callback === 'function') { callback(this, type, true); } } } return this; }; prototype.off = function(types, listener) { if (!types || !types.length || typeof listener !== 'function') { return this; } if (this._listeners === null) { return this; } var isarray = typeof types !== 'string' && typeof types.join === 'function'; if (types = (isarray ? types.join(' ') : types).match(/\S+/g)) { for (var i = 0; i < types.length; i++) { var type = types[i], all = this._listeners[type], index; if (all && (index = all.indexOf(listener)) >= 0) { all.splice(index, 1); if (!all.length) { delete this._listeners[type]; } if (typeof callback === 'function') { callback(this, type, false); } } } } return this; }; prototype.listeners = function(type) { return this._listeners && this._listeners[type]; }; prototype.publish = function(name, args) { var listeners = this.listeners(name); if (!listeners || !listeners.length) { return 0; } for (var l = 0; l < listeners.length; l++) { listeners[l].apply(this, args); } return listeners.length; }; prototype.trigger = function(name, args) { this.publish(name, args); return this; }; }; },{}],76:[function(require,module,exports){ module.exports = function(base) { for (var i = 1; i < arguments.length; i++) { var obj = arguments[i]; for ( var key in obj) { if (obj.hasOwnProperty(key)) { base[key] = obj[key]; } } } return base; }; },{}],77:[function(require,module,exports){ /** * ! is the definitive JavaScript type testing library * * @copyright 2013-2014 Enrico Marino / Jordan Harband * @license MIT */ var objProto = Object.prototype; var owns = objProto.hasOwnProperty; var toStr = objProto.toString; var NON_HOST_TYPES = { 'boolean' : 1, 'number' : 1, 'string' : 1, 'undefined' : 1 }; var hexRegex = /^[A-Fa-f0-9]+$/; var is = module.exports = {}; is.a = is.an = is.type = function(value, type) { return typeof value === type; }; is.defined = function(value) { return typeof value !== 'undefined'; }; is.empty = function(value) { var type = toStr.call(value); var key; if ('[object Array]' === type || '[object Arguments]' === type || '[object String]' === type) { return value.length === 0; } if ('[object Object]' === type) { for (key in value) { if (owns.call(value, key)) { return false; } } return true; } return !value; }; is.equal = function(value, other) { if (value === other) { return true; } var type = toStr.call(value); var key; if (type !== toStr.call(other)) { return false; } if ('[object Object]' === type) { for (key in value) { if (!is.equal(value[key], other[key]) || !(key in other)) { return false; } } for (key in other) { if (!is.equal(value[key], other[key]) || !(key in value)) { return false; } } return true; } if ('[object Array]' === type) { key = value.length; if (key !== other.length) { return false; } while (--key) { if (!is.equal(value[key], other[key])) { return false; } } return true; } if ('[object Function]' === type) { return value.prototype === other.prototype; } if ('[object Date]' === type) { return value.getTime() === other.getTime(); } return false; }; is.instance = function(value, constructor) { return value instanceof constructor; }; is.nil = function(value) { return value === null; }; is.undef = function(value) { return typeof value === 'undefined'; }; is.array = function(value) { return '[object Array]' === toStr.call(value); }; is.emptyarray = function(value) { return is.array(value) && value.length === 0; }; is.arraylike = function(value) { return !!value && !is.boolean(value) && owns.call(value, 'length') && isFinite(value.length) && is.number(value.length) && value.length >= 0; }; is.boolean = function(value) { return '[object Boolean]' === toStr.call(value); }; is.element = function(value) { return value !== undefined && typeof HTMLElement !== 'undefined' && value instanceof HTMLElement && value.nodeType === 1; }; is.fn = function(value) { return '[object Function]' === toStr.call(value); }; is.number = function(value) { return '[object Number]' === toStr.call(value); }; is.nan = function(value) { return !is.number(value) || value !== value; }; is.object = function(value) { return '[object Object]' === toStr.call(value); }; is.hash = function(value) { return is.object(value) && value.constructor === Object && !value.nodeType && !value.setInterval; }; is.regexp = function(value) { return '[object RegExp]' === toStr.call(value); }; is.string = function(value) { return '[object String]' === toStr.call(value); }; is.hex = function(value) { return is.string(value) && (!value.length || hexRegex.test(value)); }; },{}],78:[function(require,module,exports){ var create = require('./create'); var native = Math; module.exports = create(Math); module.exports.random = function(min, max) { if (typeof min === 'undefined') { max = 1, min = 0; } else if (typeof max === 'undefined') { max = min, min = 0; } return min == max ? min : native.random() * (max - min) + min; }; module.exports.rotate = function(num, min, max) { if (typeof min === 'undefined') { max = 1, min = 0; } else if (typeof max === 'undefined') { max = min, min = 0; } if (max > min) { num = (num - min) % (max - min); return num + (num < 0 ? max : min); } else { num = (num - max) % (min - max); return num + (num <= 0 ? min : max); } }; module.exports.limit = function(num, min, max) { if (num < min) { return min; } else if (num > max) { return max; } else { return num; } }; module.exports.length = function(x, y) { return native.sqrt(x * x + y * y); }; },{"./create":74}],79:[function(require,module,exports){ module.exports = function(img, owidth, oheight, stretch, inner, insert) { var width = img.width; var height = img.height; var left = img.left; var right = img.right; var top = img.top; var bottom = img.bottom; left = typeof left === 'number' && left === left ? left : 0; right = typeof right === 'number' && right === right ? right : 0; top = typeof top === 'number' && top === top ? top : 0; bottom = typeof bottom === 'number' && bottom === bottom ? bottom : 0; width = width - left - right; height = height - top - bottom; if (!inner) { owidth = Math.max(owidth - left - right, 0); oheight = Math.max(oheight - top - bottom, 0); } var i = 0; if (top > 0 && left > 0) insert(i++, 0, 0, left, top, 0, 0, left, top); if (bottom > 0 && left > 0) insert(i++, 0, height + top, left, bottom, 0, oheight + top, left, bottom); if (top > 0 && right > 0) insert(i++, width + left, 0, right, top, owidth + left, 0, right, top); if (bottom > 0 && right > 0) insert(i++, width + left, height + top, right, bottom, owidth + left, oheight + top, right, bottom); if (stretch) { if (top > 0) insert(i++, left, 0, width, top, left, 0, owidth, top); if (bottom > 0) insert(i++, left, height + top, width, bottom, left, oheight + top, owidth, bottom); if (left > 0) insert(i++, 0, top, left, height, 0, top, left, oheight); if (right > 0) insert(i++, width + left, top, right, height, owidth + left, top, right, oheight); // center insert(i++, left, top, width, height, left, top, owidth, oheight); } else { // tile var l = left, r = owidth, w; while (r > 0) { w = Math.min(width, r), r -= width; var t = top, b = oheight, h; while (b > 0) { h = Math.min(height, b), b -= height; insert(i++, left, top, w, h, l, t, w, h); if (r <= 0) { if (left) insert(i++, 0, top, left, h, 0, t, left, h); if (right) insert(i++, width + left, top, right, h, l + w, t, right, h); } t += h; } if (top) insert(i++, left, 0, w, top, l, 0, w, top); if (bottom) insert(i++, left, height + top, w, bottom, l, t, w, bottom); l += w; } } return i; }; },{}],80:[function(require,module,exports){ module.exports = {}; },{}],81:[function(require,module,exports){ module.exports.startsWith = function(str, sub) { return typeof str === 'string' && typeof sub === 'string' && str.substring(0, sub.length) == sub; }; },{}],82:[function(require,module,exports){ module.exports = require('../lib/'); module.exports.internal = {}; require('../lib/canvas'); module.exports.internal.Image = require('../lib/image'); require('../lib/anim'); require('../lib/str'); require('../lib/layout'); require('../lib/addon/tween'); module.exports.Mouse = require('../lib/addon/mouse'); module.exports.Math = require('../lib/util/math'); module.exports._extend = require('../lib/util/extend'); module.exports._create = require('../lib/util/create'); require('../lib/loader/web'); },{"../lib/":63,"../lib/addon/mouse":55,"../lib/addon/tween":56,"../lib/anim":57,"../lib/canvas":59,"../lib/image":62,"../lib/layout":64,"../lib/loader/web":65,"../lib/str":70,"../lib/util/create":74,"../lib/util/extend":76,"../lib/util/math":78}]},{},[1])(1) });
/* Copyright (c) 2003-2013, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ CKEDITOR.plugins.setLang( 'image', 'eo', { alertUrl: 'Bonvolu tajpi la retadreson de la bildo', alt: 'Anstataŭiga Teksto', border: 'Bordero', btnUpload: 'Sendu al Servilo', button2Img: 'Ĉu vi volas transformi la selektitan bildbutonon en simplan bildon?', hSpace: 'Horizontala Spaco', img2Button: 'Ĉu vi volas transformi la selektitan bildon en bildbutonon?', infoTab: 'Informoj pri Bildo', linkTab: 'Ligilo', lockRatio: 'Konservi Proporcion', menu: 'Atributoj de Bildo', resetSize: 'Origina Grando', title: 'Atributoj de Bildo', titleButton: 'Bildbutonaj Atributoj', upload: 'Alŝuti', urlMissing: 'La fontretadreso de la bildo mankas.', vSpace: 'Vertikala Spaco', validateBorder: 'La bordero devas esti entjera nombro.', validateHSpace: 'La horizontala spaco devas esti entjera nombro.', validateVSpace: 'La vertikala spaco devas esti entjera nombro.' });
define({ "_widgetLabel": "資訊摘要", "title": "InfoSummary Widget", "helpText": "InfoSummary 說明文字", "expand": "切換圖徵清單", "logoPrefix": "...的標誌 " });
"use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports["default"] = void 0; var _enzymeShallowEqual = _interopRequireDefault(require("enzyme-shallow-equal")); var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends")); var _assertThisInitialized2 = _interopRequireDefault(require("@babel/runtime/helpers/assertThisInitialized")); var _inheritsLoose2 = _interopRequireDefault(require("@babel/runtime/helpers/inheritsLoose")); var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty")); var _react = _interopRequireDefault(require("react")); var _propTypes = _interopRequireDefault(require("prop-types")); var _airbnbPropTypes = require("airbnb-prop-types"); var _reactWithStyles = require("react-with-styles"); var _throttle = _interopRequireDefault(require("lodash/throttle")); var _isTouchDevice = _interopRequireDefault(require("is-touch-device")); var _noflip = _interopRequireDefault(require("../utils/noflip")); var _getInputHeight = _interopRequireDefault(require("../utils/getInputHeight")); var _OpenDirectionShape = _interopRequireDefault(require("../shapes/OpenDirectionShape")); var _constants = require("../constants"); function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; } function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { (0, _defineProperty2["default"])(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } var FANG_PATH_TOP = "M0,".concat(_constants.FANG_HEIGHT_PX, " ").concat(_constants.FANG_WIDTH_PX, ",").concat(_constants.FANG_HEIGHT_PX, " ").concat(_constants.FANG_WIDTH_PX / 2, ",0z"); var FANG_STROKE_TOP = "M0,".concat(_constants.FANG_HEIGHT_PX, " ").concat(_constants.FANG_WIDTH_PX / 2, ",0 ").concat(_constants.FANG_WIDTH_PX, ",").concat(_constants.FANG_HEIGHT_PX); var FANG_PATH_BOTTOM = "M0,0 ".concat(_constants.FANG_WIDTH_PX, ",0 ").concat(_constants.FANG_WIDTH_PX / 2, ",").concat(_constants.FANG_HEIGHT_PX, "z"); var FANG_STROKE_BOTTOM = "M0,0 ".concat(_constants.FANG_WIDTH_PX / 2, ",").concat(_constants.FANG_HEIGHT_PX, " ").concat(_constants.FANG_WIDTH_PX, ",0"); var propTypes = process.env.NODE_ENV !== "production" ? (0, _airbnbPropTypes.forbidExtraProps)(_objectSpread({}, _reactWithStyles.withStylesPropTypes, { id: _propTypes["default"].string.isRequired, placeholder: _propTypes["default"].string, displayValue: _propTypes["default"].string, ariaLabel: _propTypes["default"].string, screenReaderMessage: _propTypes["default"].string, focused: _propTypes["default"].bool, disabled: _propTypes["default"].bool, required: _propTypes["default"].bool, readOnly: _propTypes["default"].bool, openDirection: _OpenDirectionShape["default"], showCaret: _propTypes["default"].bool, verticalSpacing: _airbnbPropTypes.nonNegativeInteger, small: _propTypes["default"].bool, block: _propTypes["default"].bool, regular: _propTypes["default"].bool, onChange: _propTypes["default"].func, onFocus: _propTypes["default"].func, onKeyDownShiftTab: _propTypes["default"].func, onKeyDownTab: _propTypes["default"].func, onKeyDownArrowDown: _propTypes["default"].func, onKeyDownQuestionMark: _propTypes["default"].func, // accessibility isFocused: _propTypes["default"].bool // describes actual DOM focus })) : {}; var defaultProps = { placeholder: 'Select Date', displayValue: '', ariaLabel: undefined, screenReaderMessage: '', focused: false, disabled: false, required: false, readOnly: null, openDirection: _constants.OPEN_DOWN, showCaret: false, verticalSpacing: _constants.DEFAULT_VERTICAL_SPACING, small: false, block: false, regular: false, onChange: function onChange() {}, onFocus: function onFocus() {}, onKeyDownShiftTab: function onKeyDownShiftTab() {}, onKeyDownTab: function onKeyDownTab() {}, onKeyDownArrowDown: function onKeyDownArrowDown() {}, onKeyDownQuestionMark: function onKeyDownQuestionMark() {}, // accessibility isFocused: false }; var DateInput = /*#__PURE__*/ function (_ref) { (0, _inheritsLoose2["default"])(DateInput, _ref); var _proto = DateInput.prototype; _proto[!_react["default"].PureComponent && "shouldComponentUpdate"] = function (nextProps, nextState) { return !(0, _enzymeShallowEqual["default"])(this.props, nextProps) || !(0, _enzymeShallowEqual["default"])(this.state, nextState); }; function DateInput(props) { var _this; _this = _ref.call(this, props) || this; _this.state = { dateString: '', isTouchDevice: false }; _this.onChange = _this.onChange.bind((0, _assertThisInitialized2["default"])(_this)); _this.onKeyDown = _this.onKeyDown.bind((0, _assertThisInitialized2["default"])(_this)); _this.setInputRef = _this.setInputRef.bind((0, _assertThisInitialized2["default"])(_this)); _this.throttledKeyDown = (0, _throttle["default"])(_this.onFinalKeyDown, 300, { trailing: false }); return _this; } _proto.componentDidMount = function componentDidMount() { this.setState({ isTouchDevice: (0, _isTouchDevice["default"])() }); }; _proto.componentWillReceiveProps = function componentWillReceiveProps(nextProps) { var dateString = this.state.dateString; if (dateString && nextProps.displayValue) { this.setState({ dateString: '' }); } }; _proto.componentDidUpdate = function componentDidUpdate(prevProps) { var _this$props = this.props, focused = _this$props.focused, isFocused = _this$props.isFocused; if (prevProps.focused === focused && prevProps.isFocused === isFocused) return; if (focused && isFocused) { this.inputRef.focus(); } }; _proto.onChange = function onChange(e) { var _this$props2 = this.props, onChange = _this$props2.onChange, onKeyDownQuestionMark = _this$props2.onKeyDownQuestionMark; var dateString = e.target.value; // In Safari, onKeyDown does not consistently fire ahead of onChange. As a result, we need to // special case the `?` key so that it always triggers the appropriate callback, instead of // modifying the input value if (dateString[dateString.length - 1] === '?') { onKeyDownQuestionMark(e); } else { this.setState({ dateString: dateString }, function () { return onChange(dateString); }); } }; _proto.onKeyDown = function onKeyDown(e) { e.stopPropagation(); if (!_constants.MODIFIER_KEY_NAMES.has(e.key)) { this.throttledKeyDown(e); } }; _proto.onFinalKeyDown = function onFinalKeyDown(e) { var _this$props3 = this.props, onKeyDownShiftTab = _this$props3.onKeyDownShiftTab, onKeyDownTab = _this$props3.onKeyDownTab, onKeyDownArrowDown = _this$props3.onKeyDownArrowDown, onKeyDownQuestionMark = _this$props3.onKeyDownQuestionMark; var key = e.key; if (key === 'Tab') { if (e.shiftKey) { onKeyDownShiftTab(e); } else { onKeyDownTab(e); } } else if (key === 'ArrowDown') { onKeyDownArrowDown(e); } else if (key === '?') { e.preventDefault(); onKeyDownQuestionMark(e); } }; _proto.setInputRef = function setInputRef(ref) { this.inputRef = ref; }; _proto.render = function render() { var _this$state = this.state, dateString = _this$state.dateString, isTouch = _this$state.isTouchDevice; var _this$props4 = this.props, id = _this$props4.id, placeholder = _this$props4.placeholder, ariaLabel = _this$props4.ariaLabel, displayValue = _this$props4.displayValue, screenReaderMessage = _this$props4.screenReaderMessage, focused = _this$props4.focused, showCaret = _this$props4.showCaret, onFocus = _this$props4.onFocus, disabled = _this$props4.disabled, required = _this$props4.required, readOnly = _this$props4.readOnly, openDirection = _this$props4.openDirection, verticalSpacing = _this$props4.verticalSpacing, small = _this$props4.small, regular = _this$props4.regular, block = _this$props4.block, styles = _this$props4.styles, reactDates = _this$props4.theme.reactDates; var value = dateString || displayValue || ''; var screenReaderMessageId = "DateInput__screen-reader-message-".concat(id); var withFang = showCaret && focused; var inputHeight = (0, _getInputHeight["default"])(reactDates, small); return _react["default"].createElement("div", (0, _reactWithStyles.css)(styles.DateInput, small && styles.DateInput__small, block && styles.DateInput__block, withFang && styles.DateInput__withFang, disabled && styles.DateInput__disabled, withFang && openDirection === _constants.OPEN_DOWN && styles.DateInput__openDown, withFang && openDirection === _constants.OPEN_UP && styles.DateInput__openUp), _react["default"].createElement("input", (0, _extends2["default"])({}, (0, _reactWithStyles.css)(styles.DateInput_input, small && styles.DateInput_input__small, regular && styles.DateInput_input__regular, readOnly && styles.DateInput_input__readOnly, focused && styles.DateInput_input__focused, disabled && styles.DateInput_input__disabled), { "aria-label": ariaLabel === undefined ? placeholder : ariaLabel, type: "text", id: id, name: id, ref: this.setInputRef, value: value, onChange: this.onChange, onKeyDown: this.onKeyDown, onFocus: onFocus, placeholder: placeholder, autoComplete: "off", disabled: disabled, readOnly: typeof readOnly === 'boolean' ? readOnly : isTouch, required: required, "aria-describedby": screenReaderMessage && screenReaderMessageId })), withFang && _react["default"].createElement("svg", (0, _extends2["default"])({ role: "presentation", focusable: "false" }, (0, _reactWithStyles.css)(styles.DateInput_fang, openDirection === _constants.OPEN_DOWN && { top: inputHeight + verticalSpacing - _constants.FANG_HEIGHT_PX - 1 }, openDirection === _constants.OPEN_UP && { bottom: inputHeight + verticalSpacing - _constants.FANG_HEIGHT_PX - 1 })), _react["default"].createElement("path", (0, _extends2["default"])({}, (0, _reactWithStyles.css)(styles.DateInput_fangShape), { d: openDirection === _constants.OPEN_DOWN ? FANG_PATH_TOP : FANG_PATH_BOTTOM })), _react["default"].createElement("path", (0, _extends2["default"])({}, (0, _reactWithStyles.css)(styles.DateInput_fangStroke), { d: openDirection === _constants.OPEN_DOWN ? FANG_STROKE_TOP : FANG_STROKE_BOTTOM }))), screenReaderMessage && _react["default"].createElement("p", (0, _extends2["default"])({}, (0, _reactWithStyles.css)(styles.DateInput_screenReaderMessage), { id: screenReaderMessageId }), screenReaderMessage)); }; return DateInput; }(_react["default"].PureComponent || _react["default"].Component); DateInput.propTypes = process.env.NODE_ENV !== "production" ? propTypes : {}; DateInput.defaultProps = defaultProps; var _default = (0, _reactWithStyles.withStyles)(function (_ref2) { var _ref2$reactDates = _ref2.reactDates, border = _ref2$reactDates.border, color = _ref2$reactDates.color, sizing = _ref2$reactDates.sizing, spacing = _ref2$reactDates.spacing, font = _ref2$reactDates.font, zIndex = _ref2$reactDates.zIndex; return { DateInput: { margin: 0, padding: spacing.inputPadding, background: color.background, position: 'relative', display: 'inline-block', width: sizing.inputWidth, verticalAlign: 'middle' }, DateInput__small: { width: sizing.inputWidth_small }, DateInput__block: { width: '100%' }, DateInput__disabled: { background: color.disabled, color: color.textDisabled }, DateInput_input: { fontWeight: font.input.weight, fontSize: font.input.size, lineHeight: font.input.lineHeight, color: color.text, backgroundColor: color.background, width: '100%', padding: "".concat(spacing.displayTextPaddingVertical, "px ").concat(spacing.displayTextPaddingHorizontal, "px"), paddingTop: spacing.displayTextPaddingTop, paddingBottom: spacing.displayTextPaddingBottom, paddingLeft: (0, _noflip["default"])(spacing.displayTextPaddingLeft), paddingRight: (0, _noflip["default"])(spacing.displayTextPaddingRight), border: border.input.border, borderTop: border.input.borderTop, borderRight: (0, _noflip["default"])(border.input.borderRight), borderBottom: border.input.borderBottom, borderLeft: (0, _noflip["default"])(border.input.borderLeft), borderRadius: border.input.borderRadius }, DateInput_input__small: { fontSize: font.input.size_small, lineHeight: font.input.lineHeight_small, letterSpacing: font.input.letterSpacing_small, padding: "".concat(spacing.displayTextPaddingVertical_small, "px ").concat(spacing.displayTextPaddingHorizontal_small, "px"), paddingTop: spacing.displayTextPaddingTop_small, paddingBottom: spacing.displayTextPaddingBottom_small, paddingLeft: (0, _noflip["default"])(spacing.displayTextPaddingLeft_small), paddingRight: (0, _noflip["default"])(spacing.displayTextPaddingRight_small) }, DateInput_input__regular: { fontWeight: 'auto' }, DateInput_input__readOnly: { userSelect: 'none' }, DateInput_input__focused: { outline: border.input.outlineFocused, background: color.backgroundFocused, border: border.input.borderFocused, borderTop: border.input.borderTopFocused, borderRight: (0, _noflip["default"])(border.input.borderRightFocused), borderBottom: border.input.borderBottomFocused, borderLeft: (0, _noflip["default"])(border.input.borderLeftFocused) }, DateInput_input__disabled: { background: color.disabled, fontStyle: font.input.styleDisabled }, DateInput_screenReaderMessage: { border: 0, clip: 'rect(0, 0, 0, 0)', height: 1, margin: -1, overflow: 'hidden', padding: 0, position: 'absolute', width: 1 }, DateInput_fang: { position: 'absolute', width: _constants.FANG_WIDTH_PX, height: _constants.FANG_HEIGHT_PX, left: 22, // TODO: should be noflip wrapped and handled by an isRTL prop zIndex: zIndex + 2 }, DateInput_fangShape: { fill: color.background }, DateInput_fangStroke: { stroke: color.core.border, fill: 'transparent' } }; }, { pureComponent: typeof _react["default"].PureComponent !== 'undefined' })(DateInput); exports["default"] = _default;
'use strict'; var repeat = require('repeat-string'); module.exports = strong; /* Stringify a `strong`. * * The marker used is configurable by `strong`, which * defaults to an asterisk (`'*'`) but also accepts an * underscore (`'_'`): * * __foo__ */ function strong(node) { var marker = repeat(this.options.strong, 2); return marker + this.all(node).join('') + marker; }
/*jshint globalstrict: true*/ 'use strict'; function addToScope(locals, identifier, instance) { if (locals && _.isObject(locals.$scope)) { locals.$scope[identifier] = instance; } else { throw 'Cannot export controller as ' + identifier + '! No $scope object provided via locals'; } } function $ControllerProvider() { var controllers = {}; var globals = false; this.allowGlobals = function() { globals = true; }; this.register = function(name, controller) { if (_.isObject(name)) { _.extend(controllers, name); } else { controllers[name] = controller; } }; this.$get = ['$injector', function($injector) { return function(ctrl, locals, later, identifier) { if (_.isString(ctrl)) { var match = ctrl.match(/^(\S+)(\s+as\s+(\w+))?/); ctrl = match[1]; identifier = identifier || match[3]; if (controllers.hasOwnProperty(ctrl)) { ctrl = controllers[ctrl]; } else if (globals) { ctrl = window[ctrl]; } } var instance; if (later) { var ctrlConstructor = _.isArray(ctrl) ? _.last(ctrl) : ctrl; instance = Object.create(ctrlConstructor.prototype); if (identifier) { addToScope(locals, identifier, instance); } return _.extend(function() { $injector.invoke(ctrl, instance, locals); return instance; }, { instance: instance }); } else { instance = $injector.instantiate(ctrl, locals); if (identifier) { addToScope(locals, identifier, instance); } return instance; } }; }]; }
var x = null; var o = { p: 0, ...x }; (o.p: empty); // error: number ~> empty
module.exports = { '2.2': require('./2_2'), '_default': require('./2_1'), '2.1': require('./2_1'), '2.0': require('./2_0'), '1.7': require('./1_7'), '1.6': require('./1_6'), '2.x': require('./2_x'), 'master': require('./master') };
// Copyright 2009 the Sputnik authors. All rights reserved. // This code is governed by the BSD license found in the LICENSE file. /** * @name: S11.8.3_A2.1_T3; * @section: 11.8.3, 11.8.5; * @assertion: Operator x <= y uses GetValue; * @description: If GetBase(y) is null, throw ReferenceError; */ //CHECK#1 try { 1 <= y; $ERROR('#1.1: 1 <= y throw ReferenceError. Actual: ' + (1 <= y)); } catch (e) { if ((e instanceof ReferenceError) !== true) { $ERROR('#1.2: 1 <= y throw ReferenceError. Actual: ' + (e)); } }
// @flow import type {Foo} from './foo'; import type {Bar} from './bar'; function f(x: Foo): Bar { return x; }
/** * Copyright (c) 2016-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ 'use strict'; const generate = require('babel-generator').default; const stub = require('sinon/lib/sinon/stub'); exports.fn = () => { const s = stub(); const f = jest.fn(s); f.stub = s; return f; }; const generateOptions = { concise: true }; exports.codeFromAst = ast => generate(ast, generateOptions).code; exports.comparableCode = code => code.trim().replace(/\s\s+/g, ' ');
define(function(require, exports, module) { exports.dirname = function(path) { if (path[path.length - 1] === '/') { path = path.substring(0, path.length - 1); } var parts = path.split("/"); return parts.slice(0, parts.length - 1).join("/"); }; exports.filename = function(path) { if (path[path.length - 1] === '/') { path = path.substring(0, path.length - 1); } var parts = path.split("/"); return parts[parts.length - 1]; }; exports.ext = function(path) { var filename = exports.filename(path); var parts = filename.split('.'); if(parts.length === 1) { return null; } return parts.slice(1).join("."); }; });
// Connect to MongoDB using Mongoose var mongoose = require('mongoose'); var db; if (process.env.VCAP_SERVICES) { var env = JSON.parse(process.env.VCAP_SERVICES); db = mongoose.createConnection(env['mongodb-2.2'][0].credentials.url); } else { db = mongoose.createConnection('localhost', 'pollsapp'); } // Get Poll schema and model var PollSchema = require('../models/Poll.js').PollSchema; var Poll = db.model('polls', PollSchema); // Main application view exports.index = function(req, res) { res.render('index'); }; // JSON API for list of polls exports.list = function(req, res) { // Query Mongo for polls, just get back the question text Poll.find({}, 'question', function(error, polls) { res.json(polls); }); }; // JSON API for getting a single poll exports.poll = function(req, res) { // Poll ID comes in the URL var pollId = req.params.id; // Find the poll by its ID, use lean as we won't be changing it Poll.findById(pollId, '', { lean: true }, function(err, poll) { if(poll) { var userVoted = false, userChoice, totalVotes = 0; // Loop through poll choices to determine if user has voted // on this poll, and if so, what they selected for(c in poll.choices) { var choice = poll.choices[c]; for(v in choice.votes) { var vote = choice.votes[v]; totalVotes++; if(vote.ip === (req.header('x-forwarded-for') || req.ip)) { userVoted = true; userChoice = { _id: choice._id, text: choice.text }; } } } // Attach info about user's past voting on this poll poll.userVoted = userVoted; poll.userChoice = userChoice; poll.totalVotes = totalVotes; res.json(poll); } else { res.json({error:true}); } }); }; // JSON API for creating a new poll exports.create = function(req, res) { var reqBody = req.body, // Filter out choices with empty text choices = reqBody.choices.filter(function(v) { return v.text != ''; }), // Build up poll object to save pollObj = {question: reqBody.question, choices: choices}; // Create poll model from built up poll object var poll = new Poll(pollObj); // Save poll to DB poll.save(function(err, doc) { if(err || !doc) { throw 'Error'; } else { res.json(doc); } }); }; exports.vote = function(socket) { socket.on('send:vote', function(data) { var ip = socket.handshake.headers['x-forwarded-for'] || socket.handshake.address.address; Poll.findById(data.poll_id, function(err, poll) { var choice = poll.choices.id(data.choice); choice.votes.push({ ip: ip }); poll.save(function(err, doc) { var theDoc = { question: doc.question, _id: doc._id, choices: doc.choices, userVoted: false, totalVotes: 0 }; // Loop through poll choices to determine if user has voted // on this poll, and if so, what they selected for(var i = 0, ln = doc.choices.length; i < ln; i++) { var choice = doc.choices[i]; for(var j = 0, jLn = choice.votes.length; j < jLn; j++) { var vote = choice.votes[j]; theDoc.totalVotes++; theDoc.ip = ip; if(vote.ip === ip) { theDoc.userVoted = true; theDoc.userChoice = { _id: choice._id, text: choice.text }; } } } socket.emit('myvote', theDoc); socket.broadcast.emit('vote', theDoc); }); }); }); };
require('../../tool-env/install-babel.js'); var _ = require('underscore'); var assert = require('assert'); var bundler = require('../../isobuild/bundler.js'); var release = require('../../packaging/release.js'); var files = require('../../fs/files.js'); var catalog = require('../../packaging/catalog/catalog.js'); var buildmessage = require('../../utils/buildmessage.js'); var isopackets = require('../../tool-env/isopackets.js'); var projectContextModule = require('../../project-context.js'); var lastTmpDir = null; var tmpDir = function () { return (lastTmpDir = files.mkdtemp()); }; var makeProjectContext = function (appName) { var projectDir = files.mkdtemp("test-bundler-options"); files.cp_r(files.pathJoin(files.convertToStandardPath(__dirname), appName), projectDir); var projectContext = new projectContextModule.ProjectContext({ projectDir: projectDir }); doOrThrow(function () { projectContext.prepareProjectForBuild(); }); return projectContext; }; var doOrThrow = function (f) { var ret; var messages = buildmessage.capture(function () { ret = f(); }); if (messages.hasMessages()) { throw Error(messages.formatMessages()); } return ret; }; var runTest = function () { // As preparation, let's initialize the official catalog. It servers as our // data store, so we will probably need it. catalog.official.initialize(); var readManifest = function (tmpOutputDir) { return JSON.parse(files.readFile( files.pathJoin(tmpOutputDir, "programs", "web.browser", "program.json"), "utf8")).manifest; }; // an empty app. notably this app has no .meteor/release file. var projectContext = makeProjectContext('empty-app'); console.log("basic version"); assert.doesNotThrow(function () { var tmpOutputDir = tmpDir(); var result = bundler.bundle({ projectContext: projectContext, outputPath: tmpOutputDir, buildOptions: { minifyMode: 'production' } }); assert.strictEqual(result.errors, false, result.errors && result.errors[0]); // sanity check -- main.js has expected contents. assert.strictEqual( files.readFile(files.pathJoin(tmpOutputDir, "main.js"), "utf8"), bundler._mainJsContents); // no top level node_modules directory assert(!files.exists(files.pathJoin(tmpOutputDir, "programs", "server", "node_modules"))); // yes package node_modules directory assert(files.lstat(files.pathJoin( tmpOutputDir, "programs", "server", "npm", "node_modules", "meteor", "ddp-server")) .isDirectory()); // verify that contents are minified var manifest = readManifest(tmpOutputDir); _.each(manifest, function (item) { if (item.type !== 'js') return; // Just a hash, and no "packages/". assert(/^[0-9a-f]{40,40}\.js$/.test(item.path), item.path); }); }); console.log("no minify"); assert.doesNotThrow(function () { var tmpOutputDir = tmpDir(); var result = bundler.bundle({ projectContext: projectContext, outputPath: tmpOutputDir, buildOptions: { minifyMode: 'development' } }); assert.strictEqual(result.errors, false); // sanity check -- main.js has expected contents. assert.strictEqual(files.readFile(files.pathJoin(tmpOutputDir, "main.js"), "utf8"), bundler._mainJsContents); // verify that contents are not minified var manifest = readManifest(tmpOutputDir); var foundMeteor = false; var foundTracker = false; _.each(manifest, function (item) { if (item.type !== 'js') return; // No minified hash. assert(!/^[0-9a-f]{40,40}\.js$/.test(item.path)); // No tests. assert(!/:tests/.test(item.path)); if (item.path === 'packages/meteor.js') foundMeteor = true; if (item.path === 'packages/tracker.js') foundTracker = true; }); assert(foundMeteor); assert(foundTracker); }); if (process.platform !== "win32") { // Windows doesn't have symlinks console.log("includeNodeModules"); assert.doesNotThrow(function () { var tmpOutputDir = tmpDir(); var result = bundler.bundle({ projectContext: projectContext, outputPath: tmpOutputDir, includeNodeModules: 'symlink' }); assert.strictEqual(result.errors, false); // sanity check -- main.js has expected contents. assert.strictEqual(files.readFile(files.pathJoin(tmpOutputDir, "main.js"), "utf8"), bundler._mainJsContents); // node_modules directory exists and is a symlink assert(files.lstat(files.pathJoin(tmpOutputDir, "programs", "server", "node_modules")).isSymbolicLink()); // node_modules contains fibers assert(files.exists(files.pathJoin(tmpOutputDir, "programs", "server", "node_modules", "fibers"))); // package node_modules directory also a symlink // XXX might be breaking this assert(files.lstat(files.pathJoin( tmpOutputDir, "programs", "server", "npm", "node_modules", "meteor", "ddp-server", "node_modules")) .isSymbolicLink()); }); } }; var Fiber = require('fibers'); Fiber(function () { if (! files.inCheckout()) { throw Error("This old test doesn't support non-checkout"); } release.setCurrent(release.load(null)); isopackets.ensureIsopacketsLoadable(); try { runTest(); } catch (err) { console.log(err.stack); console.log('\nBundle can be found at ' + lastTmpDir); process.exit(1); } }).run();
/* jshint node: true */ module.exports = function (environment) { var ENV = { modulePrefix: 'azureexplorer', environment: environment, baseURL: '/', locationType: 'hash', EmberENV: { FEATURES: { // Here you can enable experimental features on an ember canary build // e.g. 'with-controller': true } }, exportApplicationGlobal: true, APP: { // Here you can pass flags/options to your application instance // when it is created }, sassOptions: { includePaths: ['bower_components/materialize/sass'] }, dnsSuffixContent: ['blob.core.windows.net', 'blob.core.chinacloudapi.cn'] , // set default dns suffix urls /*jshint -W109 */ contentSecurityPolicy: { 'default-src': "'none'", 'script-src': "'unsafe-inline' 'self' https://cdn.mxpnl.com", // Allow scripts from https://cdn.mxpnl.com 'font-src': "'self' http://fonts.gstatic.com", // Allow fonts to be loaded from http://fonts.gstatic.com 'connect-src': "'self' https://api.mixpanel.com http://custom-api.local", // Allow data (ajax/websocket) from api.mixpanel.com and custom-api.local 'img-src': "'self'", 'style-src': "'self' 'unsafe-inline' http://fonts.googleapis.com", // Allow inline styles and loaded CSS from http://fonts.googleapis.com 'media-src': "'self'" } /*jshint +W109 */ }; if (environment === 'test') { // Testem prefers this... ENV.baseURL = '/'; ENV.locationType = 'none'; // keep test console output quieter ENV.APP.LOG_ACTIVE_GENERATION = false; ENV.APP.LOG_VIEW_LOOKUPS = false; ENV.APP.rootElement = '#ember-testing'; } if (process && process.env) { process.env.EMBER_CLI_NW = true; } if (environment === 'production') { } // if (environment === 'development') { // ENV.APP.LOG_RESOLVER = true; // ENV.APP.LOG_ACTIVE_GENERATION = true; // ENV.APP.LOG_TRANSITIONS = true; // ENV.APP.LOG_TRANSITIONS_INTERNAL = true; // ENV.APP.LOG_VIEW_LOOKUPS = true; // } return ENV; };
'use strict'; module.exports = { db: 'mongodb://localhost/angle-test', port: 3001, app: { title: 'Angle - Test Environment' }, facebook: { clientID: process.env.FACEBOOK_ID || 'APP_ID', clientSecret: process.env.FACEBOOK_SECRET || 'APP_SECRET', callbackURL: '/auth/facebook/callback' }, twitter: { clientID: process.env.TWITTER_KEY || 'CONSUMER_KEY', clientSecret: process.env.TWITTER_SECRET || 'CONSUMER_SECRET', callbackURL: '/auth/twitter/callback' }, google: { clientID: process.env.GOOGLE_ID || 'APP_ID', clientSecret: process.env.GOOGLE_SECRET || 'APP_SECRET', callbackURL: '/auth/google/callback' }, linkedin: { clientID: process.env.LINKEDIN_ID || 'APP_ID', clientSecret: process.env.LINKEDIN_SECRET || 'APP_SECRET', callbackURL: '/auth/linkedin/callback' }, github: { clientID: process.env.GITHUB_ID || 'APP_ID', clientSecret: process.env.GITHUB_SECRET || 'APP_SECRET', callbackURL: '/auth/github/callback' }, mailer: { from: process.env.MAILER_FROM || 'MAILER_FROM', options: { service: process.env.MAILER_SERVICE_PROVIDER || 'MAILER_SERVICE_PROVIDER', auth: { user: process.env.MAILER_EMAIL_ID || 'MAILER_EMAIL_ID', pass: process.env.MAILER_PASSWORD || 'MAILER_PASSWORD' } } } };
/* Copyright (c) 2003-2015, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ CKEDITOR.plugins.setLang( 'scayt', 'fi', { btn_about: 'Tietoja oikoluvusta kirjoitetaessa', btn_dictionaries: 'Sanakirjat', btn_disable: 'Poista käytöstä oikoluku kirjoitetaessa', btn_enable: 'Ota käyttöön oikoluku kirjoitettaessa', btn_langs:'Kielet', btn_options: 'Asetukset', text_title: 'Oikolue kirjoitettaessa' });
import fileType from 'file-type'; const buffer = new Buffer(1); const array = new Uint8Array(buffer); const type1 = fileType(buffer); if (type1) { type1.ext; } const type2 = fileType(array); // $ExpectError type2.ext; if (type2) { type2.mime; } // $ExpectError fileType('');
'use strict'; // Create a report about unused icons in a project. var fs = require('fs'); var path = require('path'); var exec = require('child_process').exec; var optimist = require('optimist'); var cli = optimist .usage('Create a report about unused icons in a project.' + '\n' + 'Usage: $0 path/to/your/project/'); var projectDir = cli.argv._[0]; // No folder passed? Show help message then. if (!projectDir) { cli.showHelp(); process.exit(0); } // Check if the directory exist. var stats = fs.lstatSync(projectDir); if (!stats.isDirectory()) { console.log('\x1b[31mPlease provide a valid folder.\x1b[0m\n'); cli.showHelp(); process.exit(0); } /** * Get the list of all the icons in the font. * @returns {Array} */ function getIcons() { var icons = fs.readdirSync('./images/'); icons = icons.map(function(icon) { return path.basename(icon, '.svg'); }); return icons; } /** * Use a grep pattern to extract used icons from files. * @param {string} grep * @param {Function} callback */ function getUsedIcons(grep, callback) { exec(grep, function(err, stdout, stderr) { var usedIcons = stdout .trim() .split('\n') .map(function(icon) { // Take only the icon name. return icon.split(/["']/)[1]; }) .filter(function(icon) { // Remove non string items. return icon && icon.match(/^[a-z0-9-]+$/); }); callback(usedIcons); if (err) { console.log(err); } }); } /** * Get the list of unused icons in a folder. The patterns of extraction are: * * data-icon="[^"]+" * * .dataset.icon ?= ?.+ */ function getUnusedIcons() { var usedIcons = []; var length = 2; var cb = function(icons) { usedIcons = usedIcons.concat(icons); length--; if (length > 0) { return; } var allIcons = getIcons(); var unusedIcons = []; allIcons.forEach(function(icon) { if (usedIcons.indexOf(icon) === -1) { unusedIcons.push(icon); } }); outputUnusedIcons(allIcons, unusedIcons); }; getUsedIcons('grep -rhoP \'data-icon="[^"]+"\' ' + projectDir, cb); getUsedIcons('grep -rhoP \'.dataset.icon ?= ?.+\' ' + projectDir, cb); } /** * Display the list of unused icons to the screen. * @param {Array.<string>} icons * @param {Array.<string>} unusedIcons */ function outputUnusedIcons(icons, unusedIcons) { console.log('\x1b[36mList of unused icons in %s (%d/%d):\x1b[0m', projectDir, unusedIcons.length, icons.length); unusedIcons.forEach(function(icon) { console.log('* ' + icon); }); } getUnusedIcons();
/*eslint no-console: 0 */ "use strict"; // wrap returns a function that will invoke the supplied function and print a deprecation warning to the console each // time it is called. exports.wrap = function (func, msg) { var wrapped = function () { // Watch out for IE7 and below! :( if (typeof console !== "undefined") { if (console.info) { console.info(msg); } else { console.log(msg); } } return func.apply(this, arguments); }; if (func.prototype) { wrapped.prototype = func.prototype; } return wrapped; }; // defaultMsg returns a string which can be supplied to `wrap()` to notify the user that a particular part of the // sinon API has been deprecated. exports.defaultMsg = function (funcName) { return "sinon." + funcName + " is deprecated and will be removed from the public API in a future version of sinon."; };
/*! * ui-grid - v4.5.0 - 2018-06-15 * Copyright (c) 2018 ; License: MIT */ (function () { angular.module('ui.grid').config(['$provide', function($provide) { $provide.decorator('i18nService', ['$delegate', function($delegate) { $delegate.add('es', { aggregate: { label: 'Artículos' }, groupPanel: { description: 'Arrastre un encabezado de columna aquí y suéltelo para agrupar por esa columna.' }, search: { placeholder: 'Buscar...', showingItems: 'Artículos Mostrados:', selectedItems: 'Artículos Seleccionados:', totalItems: 'Artículos Totales:', size: 'Tamaño de Página:', first: 'Primera Página', next: 'Página Siguiente', previous: 'Página Anterior', last: 'Última Página' }, menu: { text: 'Elegir columnas:' }, sort: { ascending: 'Orden Ascendente', descending: 'Orden Descendente', remove: 'Sin Ordenar' }, column: { hide: 'Ocultar la columna' }, aggregation: { count: 'filas totales: ', sum: 'total: ', avg: 'media: ', min: 'min: ', max: 'max: ' }, pinning: { pinLeft: 'Fijar a la Izquierda', pinRight: 'Fijar a la Derecha', unpin: 'Quitar Fijación' }, gridMenu: { columns: 'Columnas:', importerTitle: 'Importar archivo', exporterAllAsCsv: 'Exportar todo como csv', exporterVisibleAsCsv: 'Exportar vista como csv', exporterSelectedAsCsv: 'Exportar selección como csv', exporterAllAsPdf: 'Exportar todo como pdf', exporterVisibleAsPdf: 'Exportar vista como pdf', exporterSelectedAsPdf: 'Exportar selección como pdf', exporterAllAsExcel: 'Exportar todo como excel', exporterVisibleAsExcel: 'Exportar vista como excel', exporterSelectedAsExcel: 'Exportar selección como excel', clearAllFilters: 'Limpiar todos los filtros' }, importer: { noHeaders: 'No fue posible derivar los nombres de las columnas, ¿tiene encabezados el archivo?', noObjects: 'No fue posible obtener registros, ¿contiene datos el archivo, aparte de los encabezados?', invalidCsv: 'No fue posible procesar el archivo, ¿es un CSV válido?', invalidJson: 'No fue posible procesar el archivo, ¿es un Json válido?', jsonNotArray: 'El archivo json importado debe contener un array, abortando.' }, pagination: { sizes: 'registros por página', totalItems: 'registros', of: 'de' }, grouping: { group: 'Agrupar', ungroup: 'Desagrupar', aggregate_count: 'Agr: Cont', aggregate_sum: 'Agr: Sum', aggregate_max: 'Agr: Máx', aggregate_min: 'Agr: Min', aggregate_avg: 'Agr: Prom', aggregate_remove: 'Agr: Quitar' } }); return $delegate; }]); }]); })();
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var tslib_1 = require("tslib"); var Canvas_1 = require("./Canvas"); var EventListeners_1 = require("../Utils/EventListeners"); var Particles_1 = require("./Particles"); var Retina_1 = require("./Retina"); var FrameManager_1 = require("./FrameManager"); var Options_1 = require("../Options/Classes/Options"); var Plugins_1 = require("../Utils/Plugins"); var SimplexNoise_1 = require("../Utils/SimplexNoise"); var Container = (function () { function Container(id, params) { var presets = []; for (var _i = 2; _i < arguments.length; _i++) { presets[_i - 2] = arguments[_i]; } this.started = false; this.destroyed = false; this.id = id; this.paused = true; this.sourceOptions = params; this.lastFrameTime = 0; this.pageHidden = false; this.retina = new Retina_1.Retina(this); this.canvas = new Canvas_1.Canvas(this); this.particles = new Particles_1.Particles(this); this.drawer = new FrameManager_1.FrameManager(this); this.interactivity = { mouse: {}, }; this.bubble = {}; this.repulse = { particles: [] }; this.plugins = {}; this.drawers = {}; this.density = 1; this.options = new Options_1.Options(); for (var _a = 0, presets_1 = presets; _a < presets_1.length; _a++) { var preset = presets_1[_a]; this.options.load(Plugins_1.Plugins.getPreset(preset)); } for (var _b = 0, _c = Plugins_1.Plugins.getSupportedShapes(); _b < _c.length; _b++) { var type = _c[_b]; this.drawers[type] = Plugins_1.Plugins.getShapeDrawer(type); } if (this.sourceOptions) { this.options.load(this.sourceOptions); } this.simplex = new SimplexNoise_1.SimplexNoise(); this.eventListeners = new EventListeners_1.EventListeners(this); } Container.requestFrame = function (callback) { return window.customRequestAnimationFrame(callback); }; Container.cancelAnimation = function (handle) { window.cancelAnimationFrame(handle); }; Container.prototype.play = function (force) { var needsUpdate = this.paused || force; if (this.paused) { this.paused = false; } if (needsUpdate) { for (var id in this.plugins) { var plugin = this.plugins[id]; if (plugin.play) { plugin.play(); } } this.lastFrameTime = performance.now(); } this.draw(); }; Container.prototype.pause = function () { if (this.drawAnimationFrame !== undefined) { Container.cancelAnimation(this.drawAnimationFrame); delete this.drawAnimationFrame; } if (!this.paused) { for (var id in this.plugins) { var plugin = this.plugins[id]; if (plugin.pause) { plugin.pause(); } } if (!this.pageHidden) { this.paused = true; } } }; Container.prototype.draw = function () { var _this = this; this.drawAnimationFrame = Container.requestFrame(function (t) { return _this.drawer.nextFrame(t); }); }; Container.prototype.getAnimationStatus = function () { return !this.paused; }; Container.prototype.densityAutoParticles = function () { this.initDensityFactor(); var numberOptions = this.options.particles.number; var optParticlesNumber = numberOptions.value; var optParticlesLimit = numberOptions.limit > 0 ? numberOptions.limit : optParticlesNumber; var particlesNumber = Math.min(optParticlesNumber, optParticlesLimit) * this.density; var particlesCount = this.particles.count; if (particlesCount < particlesNumber) { this.particles.push(Math.abs(particlesNumber - particlesCount)); } else if (particlesCount > particlesNumber) { this.particles.removeQuantity(particlesCount - particlesNumber); } }; Container.prototype.initDensityFactor = function () { var densityOptions = this.options.particles.number.density; if (!this.canvas.element || !densityOptions.enable) { return; } var canvas = this.canvas.element; var pxRatio = this.retina.pixelRatio; this.density = (canvas.width * canvas.height) / (densityOptions.factor * pxRatio * densityOptions.area); }; Container.prototype.destroy = function () { this.stop(); this.retina.reset(); this.canvas.destroy(); delete this.interactivity; delete this.options; delete this.retina; delete this.canvas; delete this.particles; delete this.bubble; delete this.repulse; delete this.drawer; delete this.eventListeners; for (var type in this.drawers) { var drawer = this.drawers[type]; if (drawer.destroy !== undefined) { drawer.destroy(this); } } this.drawers = {}; this.destroyed = true; }; Container.prototype.exportImg = function (callback) { this.exportImage(callback); }; Container.prototype.exportImage = function (callback, type, quality) { var _a; return (_a = this.canvas.element) === null || _a === void 0 ? void 0 : _a.toBlob(callback, type !== null && type !== void 0 ? type : "image/png", quality); }; Container.prototype.exportConfiguration = function () { return JSON.stringify(this.options, undefined, 2); }; Container.prototype.refresh = function () { return tslib_1.__awaiter(this, void 0, void 0, function () { return tslib_1.__generator(this, function (_a) { switch (_a.label) { case 0: this.stop(); return [4, this.start()]; case 1: _a.sent(); return [2]; } }); }); }; Container.prototype.stop = function () { if (!this.started) { return; } this.started = false; this.eventListeners.removeListeners(); this.pause(); this.particles.clear(); this.retina.reset(); this.canvas.clear(); for (var id in this.plugins) { var plugin = this.plugins[id]; if (plugin.stop !== undefined) { plugin.stop(); } } this.plugins = {}; delete this.particles.lineLinkedColor; }; Container.prototype.start = function () { return tslib_1.__awaiter(this, void 0, void 0, function () { var availablePlugins, id, _a, _b, _i, id, plugin, _c, _d, _e, type, drawer; return tslib_1.__generator(this, function (_f) { switch (_f.label) { case 0: if (this.started) { return [2]; } availablePlugins = Plugins_1.Plugins.getAvailablePlugins(this); for (id in availablePlugins) { this.plugins[id] = availablePlugins[id]; } this.started = true; this.eventListeners.addListeners(); _a = []; for (_b in this.plugins) _a.push(_b); _i = 0; _f.label = 1; case 1: if (!(_i < _a.length)) return [3, 5]; id = _a[_i]; plugin = this.plugins[id]; if (!(plugin.startAsync !== undefined)) return [3, 3]; return [4, plugin.startAsync()]; case 2: _f.sent(); return [3, 4]; case 3: if (plugin.start !== undefined) { plugin.start(); } _f.label = 4; case 4: _i++; return [3, 1]; case 5: _c = []; for (_d in this.drawers) _c.push(_d); _e = 0; _f.label = 6; case 6: if (!(_e < _c.length)) return [3, 9]; type = _c[_e]; drawer = this.drawers[type]; if (!(drawer.init !== undefined)) return [3, 8]; return [4, drawer.init(this)]; case 7: _f.sent(); _f.label = 8; case 8: _e++; return [3, 6]; case 9: this.init(); this.play(); return [2]; } }); }); }; Container.prototype.init = function () { this.retina.init(); this.canvas.init(); this.particles.init(); this.densityAutoParticles(); for (var id in this.plugins) { var plugin = this.plugins[id]; if (plugin.init !== undefined) { plugin.init(); } } }; return Container; }()); exports.Container = Container;
var foxy = require("./index"); var request = require("supertest"); var connect = require("connect"); var http = require("http"); var multi = require("multiline"); var config = { rules: { match: /Hi there/, fn: function (match) { return "Browser Sync " + match } } } var app = connect(); var output = multi(function () {/* <!doctype html> <html lang="en-US"> <head> <meta charset="UTF-8"> <title></title> </head> <body> Hi there </body> </html> */}); app.use("/hello", function (req, res, next) { res.end(output); }); var server = http.createServer(app).listen(); var proxy = foxy("http://localhost:" + server.address().port, config); request(proxy) .get("/hello") .set("accept", "text/html") .expect(200) .end(function (err, res) { console.log(res.text); console.log(res.text.indexOf("Browser Sync") === -1); server.close(); });
/** * Fill metadataStore with metadata * DO NOT USE! * This is the old version whose metadata were semi-generated in tortured fashion * from an EDM. The current version is metadata.js which defines metadata by hand * * Hold on to this version for reference */ (function(angular) { 'use strict'; angular.module("app").factory( 'metadata', factory ); function factory(breeze) { setNamingConvention(); return { fillStore: fillStore }; ///////////////////// function setNamingConvention() { // Translate certain zza property names between MongoDb names and client names var convention = new breeze.NamingConvention({ serverPropertyNameToClient: function(serverPropertyName) { switch (serverPropertyName) { case '_id': return 'id'; case 'qty': return 'quantity'; case 'optionId': return 'productOptionId'; case 'sizeId': return 'productSizeId'; case 'items': return 'orderItems'; case 'options': return 'orderItemOptions'; default: return serverPropertyName; } }, clientPropertyNameToServer: function(clientPropertyName) { switch (clientPropertyName) { case 'id': return '_id'; case 'quantity': return 'qty'; case 'productOptionId': return 'optionId'; case 'productSizeId': return 'sizeId'; case 'orderItems': return 'items'; case 'orderItemOptions': return 'options'; default: return clientPropertyName; } } }); convention.setAsDefault(); } function fillStore(store){ // ************************************** // Todo: define metadata on client in Breeze metadata format // Right now it is in CSDL format as if generated by EntityFramework. // ************************************** store.importMetadata(getMetadata()); } function getMetadata(){ // Stringify metadata before importing (Breeze CSDL-metadata-format 'bug') return JSON.stringify({ "structuralTypes":[ { "shortName":"Address", "namespace":"Zza.Model", "isComplexType":true, "dataProperties":[ { "name":"street", "dataType":"String", "maxLength":100, "validators":[ { "maxLength":100, "name":"maxLength" } ] }, { "name":"city", "dataType":"String", "maxLength":100, "validators":[ { "maxLength":100, "name":"maxLength" } ] }, { "name":"state", "dataType":"String", "maxLength":2, "validators":[ { "maxLength":2, "name":"maxLength" } ] }, { "name":"zip", "dataType":"String", "maxLength":10, "validators":[ { "maxLength":10, "name":"maxLength" } ] } ] }, { "shortName":"Customer", "namespace":"Zza.Model", "autoGeneratedKeyType":"None", "defaultResourceName":"Customers", "dataProperties":[ { "name":"id", "dataType":"MongoObjectId", "isNullable":false, "defaultValue":"", "isPartOfKey":true, "validators":[ { "name":"required" } ] }, { "name":"firstName", "dataType":"String", "maxLength":50, "validators":[ { "maxLength":50, "name":"maxLength" } ] }, { "name":"lastName", "dataType":"String", "maxLength":50, "validators":[ { "maxLength":50, "name":"maxLength" } ] }, { "name":"phone", "dataType":"String", "maxLength":100, "validators":[ { "maxLength":100, "name":"maxLength" } ] }, { "name":"email", "dataType":"String", "maxLength":255, "validators":[ { "maxLength":255, "name":"maxLength" } ] }, { "name":"address", "complexTypeName":"Address:#Zza.Model", "isScalar":true } ], "navigationProperties":[ { "name":"orders", "entityTypeName":"Order:#Zza.Model", "isScalar":false, "associationName":"Order_Customer", "invForeignKeyNames":[ "id" ] } ] }, { "shortName":"Order", "namespace":"Zza.Model", "autoGeneratedKeyType":"Identity", "defaultResourceName":"Orders", "dataProperties":[ { "name":"id", "dataType":"MongoObjectId", "isNullable":false, "defaultValue":"", "isPartOfKey":true, "validators":[ { "name":"required" } ] }, { "name":"customerId", "dataType":"MongoObjectId", "isNullable":false, "defaultValue":"", "validators":[ { "name":"required" } ] }, { "name":"name", "dataType":"String", "isNullable":false, "maxLength":50, "validators":[ { "maxLength":50, "name":"maxLength" } ] }, { "name":"statusId", "dataType":"Int32", "isNullable":false, "defaultValue":0, "validators":[ { "name":"required" }, { "name":"int32" } ] }, { "name":"status", "dataType":"String", "isNullable":false, "maxLength":20, "validators":[ { "maxLength":20, "name":"maxLength" } ] }, { "name":"ordered", "dataType":"DateTime", "isNullable":false, "defaultValue":"1900-01-01T08:00:00Z", "validators":[ { "name":"required" }, { "name":"date" } ] }, { "name":"phone", "dataType":"String", "maxLength":100, "validators":[ { "maxLength":100, "name":"maxLength" } ] }, { "name":"delivered", "dataType":"DateTime", "isNullable":false, "defaultValue":"1900-01-01T08:00:00Z", "validators":[ { "name":"required" }, { "name":"date" } ] }, { "name":"deliveryCharge", "dataType":"Decimal", "isNullable":false, "defaultValue":0, "validators":[ { "name":"required" }, { "name":"number" } ] }, { "name":"deliveryAddress", "complexTypeName":"Address:#Zza.Model", "isScalar":true }, { "name":"itemsTotal", "dataType":"Decimal", "isNullable":false, "defaultValue":0, "validators":[ { "name":"required" }, { "name":"number" } ] }, { "name":"orderItems", "complexTypeName":"OrderItem:#Zza.Model", "isScalar":false } ], "navigationProperties":[ { "name":"customer", "entityTypeName":"Customer:#Zza.Model", "isScalar":true, "associationName":"Order_Customer", "foreignKeyNames":[ "customerId" ] }, { "name":"orderStatus", "entityTypeName":"OrderStatus:#Zza.Model", "isScalar":true, "associationName":"Order_Status", "foreignKeyNames":[ "statusId" ] } ] }, { "shortName":"OrderItem", "namespace":"Zza.Model", "isComplexType":true, "dataProperties":[ { "name":"productId", "dataType":"Int32", "isNullable":false, "defaultValue":0, "validators":[ { "name":"required" }, { "name":"int32" } ] }, { "name":"name", "dataType":"String", "isNullable":false, "maxLength":50, "validators":[ { "maxLength":50, "name":"maxLength" } ] }, { "name":"type", "dataType":"String", "isNullable":false, "maxLength":50, "validators":[ { "maxLength":10, "name":"maxLength" } ] }, { "name":"productSizeId", "dataType":"Int32", "isNullable":false, "defaultValue":0, "validators":[ { "name":"required" }, { "name":"int32" } ] }, { "name":"size", "dataType":"String", "isNullable":false, "maxLength":50, "validators":[ { "maxLength":50, "name":"maxLength" } ] }, { "name":"quantity", "dataType":"Int32", "isNullable":false, "defaultValue":0, "validators":[ { "name":"required" }, { "name":"int32" } ] }, { "name":"unitPrice", "dataType":"Decimal", "isNullable":false, "defaultValue":0, "validators":[ { "name":"required" }, { "name":"number" } ] }, { "name":"totalPrice", "dataType":"Decimal", "isNullable":false, "defaultValue":0, "validators":[ { "name":"required" }, { "name":"number" } ] }, { "name":"instructions", "dataType":"String", "maxLength":255, "validators":[ { "maxLength":255, "name":"maxLength" } ] }, { "name":"orderItemOptions", "complexTypeName":"OrderItemOption:#Zza.Model", "isScalar":false } ] }, { "shortName":"OrderItemOption", "namespace":"Zza.Model", "isComplexType":true, "dataProperties":[ { "name":"productOptionId", "dataType":"Int32", "isNullable":false, "defaultValue":0, "validators":[ { "name":"required" }, { "name":"int32" } ] }, { "name":"name", "dataType":"String", "isNullable":false, "maxLength":50, "validators":[ { "maxLength":50, "name":"maxLength" } ] }, { "name":"quantity", "dataType":"Int32", "isNullable":false, "defaultValue":0, "validators":[ { "name":"required" }, { "name":"int32" } ] }, { "name":"price", "dataType":"Decimal", "isNullable":false, "defaultValue":0, "validators":[ { "name":"required" }, { "name":"number" } ] } ] }, { "shortName":"OrderStatus", "namespace":"Zza.Model", "autoGeneratedKeyType":"None", "defaultResourceName":"OrderStatuses", "dataProperties":[ { "name":"id", "dataType":"Int32", "isNullable":false, "defaultValue":0, "isPartOfKey":true, "validators":[ { "name":"required" }, { "name":"int32" } ] }, { "name":"name", "dataType":"String", "isNullable":false, "defaultValue":"", "maxLength":50, "validators":[ { "name":"required" }, { "maxLength":50, "name":"maxLength" } ] } ] }, { "shortName":"Product", "namespace":"Zza.Model", "autoGeneratedKeyType":"None", "defaultResourceName":"Products", "dataProperties":[ { "name":"id", "dataType":"Int32", "isNullable":false, "defaultValue":0, "isPartOfKey":true, "validators":[ { "name":"required" }, { "name":"int32" } ] }, { "name":"type", "dataType":"String", "isNullable":false, "defaultValue":"", "maxLength":20, "validators":[ { "name":"required" }, { "maxLength":20, "name":"maxLength" } ] }, { "name":"name", "dataType":"String", "isNullable":false, "defaultValue":"", "maxLength":50, "validators":[ { "name":"required" }, { "maxLength":50, "name":"maxLength" } ] }, { "name":"description", "dataType":"String", "isNullable":false, "defaultValue":"", "maxLength":255, "validators":[ { "name":"required" }, { "maxLength":255, "name":"maxLength" } ] }, { "name":"image", "dataType":"String", "maxLength":50, "validators":[ { "maxLength":50, "name":"maxLength" } ] }, { "name":"hasOptions", "dataType":"Boolean", "isNullable":false, "defaultValue":false, "validators":[ { "name":"required" }, { "name":"bool" } ] }, { "name":"isPremium", "dataType":"Boolean", "isNullable":false, "defaultValue":false, "validators":[ { "name":"required" }, { "name":"bool" } ] }, { "name":"isVegetarian", "dataType":"Boolean", "validators":[ { "name":"bool" } ] }, { "name":"withTomatoSauce", "dataType":"Boolean", "validators":[ { "name":"bool" } ] }, { "name":"sizeIds", "dataType":"Int32", "isScalar":false } ] }, { "shortName":"ProductOption", "namespace":"Zza.Model", "autoGeneratedKeyType":"None", "defaultResourceName":"ProductOptions", "dataProperties":[ { "name":"id", "dataType":"Int32", "isNullable":false, "defaultValue":0, "isPartOfKey":true, "validators":[ { "name":"required" }, { "name":"int32" } ] }, { "name":"type", "dataType":"String", "isNullable":false, "defaultValue":"", "maxLength":20, "validators":[ { "name":"required" }, { "maxLength":20, "name":"maxLength" } ] }, { "name":"name", "dataType":"String", "isNullable":false, "defaultValue":"", "maxLength":50, "validators":[ { "name":"required" }, { "maxLength":50, "name":"maxLength" } ] }, { "name":"factor", "dataType":"Int32", "isNullable":false, "defaultValue":0, "validators":[ { "name":"required" }, { "name":"int32" } ] }, { "name":"productTypes", "dataType":"String", "isScalar":false } ] }, { "shortName":"ProductSize", "namespace":"Zza.Model", "autoGeneratedKeyType":"None", "defaultResourceName":"ProductSizes", "dataProperties":[ { "name":"id", "dataType":"Int32", "isNullable":false, "defaultValue":0, "isPartOfKey":true, "validators":[ { "name":"required" }, { "name":"int32" } ] }, { "name":"type", "dataType":"String", "isNullable":false, "defaultValue":"", "maxLength":20, "validators":[ { "name":"required" }, { "maxLength":20, "name":"maxLength" } ] }, { "name":"name", "dataType":"String", "isNullable":false, "defaultValue":"", "maxLength":50, "validators":[ { "name":"required" }, { "maxLength":50, "name":"maxLength" } ] }, { "name":"price", "dataType":"Decimal", "isNullable":false, "defaultValue":0, "validators":[ { "name":"required" }, { "name":"number" } ] }, { "name":"premiumPrice", "dataType":"Decimal", "validators":[ { "name":"number" } ] }, { "name":"toppingPrice", "dataType":"Decimal", "validators":[ { "name":"number" } ] }, { "name":"isGlutenFree", "dataType":"Boolean", "validators":[ { "name":"bool" } ] } ] } ], "resourceEntityTypeMap":{ "Customers" : "Customer:#Zza.Model", "Orders" : "Order:#Zza.Model", "OrderStatuses" : "OrderStatus:#Zza.Model", "Products" : "Product:#Zza.Model", "ProductSizes" : "ProductSize:#Zza.Model", "ProductOptions" : "ProductOption:#Zza.Model" } }); } } }( this.angular ));
import DRFAdapter from './drf'; export default DRFAdapter.extend({ });
import keys from './keys.js'; /** Used to compose bitmasks for value comparisons. */ var COMPARE_PARTIAL_FLAG = 1; /** Used for built-in method references. */ var objectProto = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** * A specialized version of `baseIsEqualDeep` for objects with support for * partial deep comparisons. * * @private * @param {Object} object The object to compare. * @param {Object} other The other object to compare. * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. * @param {Function} customizer The function to customize comparisons. * @param {Function} equalFunc The function to determine equivalents of values. * @param {Object} stack Tracks traversed `object` and `other` objects. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. */ function equalObjects(object, other, bitmask, customizer, equalFunc, stack) { var isPartial = bitmask & COMPARE_PARTIAL_FLAG, objProps = keys(object), objLength = objProps.length, othProps = keys(other), othLength = othProps.length; if (objLength != othLength && !isPartial) { return false; } var index = objLength; while (index--) { var key = objProps[index]; if (!(isPartial ? key in other : hasOwnProperty.call(other, key))) { return false; } } // Assume cyclic values are equal. var stacked = stack.get(object); if (stacked && stack.get(other)) { return stacked == other; } var result = true; stack.set(object, other); stack.set(other, object); var skipCtor = isPartial; while (++index < objLength) { key = objProps[index]; var objValue = object[key], othValue = other[key]; if (customizer) { var compared = isPartial ? customizer(othValue, objValue, key, other, object, stack) : customizer(objValue, othValue, key, object, other, stack); } // Recursively compare objects (susceptible to call stack limits). if (!(compared === undefined ? (objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack)) : compared )) { result = false; break; } skipCtor || (skipCtor = key == 'constructor'); } if (result && !skipCtor) { var objCtor = object.constructor, othCtor = other.constructor; // Non `Object` object instances with different constructors are not equal. if (objCtor != othCtor && ('constructor' in object && 'constructor' in other) && !(typeof objCtor == 'function' && objCtor instanceof objCtor && typeof othCtor == 'function' && othCtor instanceof othCtor)) { result = false; } } stack['delete'](object); stack['delete'](other); return result; } export default equalObjects;
$(document).ready(function(){ /* ========================================================================== Fullcalendar ========================================================================== */ $('#calendar').fullCalendar({ header: { left: '', center: 'prev, title, next', right: 'today agendaDay,agendaTwoDay,agendaWeek,month' }, buttonIcons: { prev: 'font-icon font-icon-arrow-left', next: 'font-icon font-icon-arrow-right', prevYear: 'font-icon font-icon-arrow-left', nextYear: 'font-icon font-icon-arrow-right' }, defaultDate: '2016-01-12', editable: true, selectable: true, eventLimit: true, // allow "more" link when too many events events: [ { title: 'All Day Event', start: '2016-01-01' }, { title: 'Long Event', start: '2016-01-07', end: '2016-01-10', className: 'event-green' }, { id: 999, title: 'Repeating Event', start: '2016-01-09T16:00:00', className: 'event-red' }, { id: 999, title: 'Repeating Event', start: '2016-01-16T16:00:00', className: 'event-orange' }, { title: 'Conference', start: '2016-01-11', end: '2016-01-13', className: 'event-coral' }, { title: 'Meeting', start: '2016-01-12T10:30:00', end: '2016-01-12T12:30:00', className: 'event-green' }, { title: 'Lunch', start: '2016-01-12T12:00:00' }, { title: 'Meeting', start: '2016-01-12T14:30:00', className: 'event-red' }, { title: 'Happy Hour', start: '2016-01-12T17:30:00' }, { title: 'Dinner', start: '2016-01-12T20:00:00', className: 'event-orange' }, { title: 'Birthday Party', start: '2016-01-13T07:00:00' }, { title: 'Click for Google', url: 'http://google.com/', start: '2016-01-28', className: 'event-coral' } ], viewRender: function(view, element) { // При переключении вида инициализируем нестандартный скролл if (!("ontouchstart" in document.documentElement)) { $('.fc-scroller').jScrollPane({ autoReinitialise: true, autoReinitialiseDelay: 100 }); } $('.fc-popover.click').remove(); }, eventClick: function(calEvent, jsEvent, view) { var eventEl = $(this); // Add and remove event border class if (!$(this).hasClass('event-clicked')) { $('.fc-event').removeClass('event-clicked'); $(this).addClass('event-clicked'); } // Add popover $('body').append( '<div class="fc-popover click">' + '<div class="fc-header">' + moment(calEvent.start).format('dddd • D') + '<button type="button" class="cl"><i class="font-icon-close-2"></i></button>' + '</div>' + '<div class="fc-body main-screen">' + '<p>' + moment(calEvent.start).format('dddd, D YYYY, hh:mma') + '</p>' + '<p class="color-blue-grey">Name Surname Patient<br/>Surgey ACL left knee</p>' + '<ul class="actions">' + '<li><a href="#">More details</a></li>' + '<li><a href="#" class="fc-event-action-edit">Edit event</a></li>' + '<li><a href="#" class="fc-event-action-remove">Remove</a></li>' + '</ul>' + '</div>' + '<div class="fc-body remove-confirm">' + '<p>Are you sure to remove event?</p>' + '<div class="text-center">' + '<button type="button" class="btn btn-rounded btn-sm">Yes</button>' + '<button type="button" class="btn btn-rounded btn-sm btn-default remove-popover">No</button>' + '</div>' + '</div>' + '<div class="fc-body edit-event">' + '<p>Edit event</p>' + '<div class="form-group">' + '<div class="input-group date datetimepicker">' + '<input type="text" class="form-control" />' + '<span class="input-group-addon"><i class="font-icon font-icon-calend"></i></span>' + '</div>' + '</div>' + '<div class="form-group">' + '<div class="input-group date datetimepicker-2">' + '<input type="text" class="form-control" />' + '<span class="input-group-addon"><i class="font-icon font-icon-clock"></i></span>' + '</div>' + '</div>' + '<div class="form-group">' + '<textarea class="form-control" rows="2">Name Surname Patient Surgey ACL left knee</textarea>' + '</div>' + '<div class="text-center">' + '<button type="button" class="btn btn-rounded btn-sm">Save</button>' + '<button type="button" class="btn btn-rounded btn-sm btn-default remove-popover">Cancel</button>' + '</div>' + '</div>' + '</div>' ); // Datepicker init $('.fc-popover.click .datetimepicker').datetimepicker({ widgetPositioning: { horizontal: 'right' } }); $('.fc-popover.click .datetimepicker-2').datetimepicker({ widgetPositioning: { horizontal: 'right' }, format: 'LT', debug: true }); // Position popover function posPopover(){ $('.fc-popover.click').css({ left: eventEl.offset().left + eventEl.outerWidth()/2, top: eventEl.offset().top + eventEl.outerHeight() }); } posPopover(); $('.fc-scroller, .calendar-page-content, body').scroll(function(){ posPopover(); }); $(window).resize(function(){ posPopover(); }); // Remove old popover if ($('.fc-popover.click').length > 1) { for (var i = 0; i < ($('.fc-popover.click').length - 1); i++) { $('.fc-popover.click').eq(i).remove(); } } // Close buttons $('.fc-popover.click .cl, .fc-popover.click .remove-popover').click(function(){ $('.fc-popover.click').remove(); $('.fc-event').removeClass('event-clicked'); }); // Actions link $('.fc-event-action-edit').click(function(e){ e.preventDefault(); $('.fc-popover.click .main-screen').hide(); $('.fc-popover.click .edit-event').show(); }); $('.fc-event-action-remove').click(function(e){ e.preventDefault(); $('.fc-popover.click .main-screen').hide(); $('.fc-popover.click .remove-confirm').show(); }); } }); /* ========================================================================== Side datepicker ========================================================================== */ $('#side-datetimepicker').datetimepicker({ inline: true, format: 'DD/MM/YYYY' }); /* ========================================================================== */ }); /* ========================================================================== Calendar page grid ========================================================================== */ (function($, viewport){ $(document).ready(function() { if(viewport.is('>=lg')) { $('.calendar-page-content, .calendar-page-side').matchHeight(); } // Execute code each time window size changes $(window).resize( viewport.changed(function() { if(viewport.is('<lg')) { $('.calendar-page-content, .calendar-page-side').matchHeight({ remove: true }); } }) ); }); })(jQuery, ResponsiveBootstrapToolkit);
// Turkish $.extend( $.fn.pickadate.defaults, { monthsFull: [ 'Ocak', 'Şubat', 'Mart', 'Nisan', 'Mayıs', 'Haziran', 'Temmuz', 'Ağustos', 'Eylül', 'Ekim', 'Kasım', 'Aralık' ], monthsShort: [ 'Oca', 'Şub', 'Mar', 'Nis', 'May', 'Haz', 'Tem', 'Ağu', 'Eyl', 'Eki', 'Kas', 'Ara' ], weekdaysFull: [ 'Pazar', 'Pazartesi', 'Salı', 'Çarşamba', 'Perşembe', 'Cuma', 'Cumartesi' ], weekdaysShort: [ 'Pzr', 'Pzt', 'Sal', 'Çrş', 'Prş', 'Cum', 'Cmt' ], today: 'bugün', clear: 'sil', firstDay: 1, format: 'dd mmmm yyyy dddd', formatSubmit: 'yyyy/mm/dd' })
'use strict'; module.exports = { 'serverport': 3000, 'scripts': { 'src': './app/js/**/*.js', 'dest': './build/js/' }, 'images': { 'src': './app/images/**/*.{jpeg,jpg,png}', 'dest': './build/images/' }, 'styles': { 'src': './app/styles/**/*.scss', 'dest': './build/css/' }, 'sourceDir': './app/', 'buildDir': './build/' };
/**! Qoopido.demand 4.2.7-alpha.11 | https://github.com/dlueth/qoopido.demand | (c) 2018 Dirk Lueth */ !function(){"use strict";provide(["/demand/abstract/handler"],function(n){var t=/^application\/json/;function e(){}return e.prototype={validate:function(n){return t.test(n)},onPreRequest:function(n){var t=n.url.pathname;n.url.pathname=".json"!==t.slice(-".json".length)?t+".json":t},process:function(n){var t=JSON.parse(n.source);provide(function(){return t})}},new(e.extends(n))})}(); //# sourceMappingURL=json.js.map
hljs.registerLanguage("brainfuck",function(e){var r={cN:"literal",b:"[\\+\\-]",relevance:0};return{aliases:["bf"],c:[e.C("[^\\[\\]\\.,\\+\\-<> \r\n]","[\\[\\]\\.,\\+\\-<> \r\n]",{rE:!0,relevance:0}),{cN:"title",b:"[\\[\\]]",relevance:0},{cN:"string",b:"[\\.,]",relevance:0},{b:/(?:\+\+|\-\-)/,c:[r]},r]}});
/*global describe, it, before, after */ // # Frontend Route tests // As it stands, these tests depend on the database, and as such are integration tests. // Mocking out the models to not touch the DB would turn these into unit tests, and should probably be done in future, // But then again testing real code, rather than mock code, might be more useful... var request = require('supertest'), should = require('should'), testUtils = require('../../utils'), ghost = require('../../../../core'); describe('Admin Routing', function () { function doEnd(done) { return function (err, res) { if (err) { return done(err); } should.not.exist(res.headers['x-cache-invalidate']); should.exist(res.headers.date); done(); }; } function doEndNoAuth(done) { return function (err, res) { if (err) { return done(err); } should.not.exist(res.headers['x-cache-invalidate']); should.exist(res.headers.date); done(); }; } before(function (done) { ghost().then(function (ghostServer) { // Setup the request object with the ghost express app request = request(ghostServer.rootApp); done(); }).catch(function (e) { console.log('Ghost Error: ', e); console.log(e.stack); }); }); after(function (done) { testUtils.clearData().then(function () { done(); }).catch(done); }); describe('Legacy Redirects', function () { it('should redirect /logout/ to /ghost/signout/', function (done) { request.get('/logout/') .expect('Location', '/ghost/signout/') .expect('Cache-Control', testUtils.cacheRules.year) .expect(301) .end(doEndNoAuth(done)); }); it('should redirect /signout/ to /ghost/signout/', function (done) { request.get('/signout/') .expect('Location', '/ghost/signout/') .expect('Cache-Control', testUtils.cacheRules.year) .expect(301) .end(doEndNoAuth(done)); }); it('should redirect /signup/ to /ghost/signup/', function (done) { request.get('/signup/') .expect('Location', '/ghost/signup/') .expect('Cache-Control', testUtils.cacheRules.year) .expect(301) .end(doEndNoAuth(done)); }); // Admin aliases it('should redirect /signin/ to /ghost/', function (done) { request.get('/signin/') .expect('Location', '/ghost/') .expect('Cache-Control', testUtils.cacheRules.public) .expect(302) .end(doEndNoAuth(done)); }); it('should redirect /admin/ to /ghost/', function (done) { request.get('/admin/') .expect('Location', '/ghost/') .expect('Cache-Control', testUtils.cacheRules.public) .expect(302) .end(doEndNoAuth(done)); }); it('should redirect /GHOST/ to /ghost/', function (done) { request.get('/GHOST/') .expect('Location', '/ghost/') .expect(301) .end(doEndNoAuth(done)); }); }); // we'll use X-Forwarded-Proto: https to simulate an 'https://' request behind a proxy describe('Require HTTPS - no redirect', function () { var forkedGhost, request; before(function (done) { var configTestHttps = testUtils.fork.config(); configTestHttps.forceAdminSSL = {redirect: false}; configTestHttps.urlSSL = 'https://localhost/'; testUtils.fork.ghost(configTestHttps, 'testhttps') .then(function (child) { forkedGhost = child; request = require('supertest'); request = request(configTestHttps.url.replace(/\/$/, '')); }).then(done) .catch(done); }); after(function (done) { if (forkedGhost) { forkedGhost.kill(done); } }); it('should block admin access over non-HTTPS', function (done) { request.get('/ghost/') .expect(403) .end(done); }); it('should allow admin access over HTTPS', function (done) { request.get('/ghost/setup/') .set('X-Forwarded-Proto', 'https') .expect(200) .end(doEnd(done)); }); }); describe('Require HTTPS - redirect', function () { var forkedGhost, request; before(function (done) { var configTestHttps = testUtils.fork.config(); configTestHttps.forceAdminSSL = {redirect: true}; configTestHttps.urlSSL = 'https://localhost/'; testUtils.fork.ghost(configTestHttps, 'testhttps') .then(function (child) { forkedGhost = child; request = require('supertest'); request = request(configTestHttps.url.replace(/\/$/, '')); }).then(done) .catch(done); }); after(function (done) { if (forkedGhost) { forkedGhost.kill(done); } }); it('should redirect admin access over non-HTTPS', function (done) { request.get('/ghost/') .expect('Location', /^https:\/\/localhost\/ghost\//) .expect(301) .end(done); }); it('should allow admin access over HTTPS', function (done) { request.get('/ghost/setup/') .set('X-Forwarded-Proto', 'https') .expect(200) .end(done); }); }); describe('Ghost Admin Setup', function () { it('should redirect from /ghost/ to /ghost/setup/ when no user/not installed yet', function (done) { request.get('/ghost/') .expect('Location', /ghost\/setup/) .expect('Cache-Control', testUtils.cacheRules['private']) .expect(302) .end(doEnd(done)); }); it('should redirect from /ghost/signin/ to /ghost/setup/ when no user', function (done) { request.get('/ghost/signin/') .expect('Location', /ghost\/setup/) .expect('Cache-Control', testUtils.cacheRules['private']) .expect(302) .end(doEnd(done)); }); it('should respond with html for /ghost/setup/', function (done) { request.get('/ghost/setup/') .expect('Content-Type', /html/) .expect('Cache-Control', testUtils.cacheRules['private']) .expect(200) .end(doEnd(done)); }); // Add user // it('should redirect from /ghost/signup to /ghost/signin with user', function (done) { // done(); // }); // it('should respond with html for /ghost/signin', function (done) { // done(); // }); // Do Login // it('should redirect from /ghost/signup to /ghost/ when logged in', function (done) { // done(); // }); // it('should redirect from /ghost/signup to /ghost/ when logged in', function (done) { // done(); // }); }); // // describe('Ghost Admin Forgot Password', function () { // before(function (done) { // // Create a user / do setup etc // testUtils.clearData() // .then(function () { // return testUtils.initData(); // }) // .then(function () { // return testUtils.insertDefaultFixtures(); // }).then(function () { // done(); // }) // .catch(done); // }); // // it('should respond with html for /ghost/forgotten/', function (done) { // request.get('/ghost/forgotten/') // .expect('Content-Type', /html/) // .expect('Cache-Control', testUtils.cacheRules['private']) // .expect(200) // .end(doEnd(done)); // }); // // it('should respond 404 for /ghost/reset/', function (done) { // request.get('/ghost/reset/') // .expect('Cache-Control', testUtils.cacheRules['private']) // .expect(404) // .expect(/Page Not Found/) // .end(doEnd(done)); // }); // // it('should redirect /ghost/reset/*/', function (done) { // request.get('/ghost/reset/athing/') // .expect('Location', /ghost\/forgotten/) // .expect('Cache-Control', testUtils.cacheRules['private']) // .expect(302) // .end(doEnd(done)); // }); // }); // }); // TODO: not working anymore, needs new test for Ember // describe('Authenticated Admin Routing', function () { // var user = testUtils.DataGenerator.forModel.users[0]; // before(function (done) { // var app = express(); // ghost({app: app}).then(function (_ghostServer) { // ghostServer = _ghostServer; // request = agent(app); // testUtils.clearData() // .then(function () { // return testUtils.initData(); // }) // .then(function () { // return testUtils.insertDefaultFixtures(); // }) // .then(function () { // request.get('/ghost/signin/') // .expect(200) // .end(function (err, res) { // if (err) { // return done(err); // } // process.nextTick(function () { // request.post('/ghost/signin/') // .send({email: user.email, password: user.password}) // .expect(200) // .end(function (err, res) { // if (err) { // return done(err); // } // request.saveCookies(res); // request.get('/ghost/') // .expect(200) // .end(function (err, res) { // if (err) { // return done(err); // } // done(); // }); // }); // }); // }); // }).catch(done); // }).catch(function (e) { // console.log('Ghost Error: ', e); // console.log(e.stack); // }); // }); // after(function () { // ghostServer.stop(); // }); // describe('Ghost Admin magic /view/ route', function () { // it('should redirect to the single post page on the frontend', function (done) { // request.get('/ghost/editor/1/view/') // .expect(302) // .expect('Location', '/welcome-to-ghost/') // .end(function (err, res) { // if (err) { // return done(err); // } // done(); // }); // }); // }); });
import getTag from './_getTag.js'; import isObjectLike from './isObjectLike.js'; /** `Object#toString` result references. */ var mapTag = '[object Map]'; /** * Checks if `value` is classified as a `Map` object. * * @static * @memberOf _ * @since 4.3.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is correctly classified, * else `false`. * @example * * _.isMap(new Map); * // => true * * _.isMap(new WeakMap); * // => false */ function isMap(value) { return isObjectLike(value) && getTag(value) == mapTag; } export default isMap;
/***@@@ BEGIN LICENSE @@@***/ /*───────────────────────────────────────────────────────────────────────────*\ │ Copyright (C) 2013 eBay Software Foundation │ │ │ │hh ,'""`. │ │ / _ _ \ 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. │ \*───────────────────────────────────────────────────────────────────────────*/ /***@@@ END LICENSE @@@***/ /*global exports:true*/ exports = module.exports = require('./lib/transcoder'); /*global exports:false*/
window.onload = function () { editor.setOpt({ emotionLocalization:false }); emotion.SmileyPath = editor.options.emotionLocalization === true ? 'images/' : "http://img.baidu.com/hi/"; emotion.SmileyBox = createTabList( emotion.tabNum ); emotion.tabExist = createArr( emotion.tabNum ); initImgName(); initEvtHandler( "tabHeads" ); }; function initImgName() { for ( var pro in emotion.SmilmgName ) { var tempName = emotion.SmilmgName[pro], tempBox = emotion.SmileyBox[pro], tempStr = ""; if ( tempBox.length ) return; for ( var i = 1; i <= tempName[1]; i++ ) { tempStr = tempName[0]; if ( i < 10 ) tempStr = tempStr + '0'; tempStr = tempStr + i + '.gif'; tempBox.push( tempStr ); } } } function initEvtHandler( conId ) { var tabHeads = $G( conId ); for ( var i = 0, j = 0; i < tabHeads.childNodes.length; i++ ) { var tabObj = tabHeads.childNodes[i]; if ( tabObj.nodeType == 1 ) { domUtils.on( tabObj, "click", (function ( index ) { return function () { switchTab( index ); }; })( j ) ); j++; } } switchTab( 0 ); $G( "tabIconReview" ).style.display = 'none'; } function InsertSmiley( url, evt ) { var obj = { src:editor.options.emotionLocalization ? editor.options.UEDITOR_HOME_URL + "dialogs/emotion/" + url : url }; obj.data_ue_src = obj.src; editor.execCommand( 'insertimage', obj ); if ( !evt.ctrlKey ) { dialog.popup.hide(); } } function switchTab( index ) { autoHeight( index ); if ( emotion.tabExist[index] == 0 ) { emotion.tabExist[index] = 1; createTab( 'tab' + index ); } //获取呈现元素句柄数组 var tabHeads = $G( "tabHeads" ).getElementsByTagName( "span" ), tabBodys = $G( "tabBodys" ).getElementsByTagName( "div" ), i = 0, L = tabHeads.length; //隐藏所有呈现元素 for ( ; i < L; i++ ) { tabHeads[i].className = ""; tabBodys[i].style.display = "none"; } //显示对应呈现元素 tabHeads[index].className = "focus"; tabBodys[index].style.display = "block"; } function autoHeight( index ) { var iframe = dialog.getDom( "iframe" ), parent = iframe.parentNode.parentNode; switch ( index ) { case 0: iframe.style.height = "380px"; parent.style.height = "392px"; break; case 1: iframe.style.height = "220px"; parent.style.height = "232px"; break; case 2: iframe.style.height = "260px"; parent.style.height = "272px"; break; case 3: iframe.style.height = "300px"; parent.style.height = "312px"; break; case 4: iframe.style.height = "140px"; parent.style.height = "152px"; break; case 5: iframe.style.height = "260px"; parent.style.height = "272px"; break; case 6: iframe.style.height = "230px"; parent.style.height = "242px"; break; default: } } function createTab( tabName ) { var faceVersion = "?v=1.1", //版本号 tab = $G( tabName ), //获取将要生成的Div句柄 imagePath = emotion.SmileyPath + emotion.imageFolders[tabName], //获取显示表情和预览表情的路径 positionLine = 11 / 2, //中间数 iWidth = iHeight = 35, //图片长宽 iColWidth = 3, //表格剩余空间的显示比例 tableCss = emotion.imageCss[tabName], cssOffset = emotion.imageCssOffset[tabName], textHTML = ['<table class="smileytable">'], i = 0, imgNum = emotion.SmileyBox[tabName].length, imgColNum = 11, faceImage, sUrl, realUrl, posflag, offset, infor; for ( ; i < imgNum; ) { textHTML.push( '<tr>' ); for ( var j = 0; j < imgColNum; j++, i++ ) { faceImage = emotion.SmileyBox[tabName][i]; if ( faceImage ) { sUrl = imagePath + faceImage + faceVersion; realUrl = imagePath + faceImage; posflag = j < positionLine ? 0 : 1; offset = cssOffset * i * (-1) - 1; infor = emotion.SmileyInfor[tabName][i]; textHTML.push( '<td class="' + tableCss + '" border="1" width="' + iColWidth + '%" style="border-collapse:collapse;" align="center" bgcolor="transparent" onclick="InsertSmiley(\'' + realUrl.replace( /'/g, "\\'" ) + '\',event)" onmouseover="over(this,\'' + sUrl + '\',\'' + posflag + '\')" onmouseout="out(this)">' ); textHTML.push( '<span>' ); textHTML.push( '<img style="background-position:left ' + offset + 'px;" title="' + infor + '" src="' + emotion.SmileyPath + (editor.options.emotionLocalization ? '0.gif" width="' : 'default/0.gif" width="') + iWidth + '" height="' + iHeight + '"></img>' ); textHTML.push( '</span>' ); } else { textHTML.push( '<td width="' + iColWidth + '%" bgcolor="#FFFFFF">' ); } textHTML.push( '</td>' ); } textHTML.push( '</tr>' ); } textHTML.push( '</table>' ); textHTML = textHTML.join( "" ); tab.innerHTML = textHTML; } function over( td, srcPath, posFlag ) { td.style.backgroundColor = "#ACCD3C"; $G( 'faceReview' ).style.backgroundImage = "url(" + srcPath + ")"; if ( posFlag == 1 ) $G( "tabIconReview" ).className = "show"; $G( "tabIconReview" ).style.display = 'block'; } function out( td ) { td.style.backgroundColor = "transparent"; var tabIconRevew = $G( "tabIconReview" ); tabIconRevew.className = ""; tabIconRevew.style.display = 'none'; } function createTabList( tabNum ) { var obj = {}; for ( var i = 0; i < tabNum; i++ ) { obj["tab" + i] = []; } return obj; } function createArr( tabNum ) { var arr = []; for ( var i = 0; i < tabNum; i++ ) { arr[i] = 0; } return arr; }
// Fine Uploader 5.15.1 - MIT licensed. http://fineuploader.com (function(global) { (function($) { "use strict"; var $el, pluginOptions = [ "uploaderType", "endpointType" ]; function init(options) { var xformedOpts = transformVariables(options || {}), newUploaderInstance = getNewUploaderInstance(xformedOpts); uploader(newUploaderInstance); addCallbacks(xformedOpts, newUploaderInstance); return $el; } function getNewUploaderInstance(params) { var uploaderType = pluginOption("uploaderType"), namespace = pluginOption("endpointType"); if (uploaderType) { uploaderType = uploaderType.charAt(0).toUpperCase() + uploaderType.slice(1).toLowerCase(); if (namespace) { return new qq[namespace]["FineUploader" + uploaderType](params); } return new qq["FineUploader" + uploaderType](params); } else { if (namespace) { return new qq[namespace].FineUploader(params); } return new qq.FineUploader(params); } } function dataStore(key, val) { var data = $el.data("fineuploader"); if (val) { if (data === undefined) { data = {}; } data[key] = val; $el.data("fineuploader", data); } else { if (data === undefined) { return null; } return data[key]; } } function uploader(instanceToStore) { return dataStore("uploader", instanceToStore); } function pluginOption(option, optionVal) { return dataStore(option, optionVal); } function addCallbacks(transformedOpts, newUploaderInstance) { var callbacks = transformedOpts.callbacks = {}; $.each(newUploaderInstance._options.callbacks, function(prop, nonJqueryCallback) { var name, callbackEventTarget; name = /^on(\w+)/.exec(prop)[1]; name = name.substring(0, 1).toLowerCase() + name.substring(1); callbackEventTarget = $el; callbacks[prop] = function() { var originalArgs = Array.prototype.slice.call(arguments), transformedArgs = [], nonJqueryCallbackRetVal, jqueryEventCallbackRetVal; $.each(originalArgs, function(idx, arg) { transformedArgs.push(maybeWrapInJquery(arg)); }); nonJqueryCallbackRetVal = nonJqueryCallback.apply(this, originalArgs); try { jqueryEventCallbackRetVal = callbackEventTarget.triggerHandler(name, transformedArgs); } catch (error) { qq.log("Caught error in Fine Uploader jQuery event handler: " + error.message, "error"); } if (nonJqueryCallbackRetVal != null) { return nonJqueryCallbackRetVal; } return jqueryEventCallbackRetVal; }; }); newUploaderInstance._options.callbacks = callbacks; } function transformVariables(source, dest) { var xformed, arrayVals; if (dest === undefined) { if (source.uploaderType !== "basic") { xformed = { element: $el[0] }; } else { xformed = {}; } } else { xformed = dest; } $.each(source, function(prop, val) { if ($.inArray(prop, pluginOptions) >= 0) { pluginOption(prop, val); } else if (val instanceof $) { xformed[prop] = val[0]; } else if ($.isPlainObject(val)) { xformed[prop] = {}; transformVariables(val, xformed[prop]); } else if ($.isArray(val)) { arrayVals = []; $.each(val, function(idx, arrayVal) { var arrayObjDest = {}; if (arrayVal instanceof $) { $.merge(arrayVals, arrayVal); } else if ($.isPlainObject(arrayVal)) { transformVariables(arrayVal, arrayObjDest); arrayVals.push(arrayObjDest); } else { arrayVals.push(arrayVal); } }); xformed[prop] = arrayVals; } else { xformed[prop] = val; } }); if (dest === undefined) { return xformed; } } function isValidCommand(command) { return $.type(command) === "string" && !command.match(/^_/) && uploader()[command] !== undefined; } function delegateCommand(command) { var xformedArgs = [], origArgs = Array.prototype.slice.call(arguments, 1), retVal; transformVariables(origArgs, xformedArgs); retVal = uploader()[command].apply(uploader(), xformedArgs); return maybeWrapInJquery(retVal); } function maybeWrapInJquery(val) { var transformedVal = val; if (val != null && typeof val === "object" && (val.nodeType === 1 || val.nodeType === 9) && val.cloneNode) { transformedVal = $(val); } return transformedVal; } $.fn.fineUploader = function(optionsOrCommand) { var self = this, selfArgs = arguments, retVals = []; this.each(function(index, el) { $el = $(el); if (uploader() && isValidCommand(optionsOrCommand)) { retVals.push(delegateCommand.apply(self, selfArgs)); if (self.length === 1) { return false; } } else if (typeof optionsOrCommand === "object" || !optionsOrCommand) { init.apply(self, selfArgs); } else { $.error("Method " + optionsOrCommand + " does not exist on jQuery.fineUploader"); } }); if (retVals.length === 1) { return retVals[0]; } else if (retVals.length > 1) { return retVals; } return this; }; })(jQuery); (function($) { "use strict"; var rootDataKey = "fineUploaderDnd", $el; function init(options) { if (!options) { options = {}; } options.dropZoneElements = [ $el ]; var xformedOpts = transformVariables(options); addCallbacks(xformedOpts); dnd(new qq.DragAndDrop(xformedOpts)); return $el; } function dataStore(key, val) { var data = $el.data(rootDataKey); if (val) { if (data === undefined) { data = {}; } data[key] = val; $el.data(rootDataKey, data); } else { if (data === undefined) { return null; } return data[key]; } } function dnd(instanceToStore) { return dataStore("dndInstance", instanceToStore); } function addCallbacks(transformedOpts) { var callbacks = transformedOpts.callbacks = {}; $.each(new qq.DragAndDrop.callbacks(), function(prop, func) { var name = prop, $callbackEl; $callbackEl = $el; callbacks[prop] = function() { var args = Array.prototype.slice.call(arguments), jqueryHandlerResult = $callbackEl.triggerHandler(name, args); return jqueryHandlerResult; }; }); } function transformVariables(source, dest) { var xformed, arrayVals; if (dest === undefined) { xformed = {}; } else { xformed = dest; } $.each(source, function(prop, val) { if (val instanceof $) { xformed[prop] = val[0]; } else if ($.isPlainObject(val)) { xformed[prop] = {}; transformVariables(val, xformed[prop]); } else if ($.isArray(val)) { arrayVals = []; $.each(val, function(idx, arrayVal) { if (arrayVal instanceof $) { $.merge(arrayVals, arrayVal); } else { arrayVals.push(arrayVal); } }); xformed[prop] = arrayVals; } else { xformed[prop] = val; } }); if (dest === undefined) { return xformed; } } function isValidCommand(command) { return $.type(command) === "string" && command === "dispose" && dnd()[command] !== undefined; } function delegateCommand(command) { var xformedArgs = [], origArgs = Array.prototype.slice.call(arguments, 1); transformVariables(origArgs, xformedArgs); return dnd()[command].apply(dnd(), xformedArgs); } $.fn.fineUploaderDnd = function(optionsOrCommand) { var self = this, selfArgs = arguments, retVals = []; this.each(function(index, el) { $el = $(el); if (dnd() && isValidCommand(optionsOrCommand)) { retVals.push(delegateCommand.apply(self, selfArgs)); if (self.length === 1) { return false; } } else if (typeof optionsOrCommand === "object" || !optionsOrCommand) { init.apply(self, selfArgs); } else { $.error("Method " + optionsOrCommand + " does not exist in Fine Uploader's DnD module."); } }); if (retVals.length === 1) { return retVals[0]; } else if (retVals.length > 1) { return retVals; } return this; }; })(jQuery); (function($) { "use strict"; $.fn.fineUploaderAzure = function(optionsOrCommand) { if (typeof optionsOrCommand === "object") { optionsOrCommand.endpointType = "azure"; } return $.fn.fineUploader.apply(this, arguments); }; })(jQuery); var qq = function(element) { "use strict"; return { hide: function() { element.style.display = "none"; return this; }, attach: function(type, fn) { if (element.addEventListener) { element.addEventListener(type, fn, false); } else if (element.attachEvent) { element.attachEvent("on" + type, fn); } return function() { qq(element).detach(type, fn); }; }, detach: function(type, fn) { if (element.removeEventListener) { element.removeEventListener(type, fn, false); } else if (element.attachEvent) { element.detachEvent("on" + type, fn); } return this; }, contains: function(descendant) { if (!descendant) { return false; } if (element === descendant) { return true; } if (element.contains) { return element.contains(descendant); } else { return !!(descendant.compareDocumentPosition(element) & 8); } }, insertBefore: function(elementB) { elementB.parentNode.insertBefore(element, elementB); return this; }, remove: function() { element.parentNode.removeChild(element); return this; }, css: function(styles) { if (element.style == null) { throw new qq.Error("Can't apply style to node as it is not on the HTMLElement prototype chain!"); } if (styles.opacity != null) { if (typeof element.style.opacity !== "string" && typeof element.filters !== "undefined") { styles.filter = "alpha(opacity=" + Math.round(100 * styles.opacity) + ")"; } } qq.extend(element.style, styles); return this; }, hasClass: function(name, considerParent) { var re = new RegExp("(^| )" + name + "( |$)"); return re.test(element.className) || !!(considerParent && re.test(element.parentNode.className)); }, addClass: function(name) { if (!qq(element).hasClass(name)) { element.className += " " + name; } return this; }, removeClass: function(name) { var re = new RegExp("(^| )" + name + "( |$)"); element.className = element.className.replace(re, " ").replace(/^\s+|\s+$/g, ""); return this; }, getByClass: function(className, first) { var candidates, result = []; if (first && element.querySelector) { return element.querySelector("." + className); } else if (element.querySelectorAll) { return element.querySelectorAll("." + className); } candidates = element.getElementsByTagName("*"); qq.each(candidates, function(idx, val) { if (qq(val).hasClass(className)) { result.push(val); } }); return first ? result[0] : result; }, getFirstByClass: function(className) { return qq(element).getByClass(className, true); }, children: function() { var children = [], child = element.firstChild; while (child) { if (child.nodeType === 1) { children.push(child); } child = child.nextSibling; } return children; }, setText: function(text) { element.innerText = text; element.textContent = text; return this; }, clearText: function() { return qq(element).setText(""); }, hasAttribute: function(attrName) { var attrVal; if (element.hasAttribute) { if (!element.hasAttribute(attrName)) { return false; } return /^false$/i.exec(element.getAttribute(attrName)) == null; } else { attrVal = element[attrName]; if (attrVal === undefined) { return false; } return /^false$/i.exec(attrVal) == null; } } }; }; (function() { "use strict"; qq.canvasToBlob = function(canvas, mime, quality) { return qq.dataUriToBlob(canvas.toDataURL(mime, quality)); }; qq.dataUriToBlob = function(dataUri) { var arrayBuffer, byteString, createBlob = function(data, mime) { var BlobBuilder = window.BlobBuilder || window.WebKitBlobBuilder || window.MozBlobBuilder || window.MSBlobBuilder, blobBuilder = BlobBuilder && new BlobBuilder(); if (blobBuilder) { blobBuilder.append(data); return blobBuilder.getBlob(mime); } else { return new Blob([ data ], { type: mime }); } }, intArray, mimeString; if (dataUri.split(",")[0].indexOf("base64") >= 0) { byteString = atob(dataUri.split(",")[1]); } else { byteString = decodeURI(dataUri.split(",")[1]); } mimeString = dataUri.split(",")[0].split(":")[1].split(";")[0]; arrayBuffer = new ArrayBuffer(byteString.length); intArray = new Uint8Array(arrayBuffer); qq.each(byteString, function(idx, character) { intArray[idx] = character.charCodeAt(0); }); return createBlob(arrayBuffer, mimeString); }; qq.log = function(message, level) { if (window.console) { if (!level || level === "info") { window.console.log(message); } else { if (window.console[level]) { window.console[level](message); } else { window.console.log("<" + level + "> " + message); } } } }; qq.isObject = function(variable) { return variable && !variable.nodeType && Object.prototype.toString.call(variable) === "[object Object]"; }; qq.isFunction = function(variable) { return typeof variable === "function"; }; qq.isArray = function(value) { return Object.prototype.toString.call(value) === "[object Array]" || value && window.ArrayBuffer && value.buffer && value.buffer.constructor === ArrayBuffer; }; qq.isItemList = function(maybeItemList) { return Object.prototype.toString.call(maybeItemList) === "[object DataTransferItemList]"; }; qq.isNodeList = function(maybeNodeList) { return Object.prototype.toString.call(maybeNodeList) === "[object NodeList]" || maybeNodeList.item && maybeNodeList.namedItem; }; qq.isString = function(maybeString) { return Object.prototype.toString.call(maybeString) === "[object String]"; }; qq.trimStr = function(string) { if (String.prototype.trim) { return string.trim(); } return string.replace(/^\s+|\s+$/g, ""); }; qq.format = function(str) { var args = Array.prototype.slice.call(arguments, 1), newStr = str, nextIdxToReplace = newStr.indexOf("{}"); qq.each(args, function(idx, val) { var strBefore = newStr.substring(0, nextIdxToReplace), strAfter = newStr.substring(nextIdxToReplace + 2); newStr = strBefore + val + strAfter; nextIdxToReplace = newStr.indexOf("{}", nextIdxToReplace + val.length); if (nextIdxToReplace < 0) { return false; } }); return newStr; }; qq.isFile = function(maybeFile) { return window.File && Object.prototype.toString.call(maybeFile) === "[object File]"; }; qq.isFileList = function(maybeFileList) { return window.FileList && Object.prototype.toString.call(maybeFileList) === "[object FileList]"; }; qq.isFileOrInput = function(maybeFileOrInput) { return qq.isFile(maybeFileOrInput) || qq.isInput(maybeFileOrInput); }; qq.isInput = function(maybeInput, notFile) { var evaluateType = function(type) { var normalizedType = type.toLowerCase(); if (notFile) { return normalizedType !== "file"; } return normalizedType === "file"; }; if (window.HTMLInputElement) { if (Object.prototype.toString.call(maybeInput) === "[object HTMLInputElement]") { if (maybeInput.type && evaluateType(maybeInput.type)) { return true; } } } if (maybeInput.tagName) { if (maybeInput.tagName.toLowerCase() === "input") { if (maybeInput.type && evaluateType(maybeInput.type)) { return true; } } } return false; }; qq.isBlob = function(maybeBlob) { if (window.Blob && Object.prototype.toString.call(maybeBlob) === "[object Blob]") { return true; } }; qq.isXhrUploadSupported = function() { var input = document.createElement("input"); input.type = "file"; return input.multiple !== undefined && typeof File !== "undefined" && typeof FormData !== "undefined" && typeof qq.createXhrInstance().upload !== "undefined"; }; qq.createXhrInstance = function() { if (window.XMLHttpRequest) { return new XMLHttpRequest(); } try { return new ActiveXObject("MSXML2.XMLHTTP.3.0"); } catch (error) { qq.log("Neither XHR or ActiveX are supported!", "error"); return null; } }; qq.isFolderDropSupported = function(dataTransfer) { return dataTransfer.items && dataTransfer.items.length > 0 && dataTransfer.items[0].webkitGetAsEntry; }; qq.isFileChunkingSupported = function() { return !qq.androidStock() && qq.isXhrUploadSupported() && (File.prototype.slice !== undefined || File.prototype.webkitSlice !== undefined || File.prototype.mozSlice !== undefined); }; qq.sliceBlob = function(fileOrBlob, start, end) { var slicer = fileOrBlob.slice || fileOrBlob.mozSlice || fileOrBlob.webkitSlice; return slicer.call(fileOrBlob, start, end); }; qq.arrayBufferToHex = function(buffer) { var bytesAsHex = "", bytes = new Uint8Array(buffer); qq.each(bytes, function(idx, byt) { var byteAsHexStr = byt.toString(16); if (byteAsHexStr.length < 2) { byteAsHexStr = "0" + byteAsHexStr; } bytesAsHex += byteAsHexStr; }); return bytesAsHex; }; qq.readBlobToHex = function(blob, startOffset, length) { var initialBlob = qq.sliceBlob(blob, startOffset, startOffset + length), fileReader = new FileReader(), promise = new qq.Promise(); fileReader.onload = function() { promise.success(qq.arrayBufferToHex(fileReader.result)); }; fileReader.onerror = promise.failure; fileReader.readAsArrayBuffer(initialBlob); return promise; }; qq.extend = function(first, second, extendNested) { qq.each(second, function(prop, val) { if (extendNested && qq.isObject(val)) { if (first[prop] === undefined) { first[prop] = {}; } qq.extend(first[prop], val, true); } else { first[prop] = val; } }); return first; }; qq.override = function(target, sourceFn) { var super_ = {}, source = sourceFn(super_); qq.each(source, function(srcPropName, srcPropVal) { if (target[srcPropName] !== undefined) { super_[srcPropName] = target[srcPropName]; } target[srcPropName] = srcPropVal; }); return target; }; qq.indexOf = function(arr, elt, from) { if (arr.indexOf) { return arr.indexOf(elt, from); } from = from || 0; var len = arr.length; if (from < 0) { from += len; } for (;from < len; from += 1) { if (arr.hasOwnProperty(from) && arr[from] === elt) { return from; } } return -1; }; qq.getUniqueId = function() { return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function(c) { var r = Math.random() * 16 | 0, v = c == "x" ? r : r & 3 | 8; return v.toString(16); }); }; qq.ie = function() { return navigator.userAgent.indexOf("MSIE") !== -1 || navigator.userAgent.indexOf("Trident") !== -1; }; qq.ie7 = function() { return navigator.userAgent.indexOf("MSIE 7") !== -1; }; qq.ie8 = function() { return navigator.userAgent.indexOf("MSIE 8") !== -1; }; qq.ie10 = function() { return navigator.userAgent.indexOf("MSIE 10") !== -1; }; qq.ie11 = function() { return qq.ie() && navigator.userAgent.indexOf("rv:11") !== -1; }; qq.edge = function() { return navigator.userAgent.indexOf("Edge") >= 0; }; qq.safari = function() { return navigator.vendor !== undefined && navigator.vendor.indexOf("Apple") !== -1; }; qq.chrome = function() { return navigator.vendor !== undefined && navigator.vendor.indexOf("Google") !== -1; }; qq.opera = function() { return navigator.vendor !== undefined && navigator.vendor.indexOf("Opera") !== -1; }; qq.firefox = function() { return !qq.edge() && !qq.ie11() && navigator.userAgent.indexOf("Mozilla") !== -1 && navigator.vendor !== undefined && navigator.vendor === ""; }; qq.windows = function() { return navigator.platform === "Win32"; }; qq.android = function() { return navigator.userAgent.toLowerCase().indexOf("android") !== -1; }; qq.androidStock = function() { return qq.android() && navigator.userAgent.toLowerCase().indexOf("chrome") < 0; }; qq.ios6 = function() { return qq.ios() && navigator.userAgent.indexOf(" OS 6_") !== -1; }; qq.ios7 = function() { return qq.ios() && navigator.userAgent.indexOf(" OS 7_") !== -1; }; qq.ios8 = function() { return qq.ios() && navigator.userAgent.indexOf(" OS 8_") !== -1; }; qq.ios800 = function() { return qq.ios() && navigator.userAgent.indexOf(" OS 8_0 ") !== -1; }; qq.ios = function() { return navigator.userAgent.indexOf("iPad") !== -1 || navigator.userAgent.indexOf("iPod") !== -1 || navigator.userAgent.indexOf("iPhone") !== -1; }; qq.iosChrome = function() { return qq.ios() && navigator.userAgent.indexOf("CriOS") !== -1; }; qq.iosSafari = function() { return qq.ios() && !qq.iosChrome() && navigator.userAgent.indexOf("Safari") !== -1; }; qq.iosSafariWebView = function() { return qq.ios() && !qq.iosChrome() && !qq.iosSafari(); }; qq.preventDefault = function(e) { if (e.preventDefault) { e.preventDefault(); } else { e.returnValue = false; } }; qq.toElement = function() { var div = document.createElement("div"); return function(html) { div.innerHTML = html; var element = div.firstChild; div.removeChild(element); return element; }; }(); qq.each = function(iterableItem, callback) { var keyOrIndex, retVal; if (iterableItem) { if (window.Storage && iterableItem.constructor === window.Storage) { for (keyOrIndex = 0; keyOrIndex < iterableItem.length; keyOrIndex++) { retVal = callback(iterableItem.key(keyOrIndex), iterableItem.getItem(iterableItem.key(keyOrIndex))); if (retVal === false) { break; } } } else if (qq.isArray(iterableItem) || qq.isItemList(iterableItem) || qq.isNodeList(iterableItem)) { for (keyOrIndex = 0; keyOrIndex < iterableItem.length; keyOrIndex++) { retVal = callback(keyOrIndex, iterableItem[keyOrIndex]); if (retVal === false) { break; } } } else if (qq.isString(iterableItem)) { for (keyOrIndex = 0; keyOrIndex < iterableItem.length; keyOrIndex++) { retVal = callback(keyOrIndex, iterableItem.charAt(keyOrIndex)); if (retVal === false) { break; } } } else { for (keyOrIndex in iterableItem) { if (Object.prototype.hasOwnProperty.call(iterableItem, keyOrIndex)) { retVal = callback(keyOrIndex, iterableItem[keyOrIndex]); if (retVal === false) { break; } } } } } }; qq.bind = function(oldFunc, context) { if (qq.isFunction(oldFunc)) { var args = Array.prototype.slice.call(arguments, 2); return function() { var newArgs = qq.extend([], args); if (arguments.length) { newArgs = newArgs.concat(Array.prototype.slice.call(arguments)); } return oldFunc.apply(context, newArgs); }; } throw new Error("first parameter must be a function!"); }; qq.obj2url = function(obj, temp, prefixDone) { var uristrings = [], prefix = "&", add = function(nextObj, i) { var nextTemp = temp ? /\[\]$/.test(temp) ? temp : temp + "[" + i + "]" : i; if (nextTemp !== "undefined" && i !== "undefined") { uristrings.push(typeof nextObj === "object" ? qq.obj2url(nextObj, nextTemp, true) : Object.prototype.toString.call(nextObj) === "[object Function]" ? encodeURIComponent(nextTemp) + "=" + encodeURIComponent(nextObj()) : encodeURIComponent(nextTemp) + "=" + encodeURIComponent(nextObj)); } }; if (!prefixDone && temp) { prefix = /\?/.test(temp) ? /\?$/.test(temp) ? "" : "&" : "?"; uristrings.push(temp); uristrings.push(qq.obj2url(obj)); } else if (Object.prototype.toString.call(obj) === "[object Array]" && typeof obj !== "undefined") { qq.each(obj, function(idx, val) { add(val, idx); }); } else if (typeof obj !== "undefined" && obj !== null && typeof obj === "object") { qq.each(obj, function(prop, val) { add(val, prop); }); } else { uristrings.push(encodeURIComponent(temp) + "=" + encodeURIComponent(obj)); } if (temp) { return uristrings.join(prefix); } else { return uristrings.join(prefix).replace(/^&/, "").replace(/%20/g, "+"); } }; qq.obj2FormData = function(obj, formData, arrayKeyName) { if (!formData) { formData = new FormData(); } qq.each(obj, function(key, val) { key = arrayKeyName ? arrayKeyName + "[" + key + "]" : key; if (qq.isObject(val)) { qq.obj2FormData(val, formData, key); } else if (qq.isFunction(val)) { formData.append(key, val()); } else { formData.append(key, val); } }); return formData; }; qq.obj2Inputs = function(obj, form) { var input; if (!form) { form = document.createElement("form"); } qq.obj2FormData(obj, { append: function(key, val) { input = document.createElement("input"); input.setAttribute("name", key); input.setAttribute("value", val); form.appendChild(input); } }); return form; }; qq.parseJson = function(json) { if (window.JSON && qq.isFunction(JSON.parse)) { return JSON.parse(json); } else { return eval("(" + json + ")"); } }; qq.getExtension = function(filename) { var extIdx = filename.lastIndexOf(".") + 1; if (extIdx > 0) { return filename.substr(extIdx, filename.length - extIdx); } }; qq.getFilename = function(blobOrFileInput) { if (qq.isInput(blobOrFileInput)) { return blobOrFileInput.value.replace(/.*(\/|\\)/, ""); } else if (qq.isFile(blobOrFileInput)) { if (blobOrFileInput.fileName !== null && blobOrFileInput.fileName !== undefined) { return blobOrFileInput.fileName; } } return blobOrFileInput.name; }; qq.DisposeSupport = function() { var disposers = []; return { dispose: function() { var disposer; do { disposer = disposers.shift(); if (disposer) { disposer(); } } while (disposer); }, attach: function() { var args = arguments; this.addDisposer(qq(args[0]).attach.apply(this, Array.prototype.slice.call(arguments, 1))); }, addDisposer: function(disposeFunction) { disposers.push(disposeFunction); } }; }; })(); (function() { "use strict"; if (typeof define === "function" && define.amd) { define(function() { return qq; }); } else if (typeof module !== "undefined" && module.exports) { module.exports = qq; } else { global.qq = qq; } })(); (function() { "use strict"; qq.Error = function(message) { this.message = "[Fine Uploader " + qq.version + "] " + message; }; qq.Error.prototype = new Error(); })(); qq.version = "5.15.1"; qq.supportedFeatures = function() { "use strict"; var supportsUploading, supportsUploadingBlobs, supportsFileDrop, supportsAjaxFileUploading, supportsFolderDrop, supportsChunking, supportsResume, supportsUploadViaPaste, supportsUploadCors, supportsDeleteFileXdr, supportsDeleteFileCorsXhr, supportsDeleteFileCors, supportsFolderSelection, supportsImagePreviews, supportsUploadProgress; function testSupportsFileInputElement() { var supported = true, tempInput; try { tempInput = document.createElement("input"); tempInput.type = "file"; qq(tempInput).hide(); if (tempInput.disabled) { supported = false; } } catch (ex) { supported = false; } return supported; } function isChrome21OrHigher() { return (qq.chrome() || qq.opera()) && navigator.userAgent.match(/Chrome\/[2][1-9]|Chrome\/[3-9][0-9]/) !== undefined; } function isChrome14OrHigher() { return (qq.chrome() || qq.opera()) && navigator.userAgent.match(/Chrome\/[1][4-9]|Chrome\/[2-9][0-9]/) !== undefined; } function isCrossOriginXhrSupported() { if (window.XMLHttpRequest) { var xhr = qq.createXhrInstance(); return xhr.withCredentials !== undefined; } return false; } function isXdrSupported() { return window.XDomainRequest !== undefined; } function isCrossOriginAjaxSupported() { if (isCrossOriginXhrSupported()) { return true; } return isXdrSupported(); } function isFolderSelectionSupported() { return document.createElement("input").webkitdirectory !== undefined; } function isLocalStorageSupported() { try { return !!window.localStorage && qq.isFunction(window.localStorage.setItem); } catch (error) { return false; } } function isDragAndDropSupported() { var span = document.createElement("span"); return ("draggable" in span || "ondragstart" in span && "ondrop" in span) && !qq.android() && !qq.ios(); } supportsUploading = testSupportsFileInputElement(); supportsAjaxFileUploading = supportsUploading && qq.isXhrUploadSupported(); supportsUploadingBlobs = supportsAjaxFileUploading && !qq.androidStock(); supportsFileDrop = supportsAjaxFileUploading && isDragAndDropSupported(); supportsFolderDrop = supportsFileDrop && isChrome21OrHigher(); supportsChunking = supportsAjaxFileUploading && qq.isFileChunkingSupported(); supportsResume = supportsAjaxFileUploading && supportsChunking && isLocalStorageSupported(); supportsUploadViaPaste = supportsAjaxFileUploading && isChrome14OrHigher(); supportsUploadCors = supportsUploading && (window.postMessage !== undefined || supportsAjaxFileUploading); supportsDeleteFileCorsXhr = isCrossOriginXhrSupported(); supportsDeleteFileXdr = isXdrSupported(); supportsDeleteFileCors = isCrossOriginAjaxSupported(); supportsFolderSelection = isFolderSelectionSupported(); supportsImagePreviews = supportsAjaxFileUploading && window.FileReader !== undefined; supportsUploadProgress = function() { if (supportsAjaxFileUploading) { return !qq.androidStock() && !qq.iosChrome(); } return false; }(); return { ajaxUploading: supportsAjaxFileUploading, blobUploading: supportsUploadingBlobs, canDetermineSize: supportsAjaxFileUploading, chunking: supportsChunking, deleteFileCors: supportsDeleteFileCors, deleteFileCorsXdr: supportsDeleteFileXdr, deleteFileCorsXhr: supportsDeleteFileCorsXhr, dialogElement: !!window.HTMLDialogElement, fileDrop: supportsFileDrop, folderDrop: supportsFolderDrop, folderSelection: supportsFolderSelection, imagePreviews: supportsImagePreviews, imageValidation: supportsImagePreviews, itemSizeValidation: supportsAjaxFileUploading, pause: supportsChunking, progressBar: supportsUploadProgress, resume: supportsResume, scaling: supportsImagePreviews && supportsUploadingBlobs, tiffPreviews: qq.safari(), unlimitedScaledImageSize: !qq.ios(), uploading: supportsUploading, uploadCors: supportsUploadCors, uploadCustomHeaders: supportsAjaxFileUploading, uploadNonMultipart: supportsAjaxFileUploading, uploadViaPaste: supportsUploadViaPaste }; }(); qq.isGenericPromise = function(maybePromise) { "use strict"; return !!(maybePromise && maybePromise.then && qq.isFunction(maybePromise.then)); }; qq.Promise = function() { "use strict"; var successArgs, failureArgs, successCallbacks = [], failureCallbacks = [], doneCallbacks = [], state = 0; qq.extend(this, { then: function(onSuccess, onFailure) { if (state === 0) { if (onSuccess) { successCallbacks.push(onSuccess); } if (onFailure) { failureCallbacks.push(onFailure); } } else if (state === -1) { onFailure && onFailure.apply(null, failureArgs); } else if (onSuccess) { onSuccess.apply(null, successArgs); } return this; }, done: function(callback) { if (state === 0) { doneCallbacks.push(callback); } else { callback.apply(null, failureArgs === undefined ? successArgs : failureArgs); } return this; }, success: function() { state = 1; successArgs = arguments; if (successCallbacks.length) { qq.each(successCallbacks, function(idx, callback) { callback.apply(null, successArgs); }); } if (doneCallbacks.length) { qq.each(doneCallbacks, function(idx, callback) { callback.apply(null, successArgs); }); } return this; }, failure: function() { state = -1; failureArgs = arguments; if (failureCallbacks.length) { qq.each(failureCallbacks, function(idx, callback) { callback.apply(null, failureArgs); }); } if (doneCallbacks.length) { qq.each(doneCallbacks, function(idx, callback) { callback.apply(null, failureArgs); }); } return this; } }); }; qq.BlobProxy = function(referenceBlob, onCreate) { "use strict"; qq.extend(this, { referenceBlob: referenceBlob, create: function() { return onCreate(referenceBlob); } }); }; qq.UploadButton = function(o) { "use strict"; var self = this, disposeSupport = new qq.DisposeSupport(), options = { acceptFiles: null, element: null, focusClass: "qq-upload-button-focus", folders: false, hoverClass: "qq-upload-button-hover", ios8BrowserCrashWorkaround: false, multiple: false, name: "qqfile", onChange: function(input) {}, title: null }, input, buttonId; qq.extend(options, o); buttonId = qq.getUniqueId(); function createInput() { var input = document.createElement("input"); input.setAttribute(qq.UploadButton.BUTTON_ID_ATTR_NAME, buttonId); input.setAttribute("title", options.title); self.setMultiple(options.multiple, input); if (options.folders && qq.supportedFeatures.folderSelection) { input.setAttribute("webkitdirectory", ""); } if (options.acceptFiles) { input.setAttribute("accept", options.acceptFiles); } input.setAttribute("type", "file"); input.setAttribute("name", options.name); qq(input).css({ position: "absolute", right: 0, top: 0, fontFamily: "Arial", fontSize: qq.ie() && !qq.ie8() ? "3500px" : "118px", margin: 0, padding: 0, cursor: "pointer", opacity: 0 }); !qq.ie7() && qq(input).css({ height: "100%" }); options.element.appendChild(input); disposeSupport.attach(input, "change", function() { options.onChange(input); }); disposeSupport.attach(input, "mouseover", function() { qq(options.element).addClass(options.hoverClass); }); disposeSupport.attach(input, "mouseout", function() { qq(options.element).removeClass(options.hoverClass); }); disposeSupport.attach(input, "focus", function() { qq(options.element).addClass(options.focusClass); }); disposeSupport.attach(input, "blur", function() { qq(options.element).removeClass(options.focusClass); }); return input; } qq(options.element).css({ position: "relative", overflow: "hidden", direction: "ltr" }); qq.extend(this, { getInput: function() { return input; }, getButtonId: function() { return buttonId; }, setMultiple: function(isMultiple, optInput) { var input = optInput || this.getInput(); if (options.ios8BrowserCrashWorkaround && qq.ios8() && (qq.iosChrome() || qq.iosSafariWebView())) { input.setAttribute("multiple", ""); } else { if (isMultiple) { input.setAttribute("multiple", ""); } else { input.removeAttribute("multiple"); } } }, setAcceptFiles: function(acceptFiles) { if (acceptFiles !== options.acceptFiles) { input.setAttribute("accept", acceptFiles); } }, reset: function() { if (input.parentNode) { qq(input).remove(); } qq(options.element).removeClass(options.focusClass); input = null; input = createInput(); } }); input = createInput(); }; qq.UploadButton.BUTTON_ID_ATTR_NAME = "qq-button-id"; qq.UploadData = function(uploaderProxy) { "use strict"; var data = [], byUuid = {}, byStatus = {}, byProxyGroupId = {}, byBatchId = {}; function getDataByIds(idOrIds) { if (qq.isArray(idOrIds)) { var entries = []; qq.each(idOrIds, function(idx, id) { entries.push(data[id]); }); return entries; } return data[idOrIds]; } function getDataByUuids(uuids) { if (qq.isArray(uuids)) { var entries = []; qq.each(uuids, function(idx, uuid) { entries.push(data[byUuid[uuid]]); }); return entries; } return data[byUuid[uuids]]; } function getDataByStatus(status) { var statusResults = [], statuses = [].concat(status); qq.each(statuses, function(index, statusEnum) { var statusResultIndexes = byStatus[statusEnum]; if (statusResultIndexes !== undefined) { qq.each(statusResultIndexes, function(i, dataIndex) { statusResults.push(data[dataIndex]); }); } }); return statusResults; } qq.extend(this, { addFile: function(spec) { var status = spec.status || qq.status.SUBMITTING, id = data.push({ name: spec.name, originalName: spec.name, uuid: spec.uuid, size: spec.size == null ? -1 : spec.size, status: status }) - 1; if (spec.batchId) { data[id].batchId = spec.batchId; if (byBatchId[spec.batchId] === undefined) { byBatchId[spec.batchId] = []; } byBatchId[spec.batchId].push(id); } if (spec.proxyGroupId) { data[id].proxyGroupId = spec.proxyGroupId; if (byProxyGroupId[spec.proxyGroupId] === undefined) { byProxyGroupId[spec.proxyGroupId] = []; } byProxyGroupId[spec.proxyGroupId].push(id); } data[id].id = id; byUuid[spec.uuid] = id; if (byStatus[status] === undefined) { byStatus[status] = []; } byStatus[status].push(id); spec.onBeforeStatusChange && spec.onBeforeStatusChange(id); uploaderProxy.onStatusChange(id, null, status); return id; }, retrieve: function(optionalFilter) { if (qq.isObject(optionalFilter) && data.length) { if (optionalFilter.id !== undefined) { return getDataByIds(optionalFilter.id); } else if (optionalFilter.uuid !== undefined) { return getDataByUuids(optionalFilter.uuid); } else if (optionalFilter.status) { return getDataByStatus(optionalFilter.status); } } else { return qq.extend([], data, true); } }, reset: function() { data = []; byUuid = {}; byStatus = {}; byBatchId = {}; }, setStatus: function(id, newStatus) { var oldStatus = data[id].status, byStatusOldStatusIndex = qq.indexOf(byStatus[oldStatus], id); byStatus[oldStatus].splice(byStatusOldStatusIndex, 1); data[id].status = newStatus; if (byStatus[newStatus] === undefined) { byStatus[newStatus] = []; } byStatus[newStatus].push(id); uploaderProxy.onStatusChange(id, oldStatus, newStatus); }, uuidChanged: function(id, newUuid) { var oldUuid = data[id].uuid; data[id].uuid = newUuid; byUuid[newUuid] = id; delete byUuid[oldUuid]; }, updateName: function(id, newName) { data[id].name = newName; }, updateSize: function(id, newSize) { data[id].size = newSize; }, setParentId: function(targetId, parentId) { data[targetId].parentId = parentId; }, getIdsInProxyGroup: function(id) { var proxyGroupId = data[id].proxyGroupId; if (proxyGroupId) { return byProxyGroupId[proxyGroupId]; } return []; }, getIdsInBatch: function(id) { var batchId = data[id].batchId; return byBatchId[batchId]; } }); }; qq.status = { SUBMITTING: "submitting", SUBMITTED: "submitted", REJECTED: "rejected", QUEUED: "queued", CANCELED: "canceled", PAUSED: "paused", UPLOADING: "uploading", UPLOAD_RETRYING: "retrying upload", UPLOAD_SUCCESSFUL: "upload successful", UPLOAD_FAILED: "upload failed", DELETE_FAILED: "delete failed", DELETING: "deleting", DELETED: "deleted" }; (function() { "use strict"; qq.basePublicApi = { addBlobs: function(blobDataOrArray, params, endpoint) { this.addFiles(blobDataOrArray, params, endpoint); }, addInitialFiles: function(cannedFileList) { var self = this; qq.each(cannedFileList, function(index, cannedFile) { self._addCannedFile(cannedFile); }); }, addFiles: function(data, params, endpoint) { this._maybeHandleIos8SafariWorkaround(); var batchId = this._storedIds.length === 0 ? qq.getUniqueId() : this._currentBatchId, processBlob = qq.bind(function(blob) { this._handleNewFile({ blob: blob, name: this._options.blobs.defaultName }, batchId, verifiedFiles); }, this), processBlobData = qq.bind(function(blobData) { this._handleNewFile(blobData, batchId, verifiedFiles); }, this), processCanvas = qq.bind(function(canvas) { var blob = qq.canvasToBlob(canvas); this._handleNewFile({ blob: blob, name: this._options.blobs.defaultName + ".png" }, batchId, verifiedFiles); }, this), processCanvasData = qq.bind(function(canvasData) { var normalizedQuality = canvasData.quality && canvasData.quality / 100, blob = qq.canvasToBlob(canvasData.canvas, canvasData.type, normalizedQuality); this._handleNewFile({ blob: blob, name: canvasData.name }, batchId, verifiedFiles); }, this), processFileOrInput = qq.bind(function(fileOrInput) { if (qq.isInput(fileOrInput) && qq.supportedFeatures.ajaxUploading) { var files = Array.prototype.slice.call(fileOrInput.files), self = this; qq.each(files, function(idx, file) { self._handleNewFile(file, batchId, verifiedFiles); }); } else { this._handleNewFile(fileOrInput, batchId, verifiedFiles); } }, this), normalizeData = function() { if (qq.isFileList(data)) { data = Array.prototype.slice.call(data); } data = [].concat(data); }, self = this, verifiedFiles = []; this._currentBatchId = batchId; if (data) { normalizeData(); qq.each(data, function(idx, fileContainer) { if (qq.isFileOrInput(fileContainer)) { processFileOrInput(fileContainer); } else if (qq.isBlob(fileContainer)) { processBlob(fileContainer); } else if (qq.isObject(fileContainer)) { if (fileContainer.blob && fileContainer.name) { processBlobData(fileContainer); } else if (fileContainer.canvas && fileContainer.name) { processCanvasData(fileContainer); } } else if (fileContainer.tagName && fileContainer.tagName.toLowerCase() === "canvas") { processCanvas(fileContainer); } else { self.log(fileContainer + " is not a valid file container! Ignoring!", "warn"); } }); this.log("Received " + verifiedFiles.length + " files."); this._prepareItemsForUpload(verifiedFiles, params, endpoint); } }, cancel: function(id) { this._handler.cancel(id); }, cancelAll: function() { var storedIdsCopy = [], self = this; qq.extend(storedIdsCopy, this._storedIds); qq.each(storedIdsCopy, function(idx, storedFileId) { self.cancel(storedFileId); }); this._handler.cancelAll(); }, clearStoredFiles: function() { this._storedIds = []; }, continueUpload: function(id) { var uploadData = this._uploadData.retrieve({ id: id }); if (!qq.supportedFeatures.pause || !this._options.chunking.enabled) { return false; } if (uploadData.status === qq.status.PAUSED) { this.log(qq.format("Paused file ID {} ({}) will be continued. Not paused.", id, this.getName(id))); this._uploadFile(id); return true; } else { this.log(qq.format("Ignoring continue for file ID {} ({}). Not paused.", id, this.getName(id)), "error"); } return false; }, deleteFile: function(id) { return this._onSubmitDelete(id); }, doesExist: function(fileOrBlobId) { return this._handler.isValid(fileOrBlobId); }, drawThumbnail: function(fileId, imgOrCanvas, maxSize, fromServer, customResizeFunction) { var promiseToReturn = new qq.Promise(), fileOrUrl, options; if (this._imageGenerator) { fileOrUrl = this._thumbnailUrls[fileId]; options = { customResizeFunction: customResizeFunction, maxSize: maxSize > 0 ? maxSize : null, scale: maxSize > 0 }; if (!fromServer && qq.supportedFeatures.imagePreviews) { fileOrUrl = this.getFile(fileId); } if (fileOrUrl == null) { promiseToReturn.failure({ container: imgOrCanvas, error: "File or URL not found." }); } else { this._imageGenerator.generate(fileOrUrl, imgOrCanvas, options).then(function success(modifiedContainer) { promiseToReturn.success(modifiedContainer); }, function failure(container, reason) { promiseToReturn.failure({ container: container, error: reason || "Problem generating thumbnail" }); }); } } else { promiseToReturn.failure({ container: imgOrCanvas, error: "Missing image generator module" }); } return promiseToReturn; }, getButton: function(fileId) { return this._getButton(this._buttonIdsForFileIds[fileId]); }, getEndpoint: function(fileId) { return this._endpointStore.get(fileId); }, getFile: function(fileOrBlobId) { return this._handler.getFile(fileOrBlobId) || null; }, getInProgress: function() { return this._uploadData.retrieve({ status: [ qq.status.UPLOADING, qq.status.UPLOAD_RETRYING, qq.status.QUEUED ] }).length; }, getName: function(id) { return this._uploadData.retrieve({ id: id }).name; }, getParentId: function(id) { var uploadDataEntry = this.getUploads({ id: id }), parentId = null; if (uploadDataEntry) { if (uploadDataEntry.parentId !== undefined) { parentId = uploadDataEntry.parentId; } } return parentId; }, getResumableFilesData: function() { return this._handler.getResumableFilesData(); }, getSize: function(id) { return this._uploadData.retrieve({ id: id }).size; }, getNetUploads: function() { return this._netUploaded; }, getRemainingAllowedItems: function() { var allowedItems = this._currentItemLimit; if (allowedItems > 0) { return allowedItems - this._netUploadedOrQueued; } return null; }, getUploads: function(optionalFilter) { return this._uploadData.retrieve(optionalFilter); }, getUuid: function(id) { return this._uploadData.retrieve({ id: id }).uuid; }, log: function(str, level) { if (this._options.debug && (!level || level === "info")) { qq.log("[Fine Uploader " + qq.version + "] " + str); } else if (level && level !== "info") { qq.log("[Fine Uploader " + qq.version + "] " + str, level); } }, pauseUpload: function(id) { var uploadData = this._uploadData.retrieve({ id: id }); if (!qq.supportedFeatures.pause || !this._options.chunking.enabled) { return false; } if (qq.indexOf([ qq.status.UPLOADING, qq.status.UPLOAD_RETRYING ], uploadData.status) >= 0) { if (this._handler.pause(id)) { this._uploadData.setStatus(id, qq.status.PAUSED); return true; } else { this.log(qq.format("Unable to pause file ID {} ({}).", id, this.getName(id)), "error"); } } else { this.log(qq.format("Ignoring pause for file ID {} ({}). Not in progress.", id, this.getName(id)), "error"); } return false; }, removeFileRef: function(id) { this._handler.expunge(id); }, reset: function() { this.log("Resetting uploader..."); this._handler.reset(); this._storedIds = []; this._autoRetries = []; this._retryTimeouts = []; this._preventRetries = []; this._thumbnailUrls = []; qq.each(this._buttons, function(idx, button) { button.reset(); }); this._paramsStore.reset(); this._endpointStore.reset(); this._netUploadedOrQueued = 0; this._netUploaded = 0; this._uploadData.reset(); this._buttonIdsForFileIds = []; this._pasteHandler && this._pasteHandler.reset(); this._options.session.refreshOnReset && this._refreshSessionData(); this._succeededSinceLastAllComplete = []; this._failedSinceLastAllComplete = []; this._totalProgress && this._totalProgress.reset(); }, retry: function(id) { return this._manualRetry(id); }, scaleImage: function(id, specs) { var self = this; return qq.Scaler.prototype.scaleImage(id, specs, { log: qq.bind(self.log, self), getFile: qq.bind(self.getFile, self), uploadData: self._uploadData }); }, setCustomHeaders: function(headers, id) { this._customHeadersStore.set(headers, id); }, setDeleteFileCustomHeaders: function(headers, id) { this._deleteFileCustomHeadersStore.set(headers, id); }, setDeleteFileEndpoint: function(endpoint, id) { this._deleteFileEndpointStore.set(endpoint, id); }, setDeleteFileParams: function(params, id) { this._deleteFileParamsStore.set(params, id); }, setEndpoint: function(endpoint, id) { this._endpointStore.set(endpoint, id); }, setForm: function(elementOrId) { this._updateFormSupportAndParams(elementOrId); }, setItemLimit: function(newItemLimit) { this._currentItemLimit = newItemLimit; }, setName: function(id, newName) { this._uploadData.updateName(id, newName); }, setParams: function(params, id) { this._paramsStore.set(params, id); }, setUuid: function(id, newUuid) { return this._uploadData.uuidChanged(id, newUuid); }, setStatus: function(id, newStatus) { var fileRecord = this.getUploads({ id: id }); if (!fileRecord) { throw new qq.Error(id + " is not a valid file ID."); } switch (newStatus) { case qq.status.DELETED: this._onDeleteComplete(id, null, false); break; case qq.status.DELETE_FAILED: this._onDeleteComplete(id, null, true); break; default: var errorMessage = "Method setStatus called on '" + name + "' not implemented yet for " + newStatus; this.log(errorMessage); throw new qq.Error(errorMessage); } }, uploadStoredFiles: function() { if (this._storedIds.length === 0) { this._itemError("noFilesError"); } else { this._uploadStoredFiles(); } } }; qq.basePrivateApi = { _addCannedFile: function(sessionData) { var self = this; return this._uploadData.addFile({ uuid: sessionData.uuid, name: sessionData.name, size: sessionData.size, status: qq.status.UPLOAD_SUCCESSFUL, onBeforeStatusChange: function(id) { sessionData.deleteFileEndpoint && self.setDeleteFileEndpoint(sessionData.deleteFileEndpoint, id); sessionData.deleteFileParams && self.setDeleteFileParams(sessionData.deleteFileParams, id); if (sessionData.thumbnailUrl) { self._thumbnailUrls[id] = sessionData.thumbnailUrl; } self._netUploaded++; self._netUploadedOrQueued++; } }); }, _annotateWithButtonId: function(file, associatedInput) { if (qq.isFile(file)) { file.qqButtonId = this._getButtonId(associatedInput); } }, _batchError: function(message) { this._options.callbacks.onError(null, null, message, undefined); }, _createDeleteHandler: function() { var self = this; return new qq.DeleteFileAjaxRequester({ method: this._options.deleteFile.method.toUpperCase(), maxConnections: this._options.maxConnections, uuidParamName: this._options.request.uuidName, customHeaders: this._deleteFileCustomHeadersStore, paramsStore: this._deleteFileParamsStore, endpointStore: this._deleteFileEndpointStore, cors: this._options.cors, log: qq.bind(self.log, self), onDelete: function(id) { self._onDelete(id); self._options.callbacks.onDelete(id); }, onDeleteComplete: function(id, xhrOrXdr, isError) { self._onDeleteComplete(id, xhrOrXdr, isError); self._options.callbacks.onDeleteComplete(id, xhrOrXdr, isError); } }); }, _createPasteHandler: function() { var self = this; return new qq.PasteSupport({ targetElement: this._options.paste.targetElement, callbacks: { log: qq.bind(self.log, self), pasteReceived: function(blob) { self._handleCheckedCallback({ name: "onPasteReceived", callback: qq.bind(self._options.callbacks.onPasteReceived, self, blob), onSuccess: qq.bind(self._handlePasteSuccess, self, blob), identifier: "pasted image" }); } } }); }, _createStore: function(initialValue, _readOnlyValues_) { var store = {}, catchall = initialValue, perIdReadOnlyValues = {}, readOnlyValues = _readOnlyValues_, copy = function(orig) { if (qq.isObject(orig)) { return qq.extend({}, orig); } return orig; }, getReadOnlyValues = function() { if (qq.isFunction(readOnlyValues)) { return readOnlyValues(); } return readOnlyValues; }, includeReadOnlyValues = function(id, existing) { if (readOnlyValues && qq.isObject(existing)) { qq.extend(existing, getReadOnlyValues()); } if (perIdReadOnlyValues[id]) { qq.extend(existing, perIdReadOnlyValues[id]); } }; return { set: function(val, id) { if (id == null) { store = {}; catchall = copy(val); } else { store[id] = copy(val); } }, get: function(id) { var values; if (id != null && store[id]) { values = store[id]; } else { values = copy(catchall); } includeReadOnlyValues(id, values); return copy(values); }, addReadOnly: function(id, values) { if (qq.isObject(store)) { if (id === null) { if (qq.isFunction(values)) { readOnlyValues = values; } else { readOnlyValues = readOnlyValues || {}; qq.extend(readOnlyValues, values); } } else { perIdReadOnlyValues[id] = perIdReadOnlyValues[id] || {}; qq.extend(perIdReadOnlyValues[id], values); } } }, remove: function(fileId) { return delete store[fileId]; }, reset: function() { store = {}; perIdReadOnlyValues = {}; catchall = initialValue; } }; }, _createUploadDataTracker: function() { var self = this; return new qq.UploadData({ getName: function(id) { return self.getName(id); }, getUuid: function(id) { return self.getUuid(id); }, getSize: function(id) { return self.getSize(id); }, onStatusChange: function(id, oldStatus, newStatus) { self._onUploadStatusChange(id, oldStatus, newStatus); self._options.callbacks.onStatusChange(id, oldStatus, newStatus); self._maybeAllComplete(id, newStatus); if (self._totalProgress) { setTimeout(function() { self._totalProgress.onStatusChange(id, oldStatus, newStatus); }, 0); } } }); }, _createUploadButton: function(spec) { var self = this, acceptFiles = spec.accept || this._options.validation.acceptFiles, allowedExtensions = spec.allowedExtensions || this._options.validation.allowedExtensions, button; function allowMultiple() { if (qq.supportedFeatures.ajaxUploading) { if (self._options.workarounds.iosEmptyVideos && qq.ios() && !qq.ios6() && self._isAllowedExtension(allowedExtensions, ".mov")) { return false; } if (spec.multiple === undefined) { return self._options.multiple; } return spec.multiple; } return false; } button = new qq.UploadButton({ acceptFiles: acceptFiles, element: spec.element, focusClass: this._options.classes.buttonFocus, folders: spec.folders, hoverClass: this._options.classes.buttonHover, ios8BrowserCrashWorkaround: this._options.workarounds.ios8BrowserCrash, multiple: allowMultiple(), name: this._options.request.inputName, onChange: function(input) { self._onInputChange(input); }, title: spec.title == null ? this._options.text.fileInputTitle : spec.title }); this._disposeSupport.addDisposer(function() { button.dispose(); }); self._buttons.push(button); return button; }, _createUploadHandler: function(additionalOptions, namespace) { var self = this, lastOnProgress = {}, options = { debug: this._options.debug, maxConnections: this._options.maxConnections, cors: this._options.cors, paramsStore: this._paramsStore, endpointStore: this._endpointStore, chunking: this._options.chunking, resume: this._options.resume, blobs: this._options.blobs, log: qq.bind(self.log, self), preventRetryParam: this._options.retry.preventRetryResponseProperty, onProgress: function(id, name, loaded, total) { if (loaded < 0 || total < 0) { return; } if (lastOnProgress[id]) { if (lastOnProgress[id].loaded !== loaded || lastOnProgress[id].total !== total) { self._onProgress(id, name, loaded, total); self._options.callbacks.onProgress(id, name, loaded, total); } } else { self._onProgress(id, name, loaded, total); self._options.callbacks.onProgress(id, name, loaded, total); } lastOnProgress[id] = { loaded: loaded, total: total }; }, onComplete: function(id, name, result, xhr) { delete lastOnProgress[id]; var status = self.getUploads({ id: id }).status, retVal; if (status === qq.status.UPLOAD_SUCCESSFUL || status === qq.status.UPLOAD_FAILED) { return; } retVal = self._onComplete(id, name, result, xhr); if (retVal instanceof qq.Promise) { retVal.done(function() { self._options.callbacks.onComplete(id, name, result, xhr); }); } else { self._options.callbacks.onComplete(id, name, result, xhr); } }, onCancel: function(id, name, cancelFinalizationEffort) { var promise = new qq.Promise(); self._handleCheckedCallback({ name: "onCancel", callback: qq.bind(self._options.callbacks.onCancel, self, id, name), onFailure: promise.failure, onSuccess: function() { cancelFinalizationEffort.then(function() { self._onCancel(id, name); }); promise.success(); }, identifier: id }); return promise; }, onUploadPrep: qq.bind(this._onUploadPrep, this), onUpload: function(id, name) { self._onUpload(id, name); self._options.callbacks.onUpload(id, name); }, onUploadChunk: function(id, name, chunkData) { self._onUploadChunk(id, chunkData); self._options.callbacks.onUploadChunk(id, name, chunkData); }, onUploadChunkSuccess: function(id, chunkData, result, xhr) { self._options.callbacks.onUploadChunkSuccess.apply(self, arguments); }, onResume: function(id, name, chunkData) { return self._options.callbacks.onResume(id, name, chunkData); }, onAutoRetry: function(id, name, responseJSON, xhr) { return self._onAutoRetry.apply(self, arguments); }, onUuidChanged: function(id, newUuid) { self.log("Server requested UUID change from '" + self.getUuid(id) + "' to '" + newUuid + "'"); self.setUuid(id, newUuid); }, getName: qq.bind(self.getName, self), getUuid: qq.bind(self.getUuid, self), getSize: qq.bind(self.getSize, self), setSize: qq.bind(self._setSize, self), getDataByUuid: function(uuid) { return self.getUploads({ uuid: uuid }); }, isQueued: function(id) { var status = self.getUploads({ id: id }).status; return status === qq.status.QUEUED || status === qq.status.SUBMITTED || status === qq.status.UPLOAD_RETRYING || status === qq.status.PAUSED; }, getIdsInProxyGroup: self._uploadData.getIdsInProxyGroup, getIdsInBatch: self._uploadData.getIdsInBatch }; qq.each(this._options.request, function(prop, val) { options[prop] = val; }); options.customHeaders = this._customHeadersStore; if (additionalOptions) { qq.each(additionalOptions, function(key, val) { options[key] = val; }); } return new qq.UploadHandlerController(options, namespace); }, _fileOrBlobRejected: function(id) { this._netUploadedOrQueued--; this._uploadData.setStatus(id, qq.status.REJECTED); }, _formatSize: function(bytes) { if (bytes === 0) { return bytes + this._options.text.sizeSymbols[0]; } var i = -1; do { bytes = bytes / 1e3; i++; } while (bytes > 999); return Math.max(bytes, .1).toFixed(1) + this._options.text.sizeSymbols[i]; }, _generateExtraButtonSpecs: function() { var self = this; this._extraButtonSpecs = {}; qq.each(this._options.extraButtons, function(idx, extraButtonOptionEntry) { var multiple = extraButtonOptionEntry.multiple, validation = qq.extend({}, self._options.validation, true), extraButtonSpec = qq.extend({}, extraButtonOptionEntry); if (multiple === undefined) { multiple = self._options.multiple; } if (extraButtonSpec.validation) { qq.extend(validation, extraButtonOptionEntry.validation, true); } qq.extend(extraButtonSpec, { multiple: multiple, validation: validation }, true); self._initExtraButton(extraButtonSpec); }); }, _getButton: function(buttonId) { var extraButtonsSpec = this._extraButtonSpecs[buttonId]; if (extraButtonsSpec) { return extraButtonsSpec.element; } else if (buttonId === this._defaultButtonId) { return this._options.button; } }, _getButtonId: function(buttonOrFileInputOrFile) { var inputs, fileInput, fileBlobOrInput = buttonOrFileInputOrFile; if (fileBlobOrInput instanceof qq.BlobProxy) { fileBlobOrInput = fileBlobOrInput.referenceBlob; } if (fileBlobOrInput && !qq.isBlob(fileBlobOrInput)) { if (qq.isFile(fileBlobOrInput)) { return fileBlobOrInput.qqButtonId; } else if (fileBlobOrInput.tagName.toLowerCase() === "input" && fileBlobOrInput.type.toLowerCase() === "file") { return fileBlobOrInput.getAttribute(qq.UploadButton.BUTTON_ID_ATTR_NAME); } inputs = fileBlobOrInput.getElementsByTagName("input"); qq.each(inputs, function(idx, input) { if (input.getAttribute("type") === "file") { fileInput = input; return false; } }); if (fileInput) { return fileInput.getAttribute(qq.UploadButton.BUTTON_ID_ATTR_NAME); } } }, _getNotFinished: function() { return this._uploadData.retrieve({ status: [ qq.status.UPLOADING, qq.status.UPLOAD_RETRYING, qq.status.QUEUED, qq.status.SUBMITTING, qq.status.SUBMITTED, qq.status.PAUSED ] }).length; }, _getValidationBase: function(buttonId) { var extraButtonSpec = this._extraButtonSpecs[buttonId]; return extraButtonSpec ? extraButtonSpec.validation : this._options.validation; }, _getValidationDescriptor: function(fileWrapper) { if (fileWrapper.file instanceof qq.BlobProxy) { return { name: qq.getFilename(fileWrapper.file.referenceBlob), size: fileWrapper.file.referenceBlob.size }; } return { name: this.getUploads({ id: fileWrapper.id }).name, size: this.getUploads({ id: fileWrapper.id }).size }; }, _getValidationDescriptors: function(fileWrappers) { var self = this, fileDescriptors = []; qq.each(fileWrappers, function(idx, fileWrapper) { fileDescriptors.push(self._getValidationDescriptor(fileWrapper)); }); return fileDescriptors; }, _handleCameraAccess: function() { if (this._options.camera.ios && qq.ios()) { var acceptIosCamera = "image/*;capture=camera", button = this._options.camera.button, buttonId = button ? this._getButtonId(button) : this._defaultButtonId, optionRoot = this._options; if (buttonId && buttonId !== this._defaultButtonId) { optionRoot = this._extraButtonSpecs[buttonId]; } optionRoot.multiple = false; if (optionRoot.validation.acceptFiles === null) { optionRoot.validation.acceptFiles = acceptIosCamera; } else { optionRoot.validation.acceptFiles += "," + acceptIosCamera; } qq.each(this._buttons, function(idx, button) { if (button.getButtonId() === buttonId) { button.setMultiple(optionRoot.multiple); button.setAcceptFiles(optionRoot.acceptFiles); return false; } }); } }, _handleCheckedCallback: function(details) { var self = this, callbackRetVal = details.callback(); if (qq.isGenericPromise(callbackRetVal)) { this.log(details.name + " - waiting for " + details.name + " promise to be fulfilled for " + details.identifier); return callbackRetVal.then(function(successParam) { self.log(details.name + " promise success for " + details.identifier); details.onSuccess(successParam); }, function() { if (details.onFailure) { self.log(details.name + " promise failure for " + details.identifier); details.onFailure(); } else { self.log(details.name + " promise failure for " + details.identifier); } }); } if (callbackRetVal !== false) { details.onSuccess(callbackRetVal); } else { if (details.onFailure) { this.log(details.name + " - return value was 'false' for " + details.identifier + ". Invoking failure callback."); details.onFailure(); } else { this.log(details.name + " - return value was 'false' for " + details.identifier + ". Will not proceed."); } } return callbackRetVal; }, _handleNewFile: function(file, batchId, newFileWrapperList) { var self = this, uuid = qq.getUniqueId(), size = -1, name = qq.getFilename(file), actualFile = file.blob || file, handler = this._customNewFileHandler ? this._customNewFileHandler : qq.bind(self._handleNewFileGeneric, self); if (!qq.isInput(actualFile) && actualFile.size >= 0) { size = actualFile.size; } handler(actualFile, name, uuid, size, newFileWrapperList, batchId, this._options.request.uuidName, { uploadData: self._uploadData, paramsStore: self._paramsStore, addFileToHandler: function(id, file) { self._handler.add(id, file); self._netUploadedOrQueued++; self._trackButton(id); } }); }, _handleNewFileGeneric: function(file, name, uuid, size, fileList, batchId) { var id = this._uploadData.addFile({ uuid: uuid, name: name, size: size, batchId: batchId }); this._handler.add(id, file); this._trackButton(id); this._netUploadedOrQueued++; fileList.push({ id: id, file: file }); }, _handlePasteSuccess: function(blob, extSuppliedName) { var extension = blob.type.split("/")[1], name = extSuppliedName; if (name == null) { name = this._options.paste.defaultName; } name += "." + extension; this.addFiles({ name: name, blob: blob }); }, _handleDeleteSuccess: function(id) { if (this.getUploads({ id: id }).status !== qq.status.DELETED) { var name = this.getName(id); this._netUploadedOrQueued--; this._netUploaded--; this._handler.expunge(id); this._uploadData.setStatus(id, qq.status.DELETED); this.log("Delete request for '" + name + "' has succeeded."); } }, _handleDeleteFailed: function(id, xhrOrXdr) { var name = this.getName(id); this._uploadData.setStatus(id, qq.status.DELETE_FAILED); this.log("Delete request for '" + name + "' has failed.", "error"); if (!xhrOrXdr || xhrOrXdr.withCredentials === undefined) { this._options.callbacks.onError(id, name, "Delete request failed", xhrOrXdr); } else { this._options.callbacks.onError(id, name, "Delete request failed with response code " + xhrOrXdr.status, xhrOrXdr); } }, _initExtraButton: function(spec) { var button = this._createUploadButton({ accept: spec.validation.acceptFiles, allowedExtensions: spec.validation.allowedExtensions, element: spec.element, folders: spec.folders, multiple: spec.multiple, title: spec.fileInputTitle }); this._extraButtonSpecs[button.getButtonId()] = spec; }, _initFormSupportAndParams: function() { this._formSupport = qq.FormSupport && new qq.FormSupport(this._options.form, qq.bind(this.uploadStoredFiles, this), qq.bind(this.log, this)); if (this._formSupport && this._formSupport.attachedToForm) { this._paramsStore = this._createStore(this._options.request.params, this._formSupport.getFormInputsAsObject); this._options.autoUpload = this._formSupport.newAutoUpload; if (this._formSupport.newEndpoint) { this._options.request.endpoint = this._formSupport.newEndpoint; } } else { this._paramsStore = this._createStore(this._options.request.params); } }, _isDeletePossible: function() { if (!qq.DeleteFileAjaxRequester || !this._options.deleteFile.enabled) { return false; } if (this._options.cors.expected) { if (qq.supportedFeatures.deleteFileCorsXhr) { return true; } if (qq.supportedFeatures.deleteFileCorsXdr && this._options.cors.allowXdr) { return true; } return false; } return true; }, _isAllowedExtension: function(allowed, fileName) { var valid = false; if (!allowed.length) { return true; } qq.each(allowed, function(idx, allowedExt) { if (qq.isString(allowedExt)) { var extRegex = new RegExp("\\." + allowedExt + "$", "i"); if (fileName.match(extRegex) != null) { valid = true; return false; } } }); return valid; }, _itemError: function(code, maybeNameOrNames, item) { var message = this._options.messages[code], allowedExtensions = [], names = [].concat(maybeNameOrNames), name = names[0], buttonId = this._getButtonId(item), validationBase = this._getValidationBase(buttonId), extensionsForMessage, placeholderMatch; function r(name, replacement) { message = message.replace(name, replacement); } qq.each(validationBase.allowedExtensions, function(idx, allowedExtension) { if (qq.isString(allowedExtension)) { allowedExtensions.push(allowedExtension); } }); extensionsForMessage = allowedExtensions.join(", ").toLowerCase(); r("{file}", this._options.formatFileName(name)); r("{extensions}", extensionsForMessage); r("{sizeLimit}", this._formatSize(validationBase.sizeLimit)); r("{minSizeLimit}", this._formatSize(validationBase.minSizeLimit)); placeholderMatch = message.match(/(\{\w+\})/g); if (placeholderMatch !== null) { qq.each(placeholderMatch, function(idx, placeholder) { r(placeholder, names[idx]); }); } this._options.callbacks.onError(null, name, message, undefined); return message; }, _manualRetry: function(id, callback) { if (this._onBeforeManualRetry(id)) { this._netUploadedOrQueued++; this._uploadData.setStatus(id, qq.status.UPLOAD_RETRYING); if (callback) { callback(id); } else { this._handler.retry(id); } return true; } }, _maybeAllComplete: function(id, status) { var self = this, notFinished = this._getNotFinished(); if (status === qq.status.UPLOAD_SUCCESSFUL) { this._succeededSinceLastAllComplete.push(id); } else if (status === qq.status.UPLOAD_FAILED) { this._failedSinceLastAllComplete.push(id); } if (notFinished === 0 && (this._succeededSinceLastAllComplete.length || this._failedSinceLastAllComplete.length)) { setTimeout(function() { self._onAllComplete(self._succeededSinceLastAllComplete, self._failedSinceLastAllComplete); }, 0); } }, _maybeHandleIos8SafariWorkaround: function() { var self = this; if (this._options.workarounds.ios8SafariUploads && qq.ios800() && qq.iosSafari()) { setTimeout(function() { window.alert(self._options.messages.unsupportedBrowserIos8Safari); }, 0); throw new qq.Error(this._options.messages.unsupportedBrowserIos8Safari); } }, _maybeParseAndSendUploadError: function(id, name, response, xhr) { if (!response.success) { if (xhr && xhr.status !== 200 && !response.error) { this._options.callbacks.onError(id, name, "XHR returned response code " + xhr.status, xhr); } else { var errorReason = response.error ? response.error : this._options.text.defaultResponseError; this._options.callbacks.onError(id, name, errorReason, xhr); } } }, _maybeProcessNextItemAfterOnValidateCallback: function(validItem, items, index, params, endpoint) { var self = this; if (items.length > index) { if (validItem || !this._options.validation.stopOnFirstInvalidFile) { setTimeout(function() { var validationDescriptor = self._getValidationDescriptor(items[index]), buttonId = self._getButtonId(items[index].file), button = self._getButton(buttonId); self._handleCheckedCallback({ name: "onValidate", callback: qq.bind(self._options.callbacks.onValidate, self, validationDescriptor, button), onSuccess: qq.bind(self._onValidateCallbackSuccess, self, items, index, params, endpoint), onFailure: qq.bind(self._onValidateCallbackFailure, self, items, index, params, endpoint), identifier: "Item '" + validationDescriptor.name + "', size: " + validationDescriptor.size }); }, 0); } else if (!validItem) { for (;index < items.length; index++) { self._fileOrBlobRejected(items[index].id); } } } }, _onAllComplete: function(successful, failed) { this._totalProgress && this._totalProgress.onAllComplete(successful, failed, this._preventRetries); this._options.callbacks.onAllComplete(qq.extend([], successful), qq.extend([], failed)); this._succeededSinceLastAllComplete = []; this._failedSinceLastAllComplete = []; }, _onAutoRetry: function(id, name, responseJSON, xhr, callback) { var self = this; self._preventRetries[id] = responseJSON[self._options.retry.preventRetryResponseProperty]; if (self._shouldAutoRetry(id, name, responseJSON)) { var retryWaitPeriod = self._options.retry.autoAttemptDelay * 1e3; self._maybeParseAndSendUploadError.apply(self, arguments); self._options.callbacks.onAutoRetry(id, name, self._autoRetries[id]); self._onBeforeAutoRetry(id, name); self._uploadData.setStatus(id, qq.status.UPLOAD_RETRYING); self._retryTimeouts[id] = setTimeout(function() { self.log("Starting retry for " + name + "..."); if (callback) { callback(id); } else { self._handler.retry(id); } }, retryWaitPeriod); return true; } }, _onBeforeAutoRetry: function(id, name) { this.log("Waiting " + this._options.retry.autoAttemptDelay + " seconds before retrying " + name + "..."); }, _onBeforeManualRetry: function(id) { var itemLimit = this._currentItemLimit, fileName; if (this._preventRetries[id]) { this.log("Retries are forbidden for id " + id, "warn"); return false; } else if (this._handler.isValid(id)) { fileName = this.getName(id); if (this._options.callbacks.onManualRetry(id, fileName) === false) { return false; } if (itemLimit > 0 && this._netUploadedOrQueued + 1 > itemLimit) { this._itemError("retryFailTooManyItems"); return false; } this.log("Retrying upload for '" + fileName + "' (id: " + id + ")..."); return true; } else { this.log("'" + id + "' is not a valid file ID", "error"); return false; } }, _onCancel: function(id, name) { this._netUploadedOrQueued--; clearTimeout(this._retryTimeouts[id]); var storedItemIndex = qq.indexOf(this._storedIds, id); if (!this._options.autoUpload && storedItemIndex >= 0) { this._storedIds.splice(storedItemIndex, 1); } this._uploadData.setStatus(id, qq.status.CANCELED); }, _onComplete: function(id, name, result, xhr) { if (!result.success) { this._netUploadedOrQueued--; this._uploadData.setStatus(id, qq.status.UPLOAD_FAILED); if (result[this._options.retry.preventRetryResponseProperty] === true) { this._preventRetries[id] = true; } } else { if (result.thumbnailUrl) { this._thumbnailUrls[id] = result.thumbnailUrl; } this._netUploaded++; this._uploadData.setStatus(id, qq.status.UPLOAD_SUCCESSFUL); } this._maybeParseAndSendUploadError(id, name, result, xhr); return result.success ? true : false; }, _onDelete: function(id) { this._uploadData.setStatus(id, qq.status.DELETING); }, _onDeleteComplete: function(id, xhrOrXdr, isError) { var name = this.getName(id); if (isError) { this._handleDeleteFailed(id, xhrOrXdr); } else { this._handleDeleteSuccess(id); } }, _onInputChange: function(input) { var fileIndex; if (qq.supportedFeatures.ajaxUploading) { for (fileIndex = 0; fileIndex < input.files.length; fileIndex++) { this._annotateWithButtonId(input.files[fileIndex], input); } this.addFiles(input.files); } else if (input.value.length > 0) { this.addFiles(input); } qq.each(this._buttons, function(idx, button) { button.reset(); }); }, _onProgress: function(id, name, loaded, total) { this._totalProgress && this._totalProgress.onIndividualProgress(id, loaded, total); }, _onSubmit: function(id, name) {}, _onSubmitCallbackSuccess: function(id, name) { this._onSubmit.apply(this, arguments); this._uploadData.setStatus(id, qq.status.SUBMITTED); this._onSubmitted.apply(this, arguments); if (this._options.autoUpload) { this._options.callbacks.onSubmitted.apply(this, arguments); this._uploadFile(id); } else { this._storeForLater(id); this._options.callbacks.onSubmitted.apply(this, arguments); } }, _onSubmitDelete: function(id, onSuccessCallback, additionalMandatedParams) { var uuid = this.getUuid(id), adjustedOnSuccessCallback; if (onSuccessCallback) { adjustedOnSuccessCallback = qq.bind(onSuccessCallback, this, id, uuid, additionalMandatedParams); } if (this._isDeletePossible()) { this._handleCheckedCallback({ name: "onSubmitDelete", callback: qq.bind(this._options.callbacks.onSubmitDelete, this, id), onSuccess: adjustedOnSuccessCallback || qq.bind(this._deleteHandler.sendDelete, this, id, uuid, additionalMandatedParams), identifier: id }); return true; } else { this.log("Delete request ignored for ID " + id + ", delete feature is disabled or request not possible " + "due to CORS on a user agent that does not support pre-flighting.", "warn"); return false; } }, _onSubmitted: function(id) {}, _onTotalProgress: function(loaded, total) { this._options.callbacks.onTotalProgress(loaded, total); }, _onUploadPrep: function(id) {}, _onUpload: function(id, name) { this._uploadData.setStatus(id, qq.status.UPLOADING); }, _onUploadChunk: function(id, chunkData) {}, _onUploadStatusChange: function(id, oldStatus, newStatus) { if (newStatus === qq.status.PAUSED) { clearTimeout(this._retryTimeouts[id]); } }, _onValidateBatchCallbackFailure: function(fileWrappers) { var self = this; qq.each(fileWrappers, function(idx, fileWrapper) { self._fileOrBlobRejected(fileWrapper.id); }); }, _onValidateBatchCallbackSuccess: function(validationDescriptors, items, params, endpoint, button) { var errorMessage, itemLimit = this._currentItemLimit, proposedNetFilesUploadedOrQueued = this._netUploadedOrQueued; if (itemLimit === 0 || proposedNetFilesUploadedOrQueued <= itemLimit) { if (items.length > 0) { this._handleCheckedCallback({ name: "onValidate", callback: qq.bind(this._options.callbacks.onValidate, this, validationDescriptors[0], button), onSuccess: qq.bind(this._onValidateCallbackSuccess, this, items, 0, params, endpoint), onFailure: qq.bind(this._onValidateCallbackFailure, this, items, 0, params, endpoint), identifier: "Item '" + items[0].file.name + "', size: " + items[0].file.size }); } else { this._itemError("noFilesError"); } } else { this._onValidateBatchCallbackFailure(items); errorMessage = this._options.messages.tooManyItemsError.replace(/\{netItems\}/g, proposedNetFilesUploadedOrQueued).replace(/\{itemLimit\}/g, itemLimit); this._batchError(errorMessage); } }, _onValidateCallbackFailure: function(items, index, params, endpoint) { var nextIndex = index + 1; this._fileOrBlobRejected(items[index].id, items[index].file.name); this._maybeProcessNextItemAfterOnValidateCallback(false, items, nextIndex, params, endpoint); }, _onValidateCallbackSuccess: function(items, index, params, endpoint) { var self = this, nextIndex = index + 1, validationDescriptor = this._getValidationDescriptor(items[index]); this._validateFileOrBlobData(items[index], validationDescriptor).then(function() { self._upload(items[index].id, params, endpoint); self._maybeProcessNextItemAfterOnValidateCallback(true, items, nextIndex, params, endpoint); }, function() { self._maybeProcessNextItemAfterOnValidateCallback(false, items, nextIndex, params, endpoint); }); }, _prepareItemsForUpload: function(items, params, endpoint) { if (items.length === 0) { this._itemError("noFilesError"); return; } var validationDescriptors = this._getValidationDescriptors(items), buttonId = this._getButtonId(items[0].file), button = this._getButton(buttonId); this._handleCheckedCallback({ name: "onValidateBatch", callback: qq.bind(this._options.callbacks.onValidateBatch, this, validationDescriptors, button), onSuccess: qq.bind(this._onValidateBatchCallbackSuccess, this, validationDescriptors, items, params, endpoint, button), onFailure: qq.bind(this._onValidateBatchCallbackFailure, this, items), identifier: "batch validation" }); }, _preventLeaveInProgress: function() { var self = this; this._disposeSupport.attach(window, "beforeunload", function(e) { if (self.getInProgress()) { e = e || window.event; e.returnValue = self._options.messages.onLeave; return self._options.messages.onLeave; } }); }, _refreshSessionData: function() { var self = this, options = this._options.session; if (qq.Session && this._options.session.endpoint != null) { if (!this._session) { qq.extend(options, { cors: this._options.cors }); options.log = qq.bind(this.log, this); options.addFileRecord = qq.bind(this._addCannedFile, this); this._session = new qq.Session(options); } setTimeout(function() { self._session.refresh().then(function(response, xhrOrXdr) { self._sessionRequestComplete(); self._options.callbacks.onSessionRequestComplete(response, true, xhrOrXdr); }, function(response, xhrOrXdr) { self._options.callbacks.onSessionRequestComplete(response, false, xhrOrXdr); }); }, 0); } }, _sessionRequestComplete: function() {}, _setSize: function(id, newSize) { this._uploadData.updateSize(id, newSize); this._totalProgress && this._totalProgress.onNewSize(id); }, _shouldAutoRetry: function(id, name, responseJSON) { var uploadData = this._uploadData.retrieve({ id: id }); if (!this._preventRetries[id] && this._options.retry.enableAuto && uploadData.status !== qq.status.PAUSED) { if (this._autoRetries[id] === undefined) { this._autoRetries[id] = 0; } if (this._autoRetries[id] < this._options.retry.maxAutoAttempts) { this._autoRetries[id] += 1; return true; } } return false; }, _storeForLater: function(id) { this._storedIds.push(id); }, _trackButton: function(id) { var buttonId; if (qq.supportedFeatures.ajaxUploading) { buttonId = this._handler.getFile(id).qqButtonId; } else { buttonId = this._getButtonId(this._handler.getInput(id)); } if (buttonId) { this._buttonIdsForFileIds[id] = buttonId; } }, _updateFormSupportAndParams: function(formElementOrId) { this._options.form.element = formElementOrId; this._formSupport = qq.FormSupport && new qq.FormSupport(this._options.form, qq.bind(this.uploadStoredFiles, this), qq.bind(this.log, this)); if (this._formSupport && this._formSupport.attachedToForm) { this._paramsStore.addReadOnly(null, this._formSupport.getFormInputsAsObject); this._options.autoUpload = this._formSupport.newAutoUpload; if (this._formSupport.newEndpoint) { this.setEndpoint(this._formSupport.newEndpoint); } } }, _upload: function(id, params, endpoint) { var name = this.getName(id); if (params) { this.setParams(params, id); } if (endpoint) { this.setEndpoint(endpoint, id); } this._handleCheckedCallback({ name: "onSubmit", callback: qq.bind(this._options.callbacks.onSubmit, this, id, name), onSuccess: qq.bind(this._onSubmitCallbackSuccess, this, id, name), onFailure: qq.bind(this._fileOrBlobRejected, this, id, name), identifier: id }); }, _uploadFile: function(id) { if (!this._handler.upload(id)) { this._uploadData.setStatus(id, qq.status.QUEUED); } }, _uploadStoredFiles: function() { var idToUpload, stillSubmitting, self = this; while (this._storedIds.length) { idToUpload = this._storedIds.shift(); this._uploadFile(idToUpload); } stillSubmitting = this.getUploads({ status: qq.status.SUBMITTING }).length; if (stillSubmitting) { qq.log("Still waiting for " + stillSubmitting + " files to clear submit queue. Will re-parse stored IDs array shortly."); setTimeout(function() { self._uploadStoredFiles(); }, 1e3); } }, _validateFileOrBlobData: function(fileWrapper, validationDescriptor) { var self = this, file = function() { if (fileWrapper.file instanceof qq.BlobProxy) { return fileWrapper.file.referenceBlob; } return fileWrapper.file; }(), name = validationDescriptor.name, size = validationDescriptor.size, buttonId = this._getButtonId(fileWrapper.file), validationBase = this._getValidationBase(buttonId), validityChecker = new qq.Promise(); validityChecker.then(function() {}, function() { self._fileOrBlobRejected(fileWrapper.id, name); }); if (qq.isFileOrInput(file) && !this._isAllowedExtension(validationBase.allowedExtensions, name)) { this._itemError("typeError", name, file); return validityChecker.failure(); } if (!this._options.validation.allowEmpty && size === 0) { this._itemError("emptyError", name, file); return validityChecker.failure(); } if (size > 0 && validationBase.sizeLimit && size > validationBase.sizeLimit) { this._itemError("sizeError", name, file); return validityChecker.failure(); } if (size > 0 && size < validationBase.minSizeLimit) { this._itemError("minSizeError", name, file); return validityChecker.failure(); } if (qq.ImageValidation && qq.supportedFeatures.imagePreviews && qq.isFile(file)) { new qq.ImageValidation(file, qq.bind(self.log, self)).validate(validationBase.image).then(validityChecker.success, function(errorCode) { self._itemError(errorCode + "ImageError", name, file); validityChecker.failure(); }); } else { validityChecker.success(); } return validityChecker; }, _wrapCallbacks: function() { var self, safeCallback, prop; self = this; safeCallback = function(name, callback, args) { var errorMsg; try { return callback.apply(self, args); } catch (exception) { errorMsg = exception.message || exception.toString(); self.log("Caught exception in '" + name + "' callback - " + errorMsg, "error"); } }; for (prop in this._options.callbacks) { (function() { var callbackName, callbackFunc; callbackName = prop; callbackFunc = self._options.callbacks[callbackName]; self._options.callbacks[callbackName] = function() { return safeCallback(callbackName, callbackFunc, arguments); }; })(); } } }; })(); (function() { "use strict"; qq.FineUploaderBasic = function(o) { var self = this; this._options = { debug: false, button: null, multiple: true, maxConnections: 3, disableCancelForFormUploads: false, autoUpload: true, request: { customHeaders: {}, endpoint: "/server/upload", filenameParam: "qqfilename", forceMultipart: true, inputName: "qqfile", method: "POST", params: {}, paramsInBody: true, totalFileSizeName: "qqtotalfilesize", uuidName: "qquuid" }, validation: { allowedExtensions: [], sizeLimit: 0, minSizeLimit: 0, itemLimit: 0, stopOnFirstInvalidFile: true, acceptFiles: null, image: { maxHeight: 0, maxWidth: 0, minHeight: 0, minWidth: 0 }, allowEmpty: false }, callbacks: { onSubmit: function(id, name) {}, onSubmitted: function(id, name) {}, onComplete: function(id, name, responseJSON, maybeXhr) {}, onAllComplete: function(successful, failed) {}, onCancel: function(id, name) {}, onUpload: function(id, name) {}, onUploadChunk: function(id, name, chunkData) {}, onUploadChunkSuccess: function(id, chunkData, responseJSON, xhr) {}, onResume: function(id, fileName, chunkData) {}, onProgress: function(id, name, loaded, total) {}, onTotalProgress: function(loaded, total) {}, onError: function(id, name, reason, maybeXhrOrXdr) {}, onAutoRetry: function(id, name, attemptNumber) {}, onManualRetry: function(id, name) {}, onValidateBatch: function(fileOrBlobData) {}, onValidate: function(fileOrBlobData) {}, onSubmitDelete: function(id) {}, onDelete: function(id) {}, onDeleteComplete: function(id, xhrOrXdr, isError) {}, onPasteReceived: function(blob) {}, onStatusChange: function(id, oldStatus, newStatus) {}, onSessionRequestComplete: function(response, success, xhrOrXdr) {} }, messages: { typeError: "{file} has an invalid extension. Valid extension(s): {extensions}.", sizeError: "{file} is too large, maximum file size is {sizeLimit}.", minSizeError: "{file} is too small, minimum file size is {minSizeLimit}.", emptyError: "{file} is empty, please select files again without it.", noFilesError: "No files to upload.", tooManyItemsError: "Too many items ({netItems}) would be uploaded. Item limit is {itemLimit}.", maxHeightImageError: "Image is too tall.", maxWidthImageError: "Image is too wide.", minHeightImageError: "Image is not tall enough.", minWidthImageError: "Image is not wide enough.", retryFailTooManyItems: "Retry failed - you have reached your file limit.", onLeave: "The files are being uploaded, if you leave now the upload will be canceled.", unsupportedBrowserIos8Safari: "Unrecoverable error - this browser does not permit file uploading of any kind due to serious bugs in iOS8 Safari. Please use iOS8 Chrome until Apple fixes these issues." }, retry: { enableAuto: false, maxAutoAttempts: 3, autoAttemptDelay: 5, preventRetryResponseProperty: "preventRetry" }, classes: { buttonHover: "qq-upload-button-hover", buttonFocus: "qq-upload-button-focus" }, chunking: { enabled: false, concurrent: { enabled: false }, mandatory: false, paramNames: { partIndex: "qqpartindex", partByteOffset: "qqpartbyteoffset", chunkSize: "qqchunksize", totalFileSize: "qqtotalfilesize", totalParts: "qqtotalparts" }, partSize: 2e6, success: { endpoint: null } }, resume: { enabled: false, recordsExpireIn: 7, paramNames: { resuming: "qqresume" } }, formatFileName: function(fileOrBlobName) { return fileOrBlobName; }, text: { defaultResponseError: "Upload failure reason unknown", fileInputTitle: "file input", sizeSymbols: [ "kB", "MB", "GB", "TB", "PB", "EB" ] }, deleteFile: { enabled: false, method: "DELETE", endpoint: "/server/upload", customHeaders: {}, params: {} }, cors: { expected: false, sendCredentials: false, allowXdr: false }, blobs: { defaultName: "misc_data" }, paste: { targetElement: null, defaultName: "pasted_image" }, camera: { ios: false, button: null }, extraButtons: [], session: { endpoint: null, params: {}, customHeaders: {}, refreshOnReset: true }, form: { element: "qq-form", autoUpload: false, interceptSubmit: true }, scaling: { customResizer: null, sendOriginal: true, orient: true, defaultType: null, defaultQuality: 80, failureText: "Failed to scale", includeExif: false, sizes: [] }, workarounds: { iosEmptyVideos: true, ios8SafariUploads: true, ios8BrowserCrash: false } }; qq.extend(this._options, o, true); this._buttons = []; this._extraButtonSpecs = {}; this._buttonIdsForFileIds = []; this._wrapCallbacks(); this._disposeSupport = new qq.DisposeSupport(); this._storedIds = []; this._autoRetries = []; this._retryTimeouts = []; this._preventRetries = []; this._thumbnailUrls = []; this._netUploadedOrQueued = 0; this._netUploaded = 0; this._uploadData = this._createUploadDataTracker(); this._initFormSupportAndParams(); this._customHeadersStore = this._createStore(this._options.request.customHeaders); this._deleteFileCustomHeadersStore = this._createStore(this._options.deleteFile.customHeaders); this._deleteFileParamsStore = this._createStore(this._options.deleteFile.params); this._endpointStore = this._createStore(this._options.request.endpoint); this._deleteFileEndpointStore = this._createStore(this._options.deleteFile.endpoint); this._handler = this._createUploadHandler(); this._deleteHandler = qq.DeleteFileAjaxRequester && this._createDeleteHandler(); if (this._options.button) { this._defaultButtonId = this._createUploadButton({ element: this._options.button, title: this._options.text.fileInputTitle }).getButtonId(); } this._generateExtraButtonSpecs(); this._handleCameraAccess(); if (this._options.paste.targetElement) { if (qq.PasteSupport) { this._pasteHandler = this._createPasteHandler(); } else { this.log("Paste support module not found", "error"); } } this._preventLeaveInProgress(); this._imageGenerator = qq.ImageGenerator && new qq.ImageGenerator(qq.bind(this.log, this)); this._refreshSessionData(); this._succeededSinceLastAllComplete = []; this._failedSinceLastAllComplete = []; this._scaler = qq.Scaler && new qq.Scaler(this._options.scaling, qq.bind(this.log, this)) || {}; if (this._scaler.enabled) { this._customNewFileHandler = qq.bind(this._scaler.handleNewFile, this._scaler); } if (qq.TotalProgress && qq.supportedFeatures.progressBar) { this._totalProgress = new qq.TotalProgress(qq.bind(this._onTotalProgress, this), function(id) { var entry = self._uploadData.retrieve({ id: id }); return entry && entry.size || 0; }); } this._currentItemLimit = this._options.validation.itemLimit; }; qq.FineUploaderBasic.prototype = qq.basePublicApi; qq.extend(qq.FineUploaderBasic.prototype, qq.basePrivateApi); })(); qq.AjaxRequester = function(o) { "use strict"; var log, shouldParamsBeInQueryString, queue = [], requestData = {}, options = { acceptHeader: null, validMethods: [ "PATCH", "POST", "PUT" ], method: "POST", contentType: "application/x-www-form-urlencoded", maxConnections: 3, customHeaders: {}, endpointStore: {}, paramsStore: {}, mandatedParams: {}, allowXRequestedWithAndCacheControl: true, successfulResponseCodes: { DELETE: [ 200, 202, 204 ], PATCH: [ 200, 201, 202, 203, 204 ], POST: [ 200, 201, 202, 203, 204 ], PUT: [ 200, 201, 202, 203, 204 ], GET: [ 200 ] }, cors: { expected: false, sendCredentials: false }, log: function(str, level) {}, onSend: function(id) {}, onComplete: function(id, xhrOrXdr, isError) {}, onProgress: null }; qq.extend(options, o); log = options.log; if (qq.indexOf(options.validMethods, options.method) < 0) { throw new Error("'" + options.method + "' is not a supported method for this type of request!"); } function isSimpleMethod() { return qq.indexOf([ "GET", "POST", "HEAD" ], options.method) >= 0; } function containsNonSimpleHeaders(headers) { var containsNonSimple = false; qq.each(containsNonSimple, function(idx, header) { if (qq.indexOf([ "Accept", "Accept-Language", "Content-Language", "Content-Type" ], header) < 0) { containsNonSimple = true; return false; } }); return containsNonSimple; } function isXdr(xhr) { return options.cors.expected && xhr.withCredentials === undefined; } function getCorsAjaxTransport() { var xhrOrXdr; if (window.XMLHttpRequest || window.ActiveXObject) { xhrOrXdr = qq.createXhrInstance(); if (xhrOrXdr.withCredentials === undefined) { xhrOrXdr = new XDomainRequest(); xhrOrXdr.onload = function() {}; xhrOrXdr.onerror = function() {}; xhrOrXdr.ontimeout = function() {}; xhrOrXdr.onprogress = function() {}; } } return xhrOrXdr; } function getXhrOrXdr(id, suppliedXhr) { var xhrOrXdr = requestData[id].xhr; if (!xhrOrXdr) { if (suppliedXhr) { xhrOrXdr = suppliedXhr; } else { if (options.cors.expected) { xhrOrXdr = getCorsAjaxTransport(); } else { xhrOrXdr = qq.createXhrInstance(); } } requestData[id].xhr = xhrOrXdr; } return xhrOrXdr; } function dequeue(id) { var i = qq.indexOf(queue, id), max = options.maxConnections, nextId; delete requestData[id]; queue.splice(i, 1); if (queue.length >= max && i < max) { nextId = queue[max - 1]; sendRequest(nextId); } } function onComplete(id, xdrError) { var xhr = getXhrOrXdr(id), method = options.method, isError = xdrError === true; dequeue(id); if (isError) { log(method + " request for " + id + " has failed", "error"); } else if (!isXdr(xhr) && !isResponseSuccessful(xhr.status)) { isError = true; log(method + " request for " + id + " has failed - response code " + xhr.status, "error"); } options.onComplete(id, xhr, isError); } function getParams(id) { var onDemandParams = requestData[id].additionalParams, mandatedParams = options.mandatedParams, params; if (options.paramsStore.get) { params = options.paramsStore.get(id); } if (onDemandParams) { qq.each(onDemandParams, function(name, val) { params = params || {}; params[name] = val; }); } if (mandatedParams) { qq.each(mandatedParams, function(name, val) { params = params || {}; params[name] = val; }); } return params; } function sendRequest(id, optXhr) { var xhr = getXhrOrXdr(id, optXhr), method = options.method, params = getParams(id), payload = requestData[id].payload, url; options.onSend(id); url = createUrl(id, params, requestData[id].additionalQueryParams); if (isXdr(xhr)) { xhr.onload = getXdrLoadHandler(id); xhr.onerror = getXdrErrorHandler(id); } else { xhr.onreadystatechange = getXhrReadyStateChangeHandler(id); } registerForUploadProgress(id); xhr.open(method, url, true); if (options.cors.expected && options.cors.sendCredentials && !isXdr(xhr)) { xhr.withCredentials = true; } setHeaders(id); log("Sending " + method + " request for " + id); if (payload) { xhr.send(payload); } else if (shouldParamsBeInQueryString || !params) { xhr.send(); } else if (params && options.contentType && options.contentType.toLowerCase().indexOf("application/x-www-form-urlencoded") >= 0) { xhr.send(qq.obj2url(params, "")); } else if (params && options.contentType && options.contentType.toLowerCase().indexOf("application/json") >= 0) { xhr.send(JSON.stringify(params)); } else { xhr.send(params); } return xhr; } function createUrl(id, params, additionalQueryParams) { var endpoint = options.endpointStore.get(id), addToPath = requestData[id].addToPath; if (addToPath != undefined) { endpoint += "/" + addToPath; } if (shouldParamsBeInQueryString && params) { endpoint = qq.obj2url(params, endpoint); } if (additionalQueryParams) { endpoint = qq.obj2url(additionalQueryParams, endpoint); } return endpoint; } function getXhrReadyStateChangeHandler(id) { return function() { if (getXhrOrXdr(id).readyState === 4) { onComplete(id); } }; } function registerForUploadProgress(id) { var onProgress = options.onProgress; if (onProgress) { getXhrOrXdr(id).upload.onprogress = function(e) { if (e.lengthComputable) { onProgress(id, e.loaded, e.total); } }; } } function getXdrLoadHandler(id) { return function() { onComplete(id); }; } function getXdrErrorHandler(id) { return function() { onComplete(id, true); }; } function setHeaders(id) { var xhr = getXhrOrXdr(id), customHeaders = options.customHeaders, onDemandHeaders = requestData[id].additionalHeaders || {}, method = options.method, allHeaders = {}; if (!isXdr(xhr)) { options.acceptHeader && xhr.setRequestHeader("Accept", options.acceptHeader); if (options.allowXRequestedWithAndCacheControl) { if (!options.cors.expected || (!isSimpleMethod() || containsNonSimpleHeaders(customHeaders))) { xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest"); xhr.setRequestHeader("Cache-Control", "no-cache"); } } if (options.contentType && (method === "POST" || method === "PUT")) { xhr.setRequestHeader("Content-Type", options.contentType); } qq.extend(allHeaders, qq.isFunction(customHeaders) ? customHeaders(id) : customHeaders); qq.extend(allHeaders, onDemandHeaders); qq.each(allHeaders, function(name, val) { xhr.setRequestHeader(name, val); }); } } function isResponseSuccessful(responseCode) { return qq.indexOf(options.successfulResponseCodes[options.method], responseCode) >= 0; } function prepareToSend(id, optXhr, addToPath, additionalParams, additionalQueryParams, additionalHeaders, payload) { requestData[id] = { addToPath: addToPath, additionalParams: additionalParams, additionalQueryParams: additionalQueryParams, additionalHeaders: additionalHeaders, payload: payload }; var len = queue.push(id); if (len <= options.maxConnections) { return sendRequest(id, optXhr); } } shouldParamsBeInQueryString = options.method === "GET" || options.method === "DELETE"; qq.extend(this, { initTransport: function(id) { var path, params, headers, payload, cacheBuster, additionalQueryParams; return { withPath: function(appendToPath) { path = appendToPath; return this; }, withParams: function(additionalParams) { params = additionalParams; return this; }, withQueryParams: function(_additionalQueryParams_) { additionalQueryParams = _additionalQueryParams_; return this; }, withHeaders: function(additionalHeaders) { headers = additionalHeaders; return this; }, withPayload: function(thePayload) { payload = thePayload; return this; }, withCacheBuster: function() { cacheBuster = true; return this; }, send: function(optXhr) { if (cacheBuster && qq.indexOf([ "GET", "DELETE" ], options.method) >= 0) { params.qqtimestamp = new Date().getTime(); } return prepareToSend(id, optXhr, path, params, additionalQueryParams, headers, payload); } }; }, canceled: function(id) { dequeue(id); } }); }; qq.UploadHandler = function(spec) { "use strict"; var proxy = spec.proxy, fileState = {}, onCancel = proxy.onCancel, getName = proxy.getName; qq.extend(this, { add: function(id, fileItem) { fileState[id] = fileItem; fileState[id].temp = {}; }, cancel: function(id) { var self = this, cancelFinalizationEffort = new qq.Promise(), onCancelRetVal = onCancel(id, getName(id), cancelFinalizationEffort); onCancelRetVal.then(function() { if (self.isValid(id)) { fileState[id].canceled = true; self.expunge(id); } cancelFinalizationEffort.success(); }); }, expunge: function(id) { delete fileState[id]; }, getThirdPartyFileId: function(id) { return fileState[id].key; }, isValid: function(id) { return fileState[id] !== undefined; }, reset: function() { fileState = {}; }, _getFileState: function(id) { return fileState[id]; }, _setThirdPartyFileId: function(id, thirdPartyFileId) { fileState[id].key = thirdPartyFileId; }, _wasCanceled: function(id) { return !!fileState[id].canceled; } }); }; qq.UploadHandlerController = function(o, namespace) { "use strict"; var controller = this, chunkingPossible = false, concurrentChunkingPossible = false, chunking, preventRetryResponse, log, handler, options = { paramsStore: {}, maxConnections: 3, chunking: { enabled: false, multiple: { enabled: false } }, log: function(str, level) {}, onProgress: function(id, fileName, loaded, total) {}, onComplete: function(id, fileName, response, xhr) {}, onCancel: function(id, fileName) {}, onUploadPrep: function(id) {}, onUpload: function(id, fileName) {}, onUploadChunk: function(id, fileName, chunkData) {}, onUploadChunkSuccess: function(id, chunkData, response, xhr) {}, onAutoRetry: function(id, fileName, response, xhr) {}, onResume: function(id, fileName, chunkData) {}, onUuidChanged: function(id, newUuid) {}, getName: function(id) {}, setSize: function(id, newSize) {}, isQueued: function(id) {}, getIdsInProxyGroup: function(id) {}, getIdsInBatch: function(id) {} }, chunked = { done: function(id, chunkIdx, response, xhr) { var chunkData = handler._getChunkData(id, chunkIdx); handler._getFileState(id).attemptingResume = false; delete handler._getFileState(id).temp.chunkProgress[chunkIdx]; handler._getFileState(id).loaded += chunkData.size; options.onUploadChunkSuccess(id, handler._getChunkDataForCallback(chunkData), response, xhr); }, finalize: function(id) { var size = options.getSize(id), name = options.getName(id); log("All chunks have been uploaded for " + id + " - finalizing...."); handler.finalizeChunks(id).then(function(response, xhr) { log("Finalize successful for " + id); var normaizedResponse = upload.normalizeResponse(response, true); options.onProgress(id, name, size, size); handler._maybeDeletePersistedChunkData(id); upload.cleanup(id, normaizedResponse, xhr); }, function(response, xhr) { var normaizedResponse = upload.normalizeResponse(response, false); log("Problem finalizing chunks for file ID " + id + " - " + normaizedResponse.error, "error"); if (normaizedResponse.reset) { chunked.reset(id); } if (!options.onAutoRetry(id, name, normaizedResponse, xhr)) { upload.cleanup(id, normaizedResponse, xhr); } }); }, handleFailure: function(chunkIdx, id, response, xhr) { var name = options.getName(id); log("Chunked upload request failed for " + id + ", chunk " + chunkIdx); handler.clearCachedChunk(id, chunkIdx); var responseToReport = upload.normalizeResponse(response, false), inProgressIdx; if (responseToReport.reset) { chunked.reset(id); } else { inProgressIdx = qq.indexOf(handler._getFileState(id).chunking.inProgress, chunkIdx); if (inProgressIdx >= 0) { handler._getFileState(id).chunking.inProgress.splice(inProgressIdx, 1); handler._getFileState(id).chunking.remaining.unshift(chunkIdx); } } if (!handler._getFileState(id).temp.ignoreFailure) { if (concurrentChunkingPossible) { handler._getFileState(id).temp.ignoreFailure = true; log(qq.format("Going to attempt to abort these chunks: {}. These are currently in-progress: {}.", JSON.stringify(Object.keys(handler._getXhrs(id))), JSON.stringify(handler._getFileState(id).chunking.inProgress))); qq.each(handler._getXhrs(id), function(ckid, ckXhr) { log(qq.format("Attempting to abort file {}.{}. XHR readyState {}. ", id, ckid, ckXhr.readyState)); ckXhr.abort(); ckXhr._cancelled = true; }); handler.moveInProgressToRemaining(id); connectionManager.free(id, true); } if (!options.onAutoRetry(id, name, responseToReport, xhr)) { upload.cleanup(id, responseToReport, xhr); } } }, hasMoreParts: function(id) { return !!handler._getFileState(id).chunking.remaining.length; }, nextPart: function(id) { var nextIdx = handler._getFileState(id).chunking.remaining.shift(); if (nextIdx >= handler._getTotalChunks(id)) { nextIdx = null; } return nextIdx; }, reset: function(id) { log("Server or callback has ordered chunking effort to be restarted on next attempt for item ID " + id, "error"); handler._maybeDeletePersistedChunkData(id); handler.reevaluateChunking(id); handler._getFileState(id).loaded = 0; }, sendNext: function(id) { var size = options.getSize(id), name = options.getName(id), chunkIdx = chunked.nextPart(id), chunkData = handler._getChunkData(id, chunkIdx), resuming = handler._getFileState(id).attemptingResume, inProgressChunks = handler._getFileState(id).chunking.inProgress || []; if (handler._getFileState(id).loaded == null) { handler._getFileState(id).loaded = 0; } if (resuming && options.onResume(id, name, chunkData) === false) { chunked.reset(id); chunkIdx = chunked.nextPart(id); chunkData = handler._getChunkData(id, chunkIdx); resuming = false; } if (chunkIdx == null && inProgressChunks.length === 0) { chunked.finalize(id); } else { log(qq.format("Sending chunked upload request for item {}.{}, bytes {}-{} of {}.", id, chunkIdx, chunkData.start + 1, chunkData.end, size)); options.onUploadChunk(id, name, handler._getChunkDataForCallback(chunkData)); inProgressChunks.push(chunkIdx); handler._getFileState(id).chunking.inProgress = inProgressChunks; if (concurrentChunkingPossible) { connectionManager.open(id, chunkIdx); } if (concurrentChunkingPossible && connectionManager.available() && handler._getFileState(id).chunking.remaining.length) { chunked.sendNext(id); } if (chunkData.blob.size === 0) { log(qq.format("Chunk {} for file {} will not be uploaded, zero sized chunk.", chunkIdx, id), "error"); chunked.handleFailure(chunkIdx, id, "File is no longer available", null); } else { handler.uploadChunk(id, chunkIdx, resuming).then(function success(response, xhr) { log("Chunked upload request succeeded for " + id + ", chunk " + chunkIdx); handler.clearCachedChunk(id, chunkIdx); var inProgressChunks = handler._getFileState(id).chunking.inProgress || [], responseToReport = upload.normalizeResponse(response, true), inProgressChunkIdx = qq.indexOf(inProgressChunks, chunkIdx); log(qq.format("Chunk {} for file {} uploaded successfully.", chunkIdx, id)); chunked.done(id, chunkIdx, responseToReport, xhr); if (inProgressChunkIdx >= 0) { inProgressChunks.splice(inProgressChunkIdx, 1); } handler._maybePersistChunkedState(id); if (!chunked.hasMoreParts(id) && inProgressChunks.length === 0) { chunked.finalize(id); } else if (chunked.hasMoreParts(id)) { chunked.sendNext(id); } else { log(qq.format("File ID {} has no more chunks to send and these chunk indexes are still marked as in-progress: {}", id, JSON.stringify(inProgressChunks))); } }, function failure(response, xhr) { chunked.handleFailure(chunkIdx, id, response, xhr); }).done(function() { handler.clearXhr(id, chunkIdx); }); } } } }, connectionManager = { _open: [], _openChunks: {}, _waiting: [], available: function() { var max = options.maxConnections, openChunkEntriesCount = 0, openChunksCount = 0; qq.each(connectionManager._openChunks, function(fileId, openChunkIndexes) { openChunkEntriesCount++; openChunksCount += openChunkIndexes.length; }); return max - (connectionManager._open.length - openChunkEntriesCount + openChunksCount); }, free: function(id, dontAllowNext) { var allowNext = !dontAllowNext, waitingIndex = qq.indexOf(connectionManager._waiting, id), connectionsIndex = qq.indexOf(connectionManager._open, id), nextId; delete connectionManager._openChunks[id]; if (upload.getProxyOrBlob(id) instanceof qq.BlobProxy) { log("Generated blob upload has ended for " + id + ", disposing generated blob."); delete handler._getFileState(id).file; } if (waitingIndex >= 0) { connectionManager._waiting.splice(waitingIndex, 1); } else if (allowNext && connectionsIndex >= 0) { connectionManager._open.splice(connectionsIndex, 1); nextId = connectionManager._waiting.shift(); if (nextId >= 0) { connectionManager._open.push(nextId); upload.start(nextId); } } }, getWaitingOrConnected: function() { var waitingOrConnected = []; qq.each(connectionManager._openChunks, function(fileId, chunks) { if (chunks && chunks.length) { waitingOrConnected.push(parseInt(fileId)); } }); qq.each(connectionManager._open, function(idx, fileId) { if (!connectionManager._openChunks[fileId]) { waitingOrConnected.push(parseInt(fileId)); } }); waitingOrConnected = waitingOrConnected.concat(connectionManager._waiting); return waitingOrConnected; }, isUsingConnection: function(id) { return qq.indexOf(connectionManager._open, id) >= 0; }, open: function(id, chunkIdx) { if (chunkIdx == null) { connectionManager._waiting.push(id); } if (connectionManager.available()) { if (chunkIdx == null) { connectionManager._waiting.pop(); connectionManager._open.push(id); } else { (function() { var openChunksEntry = connectionManager._openChunks[id] || []; openChunksEntry.push(chunkIdx); connectionManager._openChunks[id] = openChunksEntry; })(); } return true; } return false; }, reset: function() { connectionManager._waiting = []; connectionManager._open = []; } }, simple = { send: function(id, name) { handler._getFileState(id).loaded = 0; log("Sending simple upload request for " + id); handler.uploadFile(id).then(function(response, optXhr) { log("Simple upload request succeeded for " + id); var responseToReport = upload.normalizeResponse(response, true), size = options.getSize(id); options.onProgress(id, name, size, size); upload.maybeNewUuid(id, responseToReport); upload.cleanup(id, responseToReport, optXhr); }, function(response, optXhr) { log("Simple upload request failed for " + id); var responseToReport = upload.normalizeResponse(response, false); if (!options.onAutoRetry(id, name, responseToReport, optXhr)) { upload.cleanup(id, responseToReport, optXhr); } }); } }, upload = { cancel: function(id) { log("Cancelling " + id); options.paramsStore.remove(id); connectionManager.free(id); }, cleanup: function(id, response, optXhr) { var name = options.getName(id); options.onComplete(id, name, response, optXhr); if (handler._getFileState(id)) { handler._clearXhrs && handler._clearXhrs(id); } connectionManager.free(id); }, getProxyOrBlob: function(id) { return handler.getProxy && handler.getProxy(id) || handler.getFile && handler.getFile(id); }, initHandler: function() { var handlerType = namespace ? qq[namespace] : qq.traditional, handlerModuleSubtype = qq.supportedFeatures.ajaxUploading ? "Xhr" : "Form"; handler = new handlerType[handlerModuleSubtype + "UploadHandler"](options, { getDataByUuid: options.getDataByUuid, getName: options.getName, getSize: options.getSize, getUuid: options.getUuid, log: log, onCancel: options.onCancel, onProgress: options.onProgress, onUuidChanged: options.onUuidChanged }); if (handler._removeExpiredChunkingRecords) { handler._removeExpiredChunkingRecords(); } }, isDeferredEligibleForUpload: function(id) { return options.isQueued(id); }, maybeDefer: function(id, blob) { if (blob && !handler.getFile(id) && blob instanceof qq.BlobProxy) { options.onUploadPrep(id); log("Attempting to generate a blob on-demand for " + id); blob.create().then(function(generatedBlob) { log("Generated an on-demand blob for " + id); handler.updateBlob(id, generatedBlob); options.setSize(id, generatedBlob.size); handler.reevaluateChunking(id); upload.maybeSendDeferredFiles(id); }, function(errorMessage) { var errorResponse = {}; if (errorMessage) { errorResponse.error = errorMessage; } log(qq.format("Failed to generate blob for ID {}. Error message: {}.", id, errorMessage), "error"); options.onComplete(id, options.getName(id), qq.extend(errorResponse, preventRetryResponse), null); upload.maybeSendDeferredFiles(id); connectionManager.free(id); }); } else { return upload.maybeSendDeferredFiles(id); } return false; }, maybeSendDeferredFiles: function(id) { var idsInGroup = options.getIdsInProxyGroup(id), uploadedThisId = false; if (idsInGroup && idsInGroup.length) { log("Maybe ready to upload proxy group file " + id); qq.each(idsInGroup, function(idx, idInGroup) { if (upload.isDeferredEligibleForUpload(idInGroup) && !!handler.getFile(idInGroup)) { uploadedThisId = idInGroup === id; upload.now(idInGroup); } else if (upload.isDeferredEligibleForUpload(idInGroup)) { return false; } }); } else { uploadedThisId = true; upload.now(id); } return uploadedThisId; }, maybeNewUuid: function(id, response) { if (response.newUuid !== undefined) { options.onUuidChanged(id, response.newUuid); } }, normalizeResponse: function(originalResponse, successful) { var response = originalResponse; if (!qq.isObject(originalResponse)) { response = {}; if (qq.isString(originalResponse) && !successful) { response.error = originalResponse; } } response.success = successful; return response; }, now: function(id) { var name = options.getName(id); if (!controller.isValid(id)) { throw new qq.Error(id + " is not a valid file ID to upload!"); } options.onUpload(id, name); if (chunkingPossible && handler._shouldChunkThisFile(id)) { chunked.sendNext(id); } else { simple.send(id, name); } }, start: function(id) { var blobToUpload = upload.getProxyOrBlob(id); if (blobToUpload) { return upload.maybeDefer(id, blobToUpload); } else { upload.now(id); return true; } } }; qq.extend(this, { add: function(id, file) { handler.add.apply(this, arguments); }, upload: function(id) { if (connectionManager.open(id)) { return upload.start(id); } return false; }, retry: function(id) { if (concurrentChunkingPossible) { handler._getFileState(id).temp.ignoreFailure = false; } if (connectionManager.isUsingConnection(id)) { return upload.start(id); } else { return controller.upload(id); } }, cancel: function(id) { var cancelRetVal = handler.cancel(id); if (qq.isGenericPromise(cancelRetVal)) { cancelRetVal.then(function() { upload.cancel(id); }); } else if (cancelRetVal !== false) { upload.cancel(id); } }, cancelAll: function() { var waitingOrConnected = connectionManager.getWaitingOrConnected(), i; if (waitingOrConnected.length) { for (i = waitingOrConnected.length - 1; i >= 0; i--) { controller.cancel(waitingOrConnected[i]); } } connectionManager.reset(); }, getFile: function(id) { if (handler.getProxy && handler.getProxy(id)) { return handler.getProxy(id).referenceBlob; } return handler.getFile && handler.getFile(id); }, isProxied: function(id) { return !!(handler.getProxy && handler.getProxy(id)); }, getInput: function(id) { if (handler.getInput) { return handler.getInput(id); } }, reset: function() { log("Resetting upload handler"); controller.cancelAll(); connectionManager.reset(); handler.reset(); }, expunge: function(id) { if (controller.isValid(id)) { return handler.expunge(id); } }, isValid: function(id) { return handler.isValid(id); }, getResumableFilesData: function() { if (handler.getResumableFilesData) { return handler.getResumableFilesData(); } return []; }, getThirdPartyFileId: function(id) { if (controller.isValid(id)) { return handler.getThirdPartyFileId(id); } }, pause: function(id) { if (controller.isResumable(id) && handler.pause && controller.isValid(id) && handler.pause(id)) { connectionManager.free(id); handler.moveInProgressToRemaining(id); return true; } return false; }, isResumable: function(id) { return !!handler.isResumable && handler.isResumable(id); } }); qq.extend(options, o); log = options.log; chunkingPossible = options.chunking.enabled && qq.supportedFeatures.chunking; concurrentChunkingPossible = chunkingPossible && options.chunking.concurrent.enabled; preventRetryResponse = function() { var response = {}; response[options.preventRetryParam] = true; return response; }(); upload.initHandler(); }; qq.WindowReceiveMessage = function(o) { "use strict"; var options = { log: function(message, level) {} }, callbackWrapperDetachers = {}; qq.extend(options, o); qq.extend(this, { receiveMessage: function(id, callback) { var onMessageCallbackWrapper = function(event) { callback(event.data); }; if (window.postMessage) { callbackWrapperDetachers[id] = qq(window).attach("message", onMessageCallbackWrapper); } else { log("iframe message passing not supported in this browser!", "error"); } }, stopReceivingMessages: function(id) { if (window.postMessage) { var detacher = callbackWrapperDetachers[id]; if (detacher) { detacher(); } } } }); }; qq.FormUploadHandler = function(spec) { "use strict"; var options = spec.options, handler = this, proxy = spec.proxy, formHandlerInstanceId = qq.getUniqueId(), onloadCallbacks = {}, detachLoadEvents = {}, postMessageCallbackTimers = {}, isCors = options.isCors, inputName = options.inputName, getUuid = proxy.getUuid, log = proxy.log, corsMessageReceiver = new qq.WindowReceiveMessage({ log: log }); function expungeFile(id) { delete detachLoadEvents[id]; if (isCors) { clearTimeout(postMessageCallbackTimers[id]); delete postMessageCallbackTimers[id]; corsMessageReceiver.stopReceivingMessages(id); } var iframe = document.getElementById(handler._getIframeName(id)); if (iframe) { iframe.setAttribute("src", "javascript:false;"); qq(iframe).remove(); } } function getFileIdForIframeName(iframeName) { return iframeName.split("_")[0]; } function initIframeForUpload(name) { var iframe = qq.toElement("<iframe src='javascript:false;' name='" + name + "' />"); iframe.setAttribute("id", name); iframe.style.display = "none"; document.body.appendChild(iframe); return iframe; } function registerPostMessageCallback(iframe, callback) { var iframeName = iframe.id, fileId = getFileIdForIframeName(iframeName), uuid = getUuid(fileId); onloadCallbacks[uuid] = callback; detachLoadEvents[fileId] = qq(iframe).attach("load", function() { if (handler.getInput(fileId)) { log("Received iframe load event for CORS upload request (iframe name " + iframeName + ")"); postMessageCallbackTimers[iframeName] = setTimeout(function() { var errorMessage = "No valid message received from loaded iframe for iframe name " + iframeName; log(errorMessage, "error"); callback({ error: errorMessage }); }, 1e3); } }); corsMessageReceiver.receiveMessage(iframeName, function(message) { log("Received the following window message: '" + message + "'"); var fileId = getFileIdForIframeName(iframeName), response = handler._parseJsonResponse(message), uuid = response.uuid, onloadCallback; if (uuid && onloadCallbacks[uuid]) { log("Handling response for iframe name " + iframeName); clearTimeout(postMessageCallbackTimers[iframeName]); delete postMessageCallbackTimers[iframeName]; handler._detachLoadEvent(iframeName); onloadCallback = onloadCallbacks[uuid]; delete onloadCallbacks[uuid]; corsMessageReceiver.stopReceivingMessages(iframeName); onloadCallback(response); } else if (!uuid) { log("'" + message + "' does not contain a UUID - ignoring."); } }); } qq.extend(this, new qq.UploadHandler(spec)); qq.override(this, function(super_) { return { add: function(id, fileInput) { super_.add(id, { input: fileInput }); fileInput.setAttribute("name", inputName); if (fileInput.parentNode) { qq(fileInput).remove(); } }, expunge: function(id) { expungeFile(id); super_.expunge(id); }, isValid: function(id) { return super_.isValid(id) && handler._getFileState(id).input !== undefined; } }; }); qq.extend(this, { getInput: function(id) { return handler._getFileState(id).input; }, _attachLoadEvent: function(iframe, callback) { var responseDescriptor; if (isCors) { registerPostMessageCallback(iframe, callback); } else { detachLoadEvents[iframe.id] = qq(iframe).attach("load", function() { log("Received response for " + iframe.id); if (!iframe.parentNode) { return; } try { if (iframe.contentDocument && iframe.contentDocument.body && iframe.contentDocument.body.innerHTML == "false") { return; } } catch (error) { log("Error when attempting to access iframe during handling of upload response (" + error.message + ")", "error"); responseDescriptor = { success: false }; } callback(responseDescriptor); }); } }, _createIframe: function(id) { var iframeName = handler._getIframeName(id); return initIframeForUpload(iframeName); }, _detachLoadEvent: function(id) { if (detachLoadEvents[id] !== undefined) { detachLoadEvents[id](); delete detachLoadEvents[id]; } }, _getIframeName: function(fileId) { return fileId + "_" + formHandlerInstanceId; }, _initFormForUpload: function(spec) { var method = spec.method, endpoint = spec.endpoint, params = spec.params, paramsInBody = spec.paramsInBody, targetName = spec.targetName, form = qq.toElement("<form method='" + method + "' enctype='multipart/form-data'></form>"), url = endpoint; if (paramsInBody) { qq.obj2Inputs(params, form); } else { url = qq.obj2url(params, endpoint); } form.setAttribute("action", url); form.setAttribute("target", targetName); form.style.display = "none"; document.body.appendChild(form); return form; }, _parseJsonResponse: function(innerHtmlOrMessage) { var response = {}; try { response = qq.parseJson(innerHtmlOrMessage); } catch (error) { log("Error when attempting to parse iframe upload response (" + error.message + ")", "error"); } return response; } }); }; qq.XhrUploadHandler = function(spec) { "use strict"; var handler = this, namespace = spec.options.namespace, proxy = spec.proxy, chunking = spec.options.chunking, resume = spec.options.resume, chunkFiles = chunking && spec.options.chunking.enabled && qq.supportedFeatures.chunking, resumeEnabled = resume && spec.options.resume.enabled && chunkFiles && qq.supportedFeatures.resume, getName = proxy.getName, getSize = proxy.getSize, getUuid = proxy.getUuid, getEndpoint = proxy.getEndpoint, getDataByUuid = proxy.getDataByUuid, onUuidChanged = proxy.onUuidChanged, onProgress = proxy.onProgress, log = proxy.log; function abort(id) { qq.each(handler._getXhrs(id), function(xhrId, xhr) { var ajaxRequester = handler._getAjaxRequester(id, xhrId); xhr.onreadystatechange = null; xhr.upload.onprogress = null; xhr.abort(); ajaxRequester && ajaxRequester.canceled && ajaxRequester.canceled(id); }); } qq.extend(this, new qq.UploadHandler(spec)); qq.override(this, function(super_) { return { add: function(id, blobOrProxy) { if (qq.isFile(blobOrProxy) || qq.isBlob(blobOrProxy)) { super_.add(id, { file: blobOrProxy }); } else if (blobOrProxy instanceof qq.BlobProxy) { super_.add(id, { proxy: blobOrProxy }); } else { throw new Error("Passed obj is not a File, Blob, or proxy"); } handler._initTempState(id); resumeEnabled && handler._maybePrepareForResume(id); }, expunge: function(id) { abort(id); handler._maybeDeletePersistedChunkData(id); handler._clearXhrs(id); super_.expunge(id); } }; }); qq.extend(this, { clearCachedChunk: function(id, chunkIdx) { delete handler._getFileState(id).temp.cachedChunks[chunkIdx]; }, clearXhr: function(id, chunkIdx) { var tempState = handler._getFileState(id).temp; if (tempState.xhrs) { delete tempState.xhrs[chunkIdx]; } if (tempState.ajaxRequesters) { delete tempState.ajaxRequesters[chunkIdx]; } }, finalizeChunks: function(id, responseParser) { var lastChunkIdx = handler._getTotalChunks(id) - 1, xhr = handler._getXhr(id, lastChunkIdx); if (responseParser) { return new qq.Promise().success(responseParser(xhr), xhr); } return new qq.Promise().success({}, xhr); }, getFile: function(id) { return handler.isValid(id) && handler._getFileState(id).file; }, getProxy: function(id) { return handler.isValid(id) && handler._getFileState(id).proxy; }, getResumableFilesData: function() { var resumableFilesData = []; handler._iterateResumeRecords(function(key, uploadData) { handler.moveInProgressToRemaining(null, uploadData.chunking.inProgress, uploadData.chunking.remaining); var data = { name: uploadData.name, remaining: uploadData.chunking.remaining, size: uploadData.size, uuid: uploadData.uuid }; if (uploadData.key) { data.key = uploadData.key; } resumableFilesData.push(data); }); return resumableFilesData; }, isResumable: function(id) { return !!chunking && handler.isValid(id) && !handler._getFileState(id).notResumable; }, moveInProgressToRemaining: function(id, optInProgress, optRemaining) { var inProgress = optInProgress || handler._getFileState(id).chunking.inProgress, remaining = optRemaining || handler._getFileState(id).chunking.remaining; if (inProgress) { log(qq.format("Moving these chunks from in-progress {}, to remaining.", JSON.stringify(inProgress))); inProgress.reverse(); qq.each(inProgress, function(idx, chunkIdx) { remaining.unshift(chunkIdx); }); inProgress.length = 0; } }, pause: function(id) { if (handler.isValid(id)) { log(qq.format("Aborting XHR upload for {} '{}' due to pause instruction.", id, getName(id))); handler._getFileState(id).paused = true; abort(id); return true; } }, reevaluateChunking: function(id) { if (chunking && handler.isValid(id)) { var state = handler._getFileState(id), totalChunks, i; delete state.chunking; state.chunking = {}; totalChunks = handler._getTotalChunks(id); if (totalChunks > 1 || chunking.mandatory) { state.chunking.enabled = true; state.chunking.parts = totalChunks; state.chunking.remaining = []; for (i = 0; i < totalChunks; i++) { state.chunking.remaining.push(i); } handler._initTempState(id); } else { state.chunking.enabled = false; } } }, updateBlob: function(id, newBlob) { if (handler.isValid(id)) { handler._getFileState(id).file = newBlob; } }, _clearXhrs: function(id) { var tempState = handler._getFileState(id).temp; qq.each(tempState.ajaxRequesters, function(chunkId) { delete tempState.ajaxRequesters[chunkId]; }); qq.each(tempState.xhrs, function(chunkId) { delete tempState.xhrs[chunkId]; }); }, _createXhr: function(id, optChunkIdx) { return handler._registerXhr(id, optChunkIdx, qq.createXhrInstance()); }, _getAjaxRequester: function(id, optChunkIdx) { var chunkIdx = optChunkIdx == null ? -1 : optChunkIdx; return handler._getFileState(id).temp.ajaxRequesters[chunkIdx]; }, _getChunkData: function(id, chunkIndex) { var chunkSize = chunking.partSize, fileSize = getSize(id), fileOrBlob = handler.getFile(id), startBytes = chunkSize * chunkIndex, endBytes = startBytes + chunkSize >= fileSize ? fileSize : startBytes + chunkSize, totalChunks = handler._getTotalChunks(id), cachedChunks = this._getFileState(id).temp.cachedChunks, blob = cachedChunks[chunkIndex] || qq.sliceBlob(fileOrBlob, startBytes, endBytes); cachedChunks[chunkIndex] = blob; return { part: chunkIndex, start: startBytes, end: endBytes, count: totalChunks, blob: blob, size: endBytes - startBytes }; }, _getChunkDataForCallback: function(chunkData) { return { partIndex: chunkData.part, startByte: chunkData.start + 1, endByte: chunkData.end, totalParts: chunkData.count }; }, _getLocalStorageId: function(id) { var formatVersion = "5.0", name = getName(id), size = getSize(id), chunkSize = chunking.partSize, endpoint = getEndpoint(id); return qq.format("qq{}resume{}-{}-{}-{}-{}", namespace, formatVersion, name, size, chunkSize, endpoint); }, _getMimeType: function(id) { return handler.getFile(id).type; }, _getPersistableData: function(id) { return handler._getFileState(id).chunking; }, _getTotalChunks: function(id) { if (chunking) { var fileSize = getSize(id), chunkSize = chunking.partSize; return Math.ceil(fileSize / chunkSize); } }, _getXhr: function(id, optChunkIdx) { var chunkIdx = optChunkIdx == null ? -1 : optChunkIdx; return handler._getFileState(id).temp.xhrs[chunkIdx]; }, _getXhrs: function(id) { return handler._getFileState(id).temp.xhrs; }, _iterateResumeRecords: function(callback) { if (resumeEnabled) { qq.each(localStorage, function(key, item) { if (key.indexOf(qq.format("qq{}resume", namespace)) === 0) { var uploadData = JSON.parse(item); callback(key, uploadData); } }); } }, _initTempState: function(id) { handler._getFileState(id).temp = { ajaxRequesters: {}, chunkProgress: {}, xhrs: {}, cachedChunks: {} }; }, _markNotResumable: function(id) { handler._getFileState(id).notResumable = true; }, _maybeDeletePersistedChunkData: function(id) { var localStorageId; if (resumeEnabled && handler.isResumable(id)) { localStorageId = handler._getLocalStorageId(id); if (localStorageId && localStorage.getItem(localStorageId)) { localStorage.removeItem(localStorageId); return true; } } return false; }, _maybePrepareForResume: function(id) { var state = handler._getFileState(id), localStorageId, persistedData; if (resumeEnabled && state.key === undefined) { localStorageId = handler._getLocalStorageId(id); persistedData = localStorage.getItem(localStorageId); if (persistedData) { persistedData = JSON.parse(persistedData); if (getDataByUuid(persistedData.uuid)) { handler._markNotResumable(id); } else { log(qq.format("Identified file with ID {} and name of {} as resumable.", id, getName(id))); onUuidChanged(id, persistedData.uuid); state.key = persistedData.key; state.chunking = persistedData.chunking; state.loaded = persistedData.loaded; state.attemptingResume = true; handler.moveInProgressToRemaining(id); } } } }, _maybePersistChunkedState: function(id) { var state = handler._getFileState(id), localStorageId, persistedData; if (resumeEnabled && handler.isResumable(id)) { localStorageId = handler._getLocalStorageId(id); persistedData = { name: getName(id), size: getSize(id), uuid: getUuid(id), key: state.key, chunking: state.chunking, loaded: state.loaded, lastUpdated: Date.now() }; try { localStorage.setItem(localStorageId, JSON.stringify(persistedData)); } catch (error) { log(qq.format("Unable to save resume data for '{}' due to error: '{}'.", id, error.toString()), "warn"); } } }, _registerProgressHandler: function(id, chunkIdx, chunkSize) { var xhr = handler._getXhr(id, chunkIdx), name = getName(id), progressCalculator = { simple: function(loaded, total) { var fileSize = getSize(id); if (loaded === total) { onProgress(id, name, fileSize, fileSize); } else { onProgress(id, name, loaded >= fileSize ? fileSize - 1 : loaded, fileSize); } }, chunked: function(loaded, total) { var chunkProgress = handler._getFileState(id).temp.chunkProgress, totalSuccessfullyLoadedForFile = handler._getFileState(id).loaded, loadedForRequest = loaded, totalForRequest = total, totalFileSize = getSize(id), estActualChunkLoaded = loadedForRequest - (totalForRequest - chunkSize), totalLoadedForFile = totalSuccessfullyLoadedForFile; chunkProgress[chunkIdx] = estActualChunkLoaded; qq.each(chunkProgress, function(chunkIdx, chunkLoaded) { totalLoadedForFile += chunkLoaded; }); onProgress(id, name, totalLoadedForFile, totalFileSize); } }; xhr.upload.onprogress = function(e) { if (e.lengthComputable) { var type = chunkSize == null ? "simple" : "chunked"; progressCalculator[type](e.loaded, e.total); } }; }, _registerXhr: function(id, optChunkIdx, xhr, optAjaxRequester) { var xhrsId = optChunkIdx == null ? -1 : optChunkIdx, tempState = handler._getFileState(id).temp; tempState.xhrs = tempState.xhrs || {}; tempState.ajaxRequesters = tempState.ajaxRequesters || {}; tempState.xhrs[xhrsId] = xhr; if (optAjaxRequester) { tempState.ajaxRequesters[xhrsId] = optAjaxRequester; } return xhr; }, _removeExpiredChunkingRecords: function() { var expirationDays = resume.recordsExpireIn; handler._iterateResumeRecords(function(key, uploadData) { var expirationDate = new Date(uploadData.lastUpdated); expirationDate.setDate(expirationDate.getDate() + expirationDays); if (expirationDate.getTime() <= Date.now()) { log("Removing expired resume record with key " + key); localStorage.removeItem(key); } }); }, _shouldChunkThisFile: function(id) { var state = handler._getFileState(id); if (!state.chunking) { handler.reevaluateChunking(id); } return state.chunking.enabled; } }); }; qq.DeleteFileAjaxRequester = function(o) { "use strict"; var requester, options = { method: "DELETE", uuidParamName: "qquuid", endpointStore: {}, maxConnections: 3, customHeaders: function(id) { return {}; }, paramsStore: {}, cors: { expected: false, sendCredentials: false }, log: function(str, level) {}, onDelete: function(id) {}, onDeleteComplete: function(id, xhrOrXdr, isError) {} }; qq.extend(options, o); function getMandatedParams() { if (options.method.toUpperCase() === "POST") { return { _method: "DELETE" }; } return {}; } requester = qq.extend(this, new qq.AjaxRequester({ acceptHeader: "application/json", validMethods: [ "POST", "DELETE" ], method: options.method, endpointStore: options.endpointStore, paramsStore: options.paramsStore, mandatedParams: getMandatedParams(), maxConnections: options.maxConnections, customHeaders: function(id) { return options.customHeaders.get(id); }, log: options.log, onSend: options.onDelete, onComplete: options.onDeleteComplete, cors: options.cors })); qq.extend(this, { sendDelete: function(id, uuid, additionalMandatedParams) { var additionalOptions = additionalMandatedParams || {}; options.log("Submitting delete file request for " + id); if (options.method === "DELETE") { requester.initTransport(id).withPath(uuid).withParams(additionalOptions).send(); } else { additionalOptions[options.uuidParamName] = uuid; requester.initTransport(id).withParams(additionalOptions).send(); } } }); }; (function() { function detectSubsampling(img) { var iw = img.naturalWidth, ih = img.naturalHeight, canvas = document.createElement("canvas"), ctx; if (iw * ih > 1024 * 1024) { canvas.width = canvas.height = 1; ctx = canvas.getContext("2d"); ctx.drawImage(img, -iw + 1, 0); return ctx.getImageData(0, 0, 1, 1).data[3] === 0; } else { return false; } } function detectVerticalSquash(img, iw, ih) { var canvas = document.createElement("canvas"), sy = 0, ey = ih, py = ih, ctx, data, alpha, ratio; canvas.width = 1; canvas.height = ih; ctx = canvas.getContext("2d"); ctx.drawImage(img, 0, 0); data = ctx.getImageData(0, 0, 1, ih).data; while (py > sy) { alpha = data[(py - 1) * 4 + 3]; if (alpha === 0) { ey = py; } else { sy = py; } py = ey + sy >> 1; } ratio = py / ih; return ratio === 0 ? 1 : ratio; } function renderImageToDataURL(img, blob, options, doSquash) { var canvas = document.createElement("canvas"), mime = options.mime || "image/jpeg", promise = new qq.Promise(); renderImageToCanvas(img, blob, canvas, options, doSquash).then(function() { promise.success(canvas.toDataURL(mime, options.quality || .8)); }); return promise; } function maybeCalculateDownsampledDimensions(spec) { var maxPixels = 5241e3; if (!qq.ios()) { throw new qq.Error("Downsampled dimensions can only be reliably calculated for iOS!"); } if (spec.origHeight * spec.origWidth > maxPixels) { return { newHeight: Math.round(Math.sqrt(maxPixels * (spec.origHeight / spec.origWidth))), newWidth: Math.round(Math.sqrt(maxPixels * (spec.origWidth / spec.origHeight))) }; } } function renderImageToCanvas(img, blob, canvas, options, doSquash) { var iw = img.naturalWidth, ih = img.naturalHeight, width = options.width, height = options.height, ctx = canvas.getContext("2d"), promise = new qq.Promise(), modifiedDimensions; ctx.save(); if (options.resize) { return renderImageToCanvasWithCustomResizer({ blob: blob, canvas: canvas, image: img, imageHeight: ih, imageWidth: iw, orientation: options.orientation, resize: options.resize, targetHeight: height, targetWidth: width }); } if (!qq.supportedFeatures.unlimitedScaledImageSize) { modifiedDimensions = maybeCalculateDownsampledDimensions({ origWidth: width, origHeight: height }); if (modifiedDimensions) { qq.log(qq.format("Had to reduce dimensions due to device limitations from {}w / {}h to {}w / {}h", width, height, modifiedDimensions.newWidth, modifiedDimensions.newHeight), "warn"); width = modifiedDimensions.newWidth; height = modifiedDimensions.newHeight; } } transformCoordinate(canvas, width, height, options.orientation); if (qq.ios()) { (function() { if (detectSubsampling(img)) { iw /= 2; ih /= 2; } var d = 1024, tmpCanvas = document.createElement("canvas"), vertSquashRatio = doSquash ? detectVerticalSquash(img, iw, ih) : 1, dw = Math.ceil(d * width / iw), dh = Math.ceil(d * height / ih / vertSquashRatio), sy = 0, dy = 0, tmpCtx, sx, dx; tmpCanvas.width = tmpCanvas.height = d; tmpCtx = tmpCanvas.getContext("2d"); while (sy < ih) { sx = 0; dx = 0; while (sx < iw) { tmpCtx.clearRect(0, 0, d, d); tmpCtx.drawImage(img, -sx, -sy); ctx.drawImage(tmpCanvas, 0, 0, d, d, dx, dy, dw, dh); sx += d; dx += dw; } sy += d; dy += dh; } ctx.restore(); tmpCanvas = tmpCtx = null; })(); } else { ctx.drawImage(img, 0, 0, width, height); } canvas.qqImageRendered && canvas.qqImageRendered(); promise.success(); return promise; } function renderImageToCanvasWithCustomResizer(resizeInfo) { var blob = resizeInfo.blob, image = resizeInfo.image, imageHeight = resizeInfo.imageHeight, imageWidth = resizeInfo.imageWidth, orientation = resizeInfo.orientation, promise = new qq.Promise(), resize = resizeInfo.resize, sourceCanvas = document.createElement("canvas"), sourceCanvasContext = sourceCanvas.getContext("2d"), targetCanvas = resizeInfo.canvas, targetHeight = resizeInfo.targetHeight, targetWidth = resizeInfo.targetWidth; transformCoordinate(sourceCanvas, imageWidth, imageHeight, orientation); targetCanvas.height = targetHeight; targetCanvas.width = targetWidth; sourceCanvasContext.drawImage(image, 0, 0); resize({ blob: blob, height: targetHeight, image: image, sourceCanvas: sourceCanvas, targetCanvas: targetCanvas, width: targetWidth }).then(function success() { targetCanvas.qqImageRendered && targetCanvas.qqImageRendered(); promise.success(); }, promise.failure); return promise; } function transformCoordinate(canvas, width, height, orientation) { switch (orientation) { case 5: case 6: case 7: case 8: canvas.width = height; canvas.height = width; break; default: canvas.width = width; canvas.height = height; } var ctx = canvas.getContext("2d"); switch (orientation) { case 2: ctx.translate(width, 0); ctx.scale(-1, 1); break; case 3: ctx.translate(width, height); ctx.rotate(Math.PI); break; case 4: ctx.translate(0, height); ctx.scale(1, -1); break; case 5: ctx.rotate(.5 * Math.PI); ctx.scale(1, -1); break; case 6: ctx.rotate(.5 * Math.PI); ctx.translate(0, -height); break; case 7: ctx.rotate(.5 * Math.PI); ctx.translate(width, -height); ctx.scale(-1, 1); break; case 8: ctx.rotate(-.5 * Math.PI); ctx.translate(-width, 0); break; default: break; } } function MegaPixImage(srcImage, errorCallback) { var self = this; if (window.Blob && srcImage instanceof Blob) { (function() { var img = new Image(), URL = window.URL && window.URL.createObjectURL ? window.URL : window.webkitURL && window.webkitURL.createObjectURL ? window.webkitURL : null; if (!URL) { throw Error("No createObjectURL function found to create blob url"); } img.src = URL.createObjectURL(srcImage); self.blob = srcImage; srcImage = img; })(); } if (!srcImage.naturalWidth && !srcImage.naturalHeight) { srcImage.onload = function() { var listeners = self.imageLoadListeners; if (listeners) { self.imageLoadListeners = null; setTimeout(function() { for (var i = 0, len = listeners.length; i < len; i++) { listeners[i](); } }, 0); } }; srcImage.onerror = errorCallback; this.imageLoadListeners = []; } this.srcImage = srcImage; } MegaPixImage.prototype.render = function(target, options) { options = options || {}; var self = this, imgWidth = this.srcImage.naturalWidth, imgHeight = this.srcImage.naturalHeight, width = options.width, height = options.height, maxWidth = options.maxWidth, maxHeight = options.maxHeight, doSquash = !this.blob || this.blob.type === "image/jpeg", tagName = target.tagName.toLowerCase(), opt; if (this.imageLoadListeners) { this.imageLoadListeners.push(function() { self.render(target, options); }); return; } if (width && !height) { height = imgHeight * width / imgWidth << 0; } else if (height && !width) { width = imgWidth * height / imgHeight << 0; } else { width = imgWidth; height = imgHeight; } if (maxWidth && width > maxWidth) { width = maxWidth; height = imgHeight * width / imgWidth << 0; } if (maxHeight && height > maxHeight) { height = maxHeight; width = imgWidth * height / imgHeight << 0; } opt = { width: width, height: height }, qq.each(options, function(optionsKey, optionsValue) { opt[optionsKey] = optionsValue; }); if (tagName === "img") { (function() { var oldTargetSrc = target.src; renderImageToDataURL(self.srcImage, self.blob, opt, doSquash).then(function(dataUri) { target.src = dataUri; oldTargetSrc === target.src && target.onload(); }); })(); } else if (tagName === "canvas") { renderImageToCanvas(this.srcImage, this.blob, target, opt, doSquash); } if (typeof this.onrender === "function") { this.onrender(target); } }; qq.MegaPixImage = MegaPixImage; })(); qq.ImageGenerator = function(log) { "use strict"; function isImg(el) { return el.tagName.toLowerCase() === "img"; } function isCanvas(el) { return el.tagName.toLowerCase() === "canvas"; } function isImgCorsSupported() { return new Image().crossOrigin !== undefined; } function isCanvasSupported() { var canvas = document.createElement("canvas"); return canvas.getContext && canvas.getContext("2d"); } function determineMimeOfFileName(nameWithPath) { var pathSegments = nameWithPath.split("/"), name = pathSegments[pathSegments.length - 1].split("?")[0], extension = qq.getExtension(name); extension = extension && extension.toLowerCase(); switch (extension) { case "jpeg": case "jpg": return "image/jpeg"; case "png": return "image/png"; case "bmp": return "image/bmp"; case "gif": return "image/gif"; case "tiff": case "tif": return "image/tiff"; } } function isCrossOrigin(url) { var targetAnchor = document.createElement("a"), targetProtocol, targetHostname, targetPort; targetAnchor.href = url; targetProtocol = targetAnchor.protocol; targetPort = targetAnchor.port; targetHostname = targetAnchor.hostname; if (targetProtocol.toLowerCase() !== window.location.protocol.toLowerCase()) { return true; } if (targetHostname.toLowerCase() !== window.location.hostname.toLowerCase()) { return true; } if (targetPort !== window.location.port && !qq.ie()) { return true; } return false; } function registerImgLoadListeners(img, promise) { img.onload = function() { img.onload = null; img.onerror = null; promise.success(img); }; img.onerror = function() { img.onload = null; img.onerror = null; log("Problem drawing thumbnail!", "error"); promise.failure(img, "Problem drawing thumbnail!"); }; } function registerCanvasDrawImageListener(canvas, promise) { canvas.qqImageRendered = function() { promise.success(canvas); }; } function registerThumbnailRenderedListener(imgOrCanvas, promise) { var registered = isImg(imgOrCanvas) || isCanvas(imgOrCanvas); if (isImg(imgOrCanvas)) { registerImgLoadListeners(imgOrCanvas, promise); } else if (isCanvas(imgOrCanvas)) { registerCanvasDrawImageListener(imgOrCanvas, promise); } else { promise.failure(imgOrCanvas); log(qq.format("Element container of type {} is not supported!", imgOrCanvas.tagName), "error"); } return registered; } function draw(fileOrBlob, container, options) { var drawPreview = new qq.Promise(), identifier = new qq.Identify(fileOrBlob, log), maxSize = options.maxSize, orient = options.orient == null ? true : options.orient, megapixErrorHandler = function() { container.onerror = null; container.onload = null; log("Could not render preview, file may be too large!", "error"); drawPreview.failure(container, "Browser cannot render image!"); }; identifier.isPreviewable().then(function(mime) { var dummyExif = { parse: function() { return new qq.Promise().success(); } }, exif = orient ? new qq.Exif(fileOrBlob, log) : dummyExif, mpImg = new qq.MegaPixImage(fileOrBlob, megapixErrorHandler); if (registerThumbnailRenderedListener(container, drawPreview)) { exif.parse().then(function(exif) { var orientation = exif && exif.Orientation; mpImg.render(container, { maxWidth: maxSize, maxHeight: maxSize, orientation: orientation, mime: mime, resize: options.customResizeFunction }); }, function(failureMsg) { log(qq.format("EXIF data could not be parsed ({}). Assuming orientation = 1.", failureMsg)); mpImg.render(container, { maxWidth: maxSize, maxHeight: maxSize, mime: mime, resize: options.customResizeFunction }); }); } }, function() { log("Not previewable"); drawPreview.failure(container, "Not previewable"); }); return drawPreview; } function drawOnCanvasOrImgFromUrl(url, canvasOrImg, draw, maxSize, customResizeFunction) { var tempImg = new Image(), tempImgRender = new qq.Promise(); registerThumbnailRenderedListener(tempImg, tempImgRender); if (isCrossOrigin(url)) { tempImg.crossOrigin = "anonymous"; } tempImg.src = url; tempImgRender.then(function rendered() { registerThumbnailRenderedListener(canvasOrImg, draw); var mpImg = new qq.MegaPixImage(tempImg); mpImg.render(canvasOrImg, { maxWidth: maxSize, maxHeight: maxSize, mime: determineMimeOfFileName(url), resize: customResizeFunction }); }, draw.failure); } function drawOnImgFromUrlWithCssScaling(url, img, draw, maxSize) { registerThumbnailRenderedListener(img, draw); qq(img).css({ maxWidth: maxSize + "px", maxHeight: maxSize + "px" }); img.src = url; } function drawFromUrl(url, container, options) { var draw = new qq.Promise(), scale = options.scale, maxSize = scale ? options.maxSize : null; if (scale && isImg(container)) { if (isCanvasSupported()) { if (isCrossOrigin(url) && !isImgCorsSupported()) { drawOnImgFromUrlWithCssScaling(url, container, draw, maxSize); } else { drawOnCanvasOrImgFromUrl(url, container, draw, maxSize); } } else { drawOnImgFromUrlWithCssScaling(url, container, draw, maxSize); } } else if (isCanvas(container)) { drawOnCanvasOrImgFromUrl(url, container, draw, maxSize); } else if (registerThumbnailRenderedListener(container, draw)) { container.src = url; } return draw; } qq.extend(this, { generate: function(fileBlobOrUrl, container, options) { if (qq.isString(fileBlobOrUrl)) { log("Attempting to update thumbnail based on server response."); return drawFromUrl(fileBlobOrUrl, container, options || {}); } else { log("Attempting to draw client-side image preview."); return draw(fileBlobOrUrl, container, options || {}); } } }); this._testing = {}; this._testing.isImg = isImg; this._testing.isCanvas = isCanvas; this._testing.isCrossOrigin = isCrossOrigin; this._testing.determineMimeOfFileName = determineMimeOfFileName; }; qq.Exif = function(fileOrBlob, log) { "use strict"; var TAG_IDS = [ 274 ], TAG_INFO = { 274: { name: "Orientation", bytes: 2 } }; function parseLittleEndian(hex) { var result = 0, pow = 0; while (hex.length > 0) { result += parseInt(hex.substring(0, 2), 16) * Math.pow(2, pow); hex = hex.substring(2, hex.length); pow += 8; } return result; } function seekToApp1(offset, promise) { var theOffset = offset, thePromise = promise; if (theOffset === undefined) { theOffset = 2; thePromise = new qq.Promise(); } qq.readBlobToHex(fileOrBlob, theOffset, 4).then(function(hex) { var match = /^ffe([0-9])/.exec(hex), segmentLength; if (match) { if (match[1] !== "1") { segmentLength = parseInt(hex.slice(4, 8), 16); seekToApp1(theOffset + segmentLength + 2, thePromise); } else { thePromise.success(theOffset); } } else { thePromise.failure("No EXIF header to be found!"); } }); return thePromise; } function getApp1Offset() { var promise = new qq.Promise(); qq.readBlobToHex(fileOrBlob, 0, 6).then(function(hex) { if (hex.indexOf("ffd8") !== 0) { promise.failure("Not a valid JPEG!"); } else { seekToApp1().then(function(offset) { promise.success(offset); }, function(error) { promise.failure(error); }); } }); return promise; } function isLittleEndian(app1Start) { var promise = new qq.Promise(); qq.readBlobToHex(fileOrBlob, app1Start + 10, 2).then(function(hex) { promise.success(hex === "4949"); }); return promise; } function getDirEntryCount(app1Start, littleEndian) { var promise = new qq.Promise(); qq.readBlobToHex(fileOrBlob, app1Start + 18, 2).then(function(hex) { if (littleEndian) { return promise.success(parseLittleEndian(hex)); } else { promise.success(parseInt(hex, 16)); } }); return promise; } function getIfd(app1Start, dirEntries) { var offset = app1Start + 20, bytes = dirEntries * 12; return qq.readBlobToHex(fileOrBlob, offset, bytes); } function getDirEntries(ifdHex) { var entries = [], offset = 0; while (offset + 24 <= ifdHex.length) { entries.push(ifdHex.slice(offset, offset + 24)); offset += 24; } return entries; } function getTagValues(littleEndian, dirEntries) { var TAG_VAL_OFFSET = 16, tagsToFind = qq.extend([], TAG_IDS), vals = {}; qq.each(dirEntries, function(idx, entry) { var idHex = entry.slice(0, 4), id = littleEndian ? parseLittleEndian(idHex) : parseInt(idHex, 16), tagsToFindIdx = tagsToFind.indexOf(id), tagValHex, tagName, tagValLength; if (tagsToFindIdx >= 0) { tagName = TAG_INFO[id].name; tagValLength = TAG_INFO[id].bytes; tagValHex = entry.slice(TAG_VAL_OFFSET, TAG_VAL_OFFSET + tagValLength * 2); vals[tagName] = littleEndian ? parseLittleEndian(tagValHex) : parseInt(tagValHex, 16); tagsToFind.splice(tagsToFindIdx, 1); } if (tagsToFind.length === 0) { return false; } }); return vals; } qq.extend(this, { parse: function() { var parser = new qq.Promise(), onParseFailure = function(message) { log(qq.format("EXIF header parse failed: '{}' ", message)); parser.failure(message); }; getApp1Offset().then(function(app1Offset) { log(qq.format("Moving forward with EXIF header parsing for '{}'", fileOrBlob.name === undefined ? "blob" : fileOrBlob.name)); isLittleEndian(app1Offset).then(function(littleEndian) { log(qq.format("EXIF Byte order is {} endian", littleEndian ? "little" : "big")); getDirEntryCount(app1Offset, littleEndian).then(function(dirEntryCount) { log(qq.format("Found {} APP1 directory entries", dirEntryCount)); getIfd(app1Offset, dirEntryCount).then(function(ifdHex) { var dirEntries = getDirEntries(ifdHex), tagValues = getTagValues(littleEndian, dirEntries); log("Successfully parsed some EXIF tags"); parser.success(tagValues); }, onParseFailure); }, onParseFailure); }, onParseFailure); }, onParseFailure); return parser; } }); this._testing = {}; this._testing.parseLittleEndian = parseLittleEndian; }; qq.Identify = function(fileOrBlob, log) { "use strict"; function isIdentifiable(magicBytes, questionableBytes) { var identifiable = false, magicBytesEntries = [].concat(magicBytes); qq.each(magicBytesEntries, function(idx, magicBytesArrayEntry) { if (questionableBytes.indexOf(magicBytesArrayEntry) === 0) { identifiable = true; return false; } }); return identifiable; } qq.extend(this, { isPreviewable: function() { var self = this, identifier = new qq.Promise(), previewable = false, name = fileOrBlob.name === undefined ? "blob" : fileOrBlob.name; log(qq.format("Attempting to determine if {} can be rendered in this browser", name)); log("First pass: check type attribute of blob object."); if (this.isPreviewableSync()) { log("Second pass: check for magic bytes in file header."); qq.readBlobToHex(fileOrBlob, 0, 4).then(function(hex) { qq.each(self.PREVIEWABLE_MIME_TYPES, function(mime, bytes) { if (isIdentifiable(bytes, hex)) { if (mime !== "image/tiff" || qq.supportedFeatures.tiffPreviews) { previewable = true; identifier.success(mime); } return false; } }); log(qq.format("'{}' is {} able to be rendered in this browser", name, previewable ? "" : "NOT")); if (!previewable) { identifier.failure(); } }, function() { log("Error reading file w/ name '" + name + "'. Not able to be rendered in this browser."); identifier.failure(); }); } else { identifier.failure(); } return identifier; }, isPreviewableSync: function() { var fileMime = fileOrBlob.type, isRecognizedImage = qq.indexOf(Object.keys(this.PREVIEWABLE_MIME_TYPES), fileMime) >= 0, previewable = false, name = fileOrBlob.name === undefined ? "blob" : fileOrBlob.name; if (isRecognizedImage) { if (fileMime === "image/tiff") { previewable = qq.supportedFeatures.tiffPreviews; } else { previewable = true; } } !previewable && log(name + " is not previewable in this browser per the blob's type attr"); return previewable; } }); }; qq.Identify.prototype.PREVIEWABLE_MIME_TYPES = { "image/jpeg": "ffd8ff", "image/gif": "474946", "image/png": "89504e", "image/bmp": "424d", "image/tiff": [ "49492a00", "4d4d002a" ] }; qq.ImageValidation = function(blob, log) { "use strict"; function hasNonZeroLimits(limits) { var atLeastOne = false; qq.each(limits, function(limit, value) { if (value > 0) { atLeastOne = true; return false; } }); return atLeastOne; } function getWidthHeight() { var sizeDetermination = new qq.Promise(); new qq.Identify(blob, log).isPreviewable().then(function() { var image = new Image(), url = window.URL && window.URL.createObjectURL ? window.URL : window.webkitURL && window.webkitURL.createObjectURL ? window.webkitURL : null; if (url) { image.onerror = function() { log("Cannot determine dimensions for image. May be too large.", "error"); sizeDetermination.failure(); }; image.onload = function() { sizeDetermination.success({ width: this.width, height: this.height }); }; image.src = url.createObjectURL(blob); } else { log("No createObjectURL function available to generate image URL!", "error"); sizeDetermination.failure(); } }, sizeDetermination.failure); return sizeDetermination; } function getFailingLimit(limits, dimensions) { var failingLimit; qq.each(limits, function(limitName, limitValue) { if (limitValue > 0) { var limitMatcher = /(max|min)(Width|Height)/.exec(limitName), dimensionPropName = limitMatcher[2].charAt(0).toLowerCase() + limitMatcher[2].slice(1), actualValue = dimensions[dimensionPropName]; switch (limitMatcher[1]) { case "min": if (actualValue < limitValue) { failingLimit = limitName; return false; } break; case "max": if (actualValue > limitValue) { failingLimit = limitName; return false; } break; } } }); return failingLimit; } this.validate = function(limits) { var validationEffort = new qq.Promise(); log("Attempting to validate image."); if (hasNonZeroLimits(limits)) { getWidthHeight().then(function(dimensions) { var failingLimit = getFailingLimit(limits, dimensions); if (failingLimit) { validationEffort.failure(failingLimit); } else { validationEffort.success(); } }, validationEffort.success); } else { validationEffort.success(); } return validationEffort; }; }; qq.Session = function(spec) { "use strict"; var options = { endpoint: null, params: {}, customHeaders: {}, cors: {}, addFileRecord: function(sessionData) {}, log: function(message, level) {} }; qq.extend(options, spec, true); function isJsonResponseValid(response) { if (qq.isArray(response)) { return true; } options.log("Session response is not an array.", "error"); } function handleFileItems(fileItems, success, xhrOrXdr, promise) { var someItemsIgnored = false; success = success && isJsonResponseValid(fileItems); if (success) { qq.each(fileItems, function(idx, fileItem) { if (fileItem.uuid == null) { someItemsIgnored = true; options.log(qq.format("Session response item {} did not include a valid UUID - ignoring.", idx), "error"); } else if (fileItem.name == null) { someItemsIgnored = true; options.log(qq.format("Session response item {} did not include a valid name - ignoring.", idx), "error"); } else { try { options.addFileRecord(fileItem); return true; } catch (err) { someItemsIgnored = true; options.log(err.message, "error"); } } return false; }); } promise[success && !someItemsIgnored ? "success" : "failure"](fileItems, xhrOrXdr); } this.refresh = function() { var refreshEffort = new qq.Promise(), refreshCompleteCallback = function(response, success, xhrOrXdr) { handleFileItems(response, success, xhrOrXdr, refreshEffort); }, requesterOptions = qq.extend({}, options), requester = new qq.SessionAjaxRequester(qq.extend(requesterOptions, { onComplete: refreshCompleteCallback })); requester.queryServer(); return refreshEffort; }; }; qq.SessionAjaxRequester = function(spec) { "use strict"; var requester, options = { endpoint: null, customHeaders: {}, params: {}, cors: { expected: false, sendCredentials: false }, onComplete: function(response, success, xhrOrXdr) {}, log: function(str, level) {} }; qq.extend(options, spec); function onComplete(id, xhrOrXdr, isError) { var response = null; if (xhrOrXdr.responseText != null) { try { response = qq.parseJson(xhrOrXdr.responseText); } catch (err) { options.log("Problem parsing session response: " + err.message, "error"); isError = true; } } options.onComplete(response, !isError, xhrOrXdr); } requester = qq.extend(this, new qq.AjaxRequester({ acceptHeader: "application/json", validMethods: [ "GET" ], method: "GET", endpointStore: { get: function() { return options.endpoint; } }, customHeaders: options.customHeaders, log: options.log, onComplete: onComplete, cors: options.cors })); qq.extend(this, { queryServer: function() { var params = qq.extend({}, options.params); options.log("Session query request."); requester.initTransport("sessionRefresh").withParams(params).withCacheBuster().send(); } }); }; qq.Scaler = function(spec, log) { "use strict"; var self = this, customResizeFunction = spec.customResizer, includeOriginal = spec.sendOriginal, orient = spec.orient, defaultType = spec.defaultType, defaultQuality = spec.defaultQuality / 100, failedToScaleText = spec.failureText, includeExif = spec.includeExif, sizes = this._getSortedSizes(spec.sizes); qq.extend(this, { enabled: qq.supportedFeatures.scaling && sizes.length > 0, getFileRecords: function(originalFileUuid, originalFileName, originalBlobOrBlobData) { var self = this, records = [], originalBlob = originalBlobOrBlobData.blob ? originalBlobOrBlobData.blob : originalBlobOrBlobData, identifier = new qq.Identify(originalBlob, log); if (identifier.isPreviewableSync()) { qq.each(sizes, function(idx, sizeRecord) { var outputType = self._determineOutputType({ defaultType: defaultType, requestedType: sizeRecord.type, refType: originalBlob.type }); records.push({ uuid: qq.getUniqueId(), name: self._getName(originalFileName, { name: sizeRecord.name, type: outputType, refType: originalBlob.type }), blob: new qq.BlobProxy(originalBlob, qq.bind(self._generateScaledImage, self, { customResizeFunction: customResizeFunction, maxSize: sizeRecord.maxSize, orient: orient, type: outputType, quality: defaultQuality, failedText: failedToScaleText, includeExif: includeExif, log: log })) }); }); records.push({ uuid: originalFileUuid, name: originalFileName, size: originalBlob.size, blob: includeOriginal ? originalBlob : null }); } else { records.push({ uuid: originalFileUuid, name: originalFileName, size: originalBlob.size, blob: originalBlob }); } return records; }, handleNewFile: function(file, name, uuid, size, fileList, batchId, uuidParamName, api) { var self = this, buttonId = file.qqButtonId || file.blob && file.blob.qqButtonId, scaledIds = [], originalId = null, addFileToHandler = api.addFileToHandler, uploadData = api.uploadData, paramsStore = api.paramsStore, proxyGroupId = qq.getUniqueId(); qq.each(self.getFileRecords(uuid, name, file), function(idx, record) { var blobSize = record.size, id; if (record.blob instanceof qq.BlobProxy) { blobSize = -1; } id = uploadData.addFile({ uuid: record.uuid, name: record.name, size: blobSize, batchId: batchId, proxyGroupId: proxyGroupId }); if (record.blob instanceof qq.BlobProxy) { scaledIds.push(id); } else { originalId = id; } if (record.blob) { addFileToHandler(id, record.blob); fileList.push({ id: id, file: record.blob }); } else { uploadData.setStatus(id, qq.status.REJECTED); } }); if (originalId !== null) { qq.each(scaledIds, function(idx, scaledId) { var params = { qqparentuuid: uploadData.retrieve({ id: originalId }).uuid, qqparentsize: uploadData.retrieve({ id: originalId }).size }; params[uuidParamName] = uploadData.retrieve({ id: scaledId }).uuid; uploadData.setParentId(scaledId, originalId); paramsStore.addReadOnly(scaledId, params); }); if (scaledIds.length) { (function() { var param = {}; param[uuidParamName] = uploadData.retrieve({ id: originalId }).uuid; paramsStore.addReadOnly(originalId, param); })(); } } } }); }; qq.extend(qq.Scaler.prototype, { scaleImage: function(id, specs, api) { "use strict"; if (!qq.supportedFeatures.scaling) { throw new qq.Error("Scaling is not supported in this browser!"); } var scalingEffort = new qq.Promise(), log = api.log, file = api.getFile(id), uploadData = api.uploadData.retrieve({ id: id }), name = uploadData && uploadData.name, uuid = uploadData && uploadData.uuid, scalingOptions = { customResizer: specs.customResizer, sendOriginal: false, orient: specs.orient, defaultType: specs.type || null, defaultQuality: specs.quality, failedToScaleText: "Unable to scale", sizes: [ { name: "", maxSize: specs.maxSize } ] }, scaler = new qq.Scaler(scalingOptions, log); if (!qq.Scaler || !qq.supportedFeatures.imagePreviews || !file) { scalingEffort.failure(); log("Could not generate requested scaled image for " + id + ". " + "Scaling is either not possible in this browser, or the file could not be located.", "error"); } else { qq.bind(function() { var record = scaler.getFileRecords(uuid, name, file)[0]; if (record && record.blob instanceof qq.BlobProxy) { record.blob.create().then(scalingEffort.success, scalingEffort.failure); } else { log(id + " is not a scalable image!", "error"); scalingEffort.failure(); } }, this)(); } return scalingEffort; }, _determineOutputType: function(spec) { "use strict"; var requestedType = spec.requestedType, defaultType = spec.defaultType, referenceType = spec.refType; if (!defaultType && !requestedType) { if (referenceType !== "image/jpeg") { return "image/png"; } return referenceType; } if (!requestedType) { return defaultType; } if (qq.indexOf(Object.keys(qq.Identify.prototype.PREVIEWABLE_MIME_TYPES), requestedType) >= 0) { if (requestedType === "image/tiff") { return qq.supportedFeatures.tiffPreviews ? requestedType : defaultType; } return requestedType; } return defaultType; }, _getName: function(originalName, scaledVersionProperties) { "use strict"; var startOfExt = originalName.lastIndexOf("."), versionType = scaledVersionProperties.type || "image/png", referenceType = scaledVersionProperties.refType, scaledName = "", scaledExt = qq.getExtension(originalName), nameAppendage = ""; if (scaledVersionProperties.name && scaledVersionProperties.name.trim().length) { nameAppendage = " (" + scaledVersionProperties.name + ")"; } if (startOfExt >= 0) { scaledName = originalName.substr(0, startOfExt); if (referenceType !== versionType) { scaledExt = versionType.split("/")[1]; } scaledName += nameAppendage + "." + scaledExt; } else { scaledName = originalName + nameAppendage; } return scaledName; }, _getSortedSizes: function(sizes) { "use strict"; sizes = qq.extend([], sizes); return sizes.sort(function(a, b) { if (a.maxSize > b.maxSize) { return 1; } if (a.maxSize < b.maxSize) { return -1; } return 0; }); }, _generateScaledImage: function(spec, sourceFile) { "use strict"; var self = this, customResizeFunction = spec.customResizeFunction, log = spec.log, maxSize = spec.maxSize, orient = spec.orient, type = spec.type, quality = spec.quality, failedText = spec.failedText, includeExif = spec.includeExif && sourceFile.type === "image/jpeg" && type === "image/jpeg", scalingEffort = new qq.Promise(), imageGenerator = new qq.ImageGenerator(log), canvas = document.createElement("canvas"); log("Attempting to generate scaled version for " + sourceFile.name); imageGenerator.generate(sourceFile, canvas, { maxSize: maxSize, orient: orient, customResizeFunction: customResizeFunction }).then(function() { var scaledImageDataUri = canvas.toDataURL(type, quality), signalSuccess = function() { log("Success generating scaled version for " + sourceFile.name); var blob = qq.dataUriToBlob(scaledImageDataUri); scalingEffort.success(blob); }; if (includeExif) { self._insertExifHeader(sourceFile, scaledImageDataUri, log).then(function(scaledImageDataUriWithExif) { scaledImageDataUri = scaledImageDataUriWithExif; signalSuccess(); }, function() { log("Problem inserting EXIF header into scaled image. Using scaled image w/out EXIF data.", "error"); signalSuccess(); }); } else { signalSuccess(); } }, function() { log("Failed attempt to generate scaled version for " + sourceFile.name, "error"); scalingEffort.failure(failedText); }); return scalingEffort; }, _insertExifHeader: function(originalImage, scaledImageDataUri, log) { "use strict"; var reader = new FileReader(), insertionEffort = new qq.Promise(), originalImageDataUri = ""; reader.onload = function() { originalImageDataUri = reader.result; insertionEffort.success(qq.ExifRestorer.restore(originalImageDataUri, scaledImageDataUri)); }; reader.onerror = function() { log("Problem reading " + originalImage.name + " during attempt to transfer EXIF data to scaled version.", "error"); insertionEffort.failure(); }; reader.readAsDataURL(originalImage); return insertionEffort; }, _dataUriToBlob: function(dataUri) { "use strict"; var byteString, mimeString, arrayBuffer, intArray; if (dataUri.split(",")[0].indexOf("base64") >= 0) { byteString = atob(dataUri.split(",")[1]); } else { byteString = decodeURI(dataUri.split(",")[1]); } mimeString = dataUri.split(",")[0].split(":")[1].split(";")[0]; arrayBuffer = new ArrayBuffer(byteString.length); intArray = new Uint8Array(arrayBuffer); qq.each(byteString, function(idx, character) { intArray[idx] = character.charCodeAt(0); }); return this._createBlob(arrayBuffer, mimeString); }, _createBlob: function(data, mime) { "use strict"; var BlobBuilder = window.BlobBuilder || window.WebKitBlobBuilder || window.MozBlobBuilder || window.MSBlobBuilder, blobBuilder = BlobBuilder && new BlobBuilder(); if (blobBuilder) { blobBuilder.append(data); return blobBuilder.getBlob(mime); } else { return new Blob([ data ], { type: mime }); } } }); qq.ExifRestorer = function() { var ExifRestorer = {}; ExifRestorer.KEY_STR = "ABCDEFGHIJKLMNOP" + "QRSTUVWXYZabcdef" + "ghijklmnopqrstuv" + "wxyz0123456789+/" + "="; ExifRestorer.encode64 = function(input) { var output = "", chr1, chr2, chr3 = "", enc1, enc2, enc3, enc4 = "", i = 0; do { chr1 = input[i++]; chr2 = input[i++]; chr3 = input[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 + this.KEY_STR.charAt(enc1) + this.KEY_STR.charAt(enc2) + this.KEY_STR.charAt(enc3) + this.KEY_STR.charAt(enc4); chr1 = chr2 = chr3 = ""; enc1 = enc2 = enc3 = enc4 = ""; } while (i < input.length); return output; }; ExifRestorer.restore = function(origFileBase64, resizedFileBase64) { var expectedBase64Header = "data:image/jpeg;base64,"; if (!origFileBase64.match(expectedBase64Header)) { return resizedFileBase64; } var rawImage = this.decode64(origFileBase64.replace(expectedBase64Header, "")); var segments = this.slice2Segments(rawImage); var image = this.exifManipulation(resizedFileBase64, segments); return expectedBase64Header + this.encode64(image); }; ExifRestorer.exifManipulation = function(resizedFileBase64, segments) { var exifArray = this.getExifArray(segments), newImageArray = this.insertExif(resizedFileBase64, exifArray), aBuffer = new Uint8Array(newImageArray); return aBuffer; }; ExifRestorer.getExifArray = function(segments) { var seg; for (var x = 0; x < segments.length; x++) { seg = segments[x]; if (seg[0] == 255 & seg[1] == 225) { return seg; } } return []; }; ExifRestorer.insertExif = function(resizedFileBase64, exifArray) { var imageData = resizedFileBase64.replace("data:image/jpeg;base64,", ""), buf = this.decode64(imageData), separatePoint = buf.indexOf(255, 3), mae = buf.slice(0, separatePoint), ato = buf.slice(separatePoint), array = mae; array = array.concat(exifArray); array = array.concat(ato); return array; }; ExifRestorer.slice2Segments = function(rawImageArray) { var head = 0, segments = []; while (1) { if (rawImageArray[head] == 255 & rawImageArray[head + 1] == 218) { break; } if (rawImageArray[head] == 255 & rawImageArray[head + 1] == 216) { head += 2; } else { var length = rawImageArray[head + 2] * 256 + rawImageArray[head + 3], endPoint = head + length + 2, seg = rawImageArray.slice(head, endPoint); segments.push(seg); head = endPoint; } if (head > rawImageArray.length) { break; } } return segments; }; ExifRestorer.decode64 = function(input) { var output = "", chr1, chr2, chr3 = "", enc1, enc2, enc3, enc4 = "", i = 0, buf = []; var base64test = /[^A-Za-z0-9\+\/\=]/g; if (base64test.exec(input)) { throw new Error("There were invalid base64 characters in the input text. " + "Valid base64 characters are A-Z, a-z, 0-9, '+', '/',and '='"); } input = input.replace(/[^A-Za-z0-9\+\/\=]/g, ""); do { enc1 = this.KEY_STR.indexOf(input.charAt(i++)); enc2 = this.KEY_STR.indexOf(input.charAt(i++)); enc3 = this.KEY_STR.indexOf(input.charAt(i++)); enc4 = this.KEY_STR.indexOf(input.charAt(i++)); chr1 = enc1 << 2 | enc2 >> 4; chr2 = (enc2 & 15) << 4 | enc3 >> 2; chr3 = (enc3 & 3) << 6 | enc4; buf.push(chr1); if (enc3 != 64) { buf.push(chr2); } if (enc4 != 64) { buf.push(chr3); } chr1 = chr2 = chr3 = ""; enc1 = enc2 = enc3 = enc4 = ""; } while (i < input.length); return buf; }; return ExifRestorer; }(); qq.TotalProgress = function(callback, getSize) { "use strict"; var perFileProgress = {}, totalLoaded = 0, totalSize = 0, lastLoadedSent = -1, lastTotalSent = -1, callbackProxy = function(loaded, total) { if (loaded !== lastLoadedSent || total !== lastTotalSent) { callback(loaded, total); } lastLoadedSent = loaded; lastTotalSent = total; }, noRetryableFiles = function(failed, retryable) { var none = true; qq.each(failed, function(idx, failedId) { if (qq.indexOf(retryable, failedId) >= 0) { none = false; return false; } }); return none; }, onCancel = function(id) { updateTotalProgress(id, -1, -1); delete perFileProgress[id]; }, onAllComplete = function(successful, failed, retryable) { if (failed.length === 0 || noRetryableFiles(failed, retryable)) { callbackProxy(totalSize, totalSize); this.reset(); } }, onNew = function(id) { var size = getSize(id); if (size > 0) { updateTotalProgress(id, 0, size); perFileProgress[id] = { loaded: 0, total: size }; } }, updateTotalProgress = function(id, newLoaded, newTotal) { var oldLoaded = perFileProgress[id] ? perFileProgress[id].loaded : 0, oldTotal = perFileProgress[id] ? perFileProgress[id].total : 0; if (newLoaded === -1 && newTotal === -1) { totalLoaded -= oldLoaded; totalSize -= oldTotal; } else { if (newLoaded) { totalLoaded += newLoaded - oldLoaded; } if (newTotal) { totalSize += newTotal - oldTotal; } } callbackProxy(totalLoaded, totalSize); }; qq.extend(this, { onAllComplete: onAllComplete, onStatusChange: function(id, oldStatus, newStatus) { if (newStatus === qq.status.CANCELED || newStatus === qq.status.REJECTED) { onCancel(id); } else if (newStatus === qq.status.SUBMITTING) { onNew(id); } }, onIndividualProgress: function(id, loaded, total) { updateTotalProgress(id, loaded, total); perFileProgress[id] = { loaded: loaded, total: total }; }, onNewSize: function(id) { onNew(id); }, reset: function() { perFileProgress = {}; totalLoaded = 0; totalSize = 0; } }); }; qq.PasteSupport = function(o) { "use strict"; var options, detachPasteHandler; options = { targetElement: null, callbacks: { log: function(message, level) {}, pasteReceived: function(blob) {} } }; function isImage(item) { return item.type && item.type.indexOf("image/") === 0; } function registerPasteHandler() { detachPasteHandler = qq(options.targetElement).attach("paste", function(event) { var clipboardData = event.clipboardData; if (clipboardData) { qq.each(clipboardData.items, function(idx, item) { if (isImage(item)) { var blob = item.getAsFile(); options.callbacks.pasteReceived(blob); } }); } }); } function unregisterPasteHandler() { if (detachPasteHandler) { detachPasteHandler(); } } qq.extend(options, o); registerPasteHandler(); qq.extend(this, { reset: function() { unregisterPasteHandler(); } }); }; qq.FormSupport = function(options, startUpload, log) { "use strict"; var self = this, interceptSubmit = options.interceptSubmit, formEl = options.element, autoUpload = options.autoUpload; qq.extend(this, { newEndpoint: null, newAutoUpload: autoUpload, attachedToForm: false, getFormInputsAsObject: function() { if (formEl == null) { return null; } return self._form2Obj(formEl); } }); function determineNewEndpoint(formEl) { if (formEl.getAttribute("action")) { self.newEndpoint = formEl.getAttribute("action"); } } function validateForm(formEl, nativeSubmit) { if (formEl.checkValidity && !formEl.checkValidity()) { log("Form did not pass validation checks - will not upload.", "error"); nativeSubmit(); } else { return true; } } function maybeUploadOnSubmit(formEl) { var nativeSubmit = formEl.submit; qq(formEl).attach("submit", function(event) { event = event || window.event; if (event.preventDefault) { event.preventDefault(); } else { event.returnValue = false; } validateForm(formEl, nativeSubmit) && startUpload(); }); formEl.submit = function() { validateForm(formEl, nativeSubmit) && startUpload(); }; } function determineFormEl(formEl) { if (formEl) { if (qq.isString(formEl)) { formEl = document.getElementById(formEl); } if (formEl) { log("Attaching to form element."); determineNewEndpoint(formEl); interceptSubmit && maybeUploadOnSubmit(formEl); } } return formEl; } formEl = determineFormEl(formEl); this.attachedToForm = !!formEl; }; qq.extend(qq.FormSupport.prototype, { _form2Obj: function(form) { "use strict"; var obj = {}, notIrrelevantType = function(type) { var irrelevantTypes = [ "button", "image", "reset", "submit" ]; return qq.indexOf(irrelevantTypes, type.toLowerCase()) < 0; }, radioOrCheckbox = function(type) { return qq.indexOf([ "checkbox", "radio" ], type.toLowerCase()) >= 0; }, ignoreValue = function(el) { if (radioOrCheckbox(el.type) && !el.checked) { return true; } return el.disabled && el.type.toLowerCase() !== "hidden"; }, selectValue = function(select) { var value = null; qq.each(qq(select).children(), function(idx, child) { if (child.tagName.toLowerCase() === "option" && child.selected) { value = child.value; return false; } }); return value; }; qq.each(form.elements, function(idx, el) { if ((qq.isInput(el, true) || el.tagName.toLowerCase() === "textarea") && notIrrelevantType(el.type) && !ignoreValue(el)) { obj[el.name] = el.value; } else if (el.tagName.toLowerCase() === "select" && !ignoreValue(el)) { var value = selectValue(el); if (value !== null) { obj[el.name] = value; } } }); return obj; } }); qq.azure = qq.azure || {}; qq.azure.util = qq.azure.util || function() { "use strict"; return { AZURE_PARAM_PREFIX: "x-ms-meta-", _paramNameMatchesAzureParameter: function(name) { switch (name) { case "Cache-Control": case "Content-Disposition": case "Content-Encoding": case "Content-MD5": case "x-ms-blob-content-encoding": case "x-ms-blob-content-disposition": case "x-ms-blob-content-md5": case "x-ms-blob-cache-control": return true; default: return false; } }, _getPrefixedParamName: function(name) { if (qq.azure.util._paramNameMatchesAzureParameter(name)) { return name; } else { return qq.azure.util.AZURE_PARAM_PREFIX + name; } }, getParamsAsHeaders: function(params) { var headers = {}; qq.each(params, function(name, val) { var headerName = qq.azure.util._getPrefixedParamName(name), value = null; if (qq.isFunction(val)) { value = String(val()); } else if (qq.isObject(val)) { qq.extend(headers, qq.azure.util.getParamsAsHeaders(val)); } else { value = String(val); } if (value !== null) { if (qq.azure.util._paramNameMatchesAzureParameter(name)) { headers[headerName] = value; } else { headers[headerName] = encodeURIComponent(value); } } }); return headers; }, parseAzureError: function(responseText, log) { var domParser = new DOMParser(), responseDoc = domParser.parseFromString(responseText, "application/xml"), errorTag = responseDoc.getElementsByTagName("Error")[0], errorDetails = {}, codeTag, messageTag; log("Received error response: " + responseText, "error"); if (errorTag) { messageTag = errorTag.getElementsByTagName("Message")[0]; if (messageTag) { errorDetails.message = messageTag.textContent; } codeTag = errorTag.getElementsByTagName("Code")[0]; if (codeTag) { errorDetails.code = codeTag.textContent; } log("Parsed Azure error: " + JSON.stringify(errorDetails), "error"); return errorDetails; } } }; }(); (function() { "use strict"; qq.nonTraditionalBasePublicApi = { setUploadSuccessParams: function(params, id) { this._uploadSuccessParamsStore.set(params, id); }, setUploadSuccessEndpoint: function(endpoint, id) { this._uploadSuccessEndpointStore.set(endpoint, id); } }; qq.nonTraditionalBasePrivateApi = { _onComplete: function(id, name, result, xhr) { var success = result.success ? true : false, self = this, onCompleteArgs = arguments, successEndpoint = this._uploadSuccessEndpointStore.get(id), successCustomHeaders = this._options.uploadSuccess.customHeaders, successMethod = this._options.uploadSuccess.method, cors = this._options.cors, promise = new qq.Promise(), uploadSuccessParams = this._uploadSuccessParamsStore.get(id), fileParams = this._paramsStore.get(id), onSuccessFromServer = function(successRequestResult) { delete self._failedSuccessRequestCallbacks[id]; qq.extend(result, successRequestResult); qq.FineUploaderBasic.prototype._onComplete.apply(self, onCompleteArgs); promise.success(successRequestResult); }, onFailureFromServer = function(successRequestResult) { var callback = submitSuccessRequest; qq.extend(result, successRequestResult); if (result && result.reset) { callback = null; } if (!callback) { delete self._failedSuccessRequestCallbacks[id]; } else { self._failedSuccessRequestCallbacks[id] = callback; } if (!self._onAutoRetry(id, name, result, xhr, callback)) { qq.FineUploaderBasic.prototype._onComplete.apply(self, onCompleteArgs); promise.failure(successRequestResult); } }, submitSuccessRequest, successAjaxRequester; if (success && successEndpoint) { successAjaxRequester = new qq.UploadSuccessAjaxRequester({ endpoint: successEndpoint, method: successMethod, customHeaders: successCustomHeaders, cors: cors, log: qq.bind(this.log, this) }); qq.extend(uploadSuccessParams, self._getEndpointSpecificParams(id, result, xhr), true); fileParams && qq.extend(uploadSuccessParams, fileParams, true); submitSuccessRequest = qq.bind(function() { successAjaxRequester.sendSuccessRequest(id, uploadSuccessParams).then(onSuccessFromServer, onFailureFromServer); }, self); submitSuccessRequest(); return promise; } return qq.FineUploaderBasic.prototype._onComplete.apply(this, arguments); }, _manualRetry: function(id) { var successRequestCallback = this._failedSuccessRequestCallbacks[id]; return qq.FineUploaderBasic.prototype._manualRetry.call(this, id, successRequestCallback); } }; })(); (function() { "use strict"; qq.azure.FineUploaderBasic = function(o) { if (!qq.supportedFeatures.ajaxUploading) { throw new qq.Error("Uploading directly to Azure is not possible in this browser."); } var options = { signature: { endpoint: null, customHeaders: {} }, blobProperties: { name: "uuid" }, uploadSuccess: { endpoint: null, method: "POST", params: {}, customHeaders: {} }, chunking: { partSize: 4e6, minFileSize: 4000001 } }; qq.extend(options, o, true); qq.FineUploaderBasic.call(this, options); this._uploadSuccessParamsStore = this._createStore(this._options.uploadSuccess.params); this._uploadSuccessEndpointStore = this._createStore(this._options.uploadSuccess.endpoint); this._failedSuccessRequestCallbacks = {}; this._cannedBlobNames = {}; }; qq.extend(qq.azure.FineUploaderBasic.prototype, qq.basePublicApi); qq.extend(qq.azure.FineUploaderBasic.prototype, qq.basePrivateApi); qq.extend(qq.azure.FineUploaderBasic.prototype, qq.nonTraditionalBasePublicApi); qq.extend(qq.azure.FineUploaderBasic.prototype, qq.nonTraditionalBasePrivateApi); qq.extend(qq.azure.FineUploaderBasic.prototype, { getBlobName: function(id) { if (this._cannedBlobNames[id] == null) { return this._handler.getThirdPartyFileId(id); } return this._cannedBlobNames[id]; }, _getEndpointSpecificParams: function(id) { return { blob: this.getBlobName(id), uuid: this.getUuid(id), name: this.getName(id), container: this._endpointStore.get(id) }; }, _createUploadHandler: function() { return qq.FineUploaderBasic.prototype._createUploadHandler.call(this, { signature: this._options.signature, onGetBlobName: qq.bind(this._determineBlobName, this), deleteBlob: qq.bind(this._deleteBlob, this, true) }, "azure"); }, _determineBlobName: function(id) { var self = this, blobNameOptionValue = this._options.blobProperties.name, uuid = this.getUuid(id), filename = this.getName(id), fileExtension = qq.getExtension(filename), blobNameToUse = uuid; if (qq.isString(blobNameOptionValue)) { switch (blobNameOptionValue) { case "uuid": if (fileExtension !== undefined) { blobNameToUse += "." + fileExtension; } return new qq.Promise().success(blobNameToUse); case "filename": return new qq.Promise().success(filename); default: return new qq.Promise.failure("Invalid blobName option value - " + blobNameOptionValue); } } else { return blobNameOptionValue.call(this, id); } }, _addCannedFile: function(sessionData) { var id; if (sessionData.blobName == null) { throw new qq.Error("Did not find blob name property in server session response. This is required!"); } else { id = qq.FineUploaderBasic.prototype._addCannedFile.apply(this, arguments); this._cannedBlobNames[id] = sessionData.blobName; } return id; }, _deleteBlob: function(relatedToCancel, id) { var self = this, deleteBlobSasUri = {}, blobUriStore = { get: function(id) { return self._endpointStore.get(id) + "/" + self.getBlobName(id); } }, deleteFileEndpointStore = { get: function(id) { return deleteBlobSasUri[id]; } }, getSasSuccess = function(id, sasUri) { deleteBlobSasUri[id] = sasUri; deleteBlob.send(id); }, getSasFailure = function(id, reason, xhr) { if (relatedToCancel) { self.log("Will cancel upload, but cannot remove uncommitted parts from Azure due to issue retrieving SAS", "error"); qq.FineUploaderBasic.prototype._onCancel.call(self, id, self.getName(id)); } else { self._onDeleteComplete(id, xhr, true); self._options.callbacks.onDeleteComplete(id, xhr, true); } }, deleteBlob = new qq.azure.DeleteBlob({ endpointStore: deleteFileEndpointStore, log: qq.bind(self.log, self), onDelete: function(id) { self._onDelete(id); self._options.callbacks.onDelete(id); }, onDeleteComplete: function(id, xhrOrXdr, isError) { delete deleteBlobSasUri[id]; if (isError) { if (relatedToCancel) { self.log("Will cancel upload, but failed to remove uncommitted parts from Azure.", "error"); } else { qq.azure.util.parseAzureError(xhrOrXdr.responseText, qq.bind(self.log, self)); } } if (relatedToCancel) { qq.FineUploaderBasic.prototype._onCancel.call(self, id, self.getName(id)); self.log("Deleted uncommitted blob chunks for " + id); } else { self._onDeleteComplete(id, xhrOrXdr, isError); self._options.callbacks.onDeleteComplete(id, xhrOrXdr, isError); } } }), getSas = new qq.azure.GetSas({ cors: this._options.cors, customHeaders: this._options.signature.customHeaders, endpointStore: { get: function() { return self._options.signature.endpoint; } }, restRequestVerb: deleteBlob.method, log: qq.bind(self.log, self) }); getSas.request(id, blobUriStore.get(id)).then(qq.bind(getSasSuccess, self, id), qq.bind(getSasFailure, self, id)); }, _createDeleteHandler: function() { var self = this; return { sendDelete: function(id, uuid) { self._deleteBlob(false, id); } }; } }); })(); qq.azure.XhrUploadHandler = function(spec, proxy) { "use strict"; var handler = this, log = proxy.log, cors = spec.cors, endpointStore = spec.endpointStore, paramsStore = spec.paramsStore, signature = spec.signature, filenameParam = spec.filenameParam, minFileSizeForChunking = spec.chunking.minFileSize, deleteBlob = spec.deleteBlob, onGetBlobName = spec.onGetBlobName, getName = proxy.getName, getSize = proxy.getSize, getBlobMetadata = function(id) { var params = paramsStore.get(id); params[filenameParam] = getName(id); return params; }, api = { putBlob: new qq.azure.PutBlob({ getBlobMetadata: getBlobMetadata, log: log }), putBlock: new qq.azure.PutBlock({ log: log }), putBlockList: new qq.azure.PutBlockList({ getBlobMetadata: getBlobMetadata, log: log }), getSasForPutBlobOrBlock: new qq.azure.GetSas({ cors: cors, customHeaders: signature.customHeaders, endpointStore: { get: function() { return signature.endpoint; } }, log: log, restRequestVerb: "PUT" }) }; function combineChunks(id) { var promise = new qq.Promise(); getSignedUrl(id).then(function(sasUri) { var mimeType = handler._getMimeType(id), blockIdEntries = handler._getPersistableData(id).blockIdEntries; api.putBlockList.send(id, sasUri, blockIdEntries, mimeType, function(xhr) { handler._registerXhr(id, null, xhr, api.putBlockList); }).then(function(xhr) { log("Success combining chunks for id " + id); promise.success({}, xhr); }, function(xhr) { log("Attempt to combine chunks failed for id " + id, "error"); handleFailure(xhr, promise); }); }, promise.failure); return promise; } function determineBlobUrl(id) { var containerUrl = endpointStore.get(id), promise = new qq.Promise(), getBlobNameSuccess = function(blobName) { handler._setThirdPartyFileId(id, blobName); promise.success(containerUrl + "/" + blobName); }, getBlobNameFailure = function(reason) { promise.failure(reason); }; onGetBlobName(id).then(getBlobNameSuccess, getBlobNameFailure); return promise; } function getSignedUrl(id, optChunkIdx) { var getSasId = optChunkIdx == null ? id : id + "." + optChunkIdx, promise = new qq.Promise(), getSasSuccess = function(sasUri) { log("GET SAS request succeeded."); promise.success(sasUri); }, getSasFailure = function(reason, getSasXhr) { log("GET SAS request failed: " + reason, "error"); promise.failure({ error: "Problem communicating with local server" }, getSasXhr); }, determineBlobUrlSuccess = function(blobUrl) { api.getSasForPutBlobOrBlock.request(getSasId, blobUrl).then(getSasSuccess, getSasFailure); }, determineBlobUrlFailure = function(reason) { log(qq.format("Failed to determine blob name for ID {} - {}", id, reason), "error"); promise.failure({ error: reason }); }; determineBlobUrl(id).then(determineBlobUrlSuccess, determineBlobUrlFailure); return promise; } function handleFailure(xhr, promise) { var azureError = qq.azure.util.parseAzureError(xhr.responseText, log), errorMsg = "Problem sending file to Azure"; promise.failure({ error: errorMsg, azureError: azureError && azureError.message, reset: xhr.status === 403 }); } qq.extend(this, { uploadChunk: function(id, chunkIdx) { var promise = new qq.Promise(); getSignedUrl(id, chunkIdx).then(function(sasUri) { var xhr = handler._createXhr(id, chunkIdx), chunkData = handler._getChunkData(id, chunkIdx); handler._registerProgressHandler(id, chunkIdx, chunkData.size); handler._registerXhr(id, chunkIdx, xhr, api.putBlock); api.putBlock.upload(id + "." + chunkIdx, xhr, sasUri, chunkIdx, chunkData.blob).then(function(blockIdEntry) { if (!handler._getPersistableData(id).blockIdEntries) { handler._getPersistableData(id).blockIdEntries = []; } handler._getPersistableData(id).blockIdEntries.push(blockIdEntry); log("Put Block call succeeded for " + id); promise.success({}, xhr); }, function() { log(qq.format("Put Block call failed for ID {} on part {}", id, chunkIdx), "error"); handleFailure(xhr, promise); }); }, promise.failure); return promise; }, uploadFile: function(id) { var promise = new qq.Promise(), fileOrBlob = handler.getFile(id); getSignedUrl(id).then(function(sasUri) { var xhr = handler._createXhr(id); handler._registerProgressHandler(id); api.putBlob.upload(id, xhr, sasUri, fileOrBlob).then(function() { log("Put Blob call succeeded for " + id); promise.success({}, xhr); }, function() { log("Put Blob call failed for " + id, "error"); handleFailure(xhr, promise); }); }, promise.failure); return promise; } }); qq.extend(this, new qq.XhrUploadHandler({ options: qq.extend({ namespace: "azure" }, spec), proxy: qq.extend({ getEndpoint: spec.endpointStore.get }, proxy) })); qq.override(this, function(super_) { return { expunge: function(id) { var relatedToCancel = handler._wasCanceled(id), chunkingData = handler._getPersistableData(id), blockIdEntries = chunkingData && chunkingData.blockIdEntries || []; if (relatedToCancel && blockIdEntries.length > 0) { deleteBlob(id); } super_.expunge(id); }, finalizeChunks: function(id) { return combineChunks(id); }, _shouldChunkThisFile: function(id) { var maybePossible = super_._shouldChunkThisFile(id); return maybePossible && getSize(id) >= minFileSizeForChunking; } }; }); }; qq.azure.GetSas = function(o) { "use strict"; var requester, options = { cors: { expected: false, sendCredentials: false }, customHeaders: {}, restRequestVerb: "PUT", endpointStore: null, log: function(str, level) {} }, requestPromises = {}; qq.extend(options, o); function sasResponseReceived(id, xhr, isError) { var promise = requestPromises[id]; if (isError) { promise.failure("Received response code " + xhr.status, xhr); } else { if (xhr.responseText.length) { promise.success(xhr.responseText); } else { promise.failure("Empty response.", xhr); } } delete requestPromises[id]; } requester = qq.extend(this, new qq.AjaxRequester({ acceptHeader: "application/json", validMethods: [ "GET" ], method: "GET", successfulResponseCodes: { GET: [ 200 ] }, contentType: null, customHeaders: options.customHeaders, endpointStore: options.endpointStore, cors: options.cors, log: options.log, onComplete: sasResponseReceived })); qq.extend(this, { request: function(id, blobUri) { var requestPromise = new qq.Promise(), restVerb = options.restRequestVerb; options.log(qq.format("Submitting GET SAS request for a {} REST request related to file ID {}.", restVerb, id)); requestPromises[id] = requestPromise; requester.initTransport(id).withParams({ bloburi: blobUri, _method: restVerb }).withCacheBuster().send(); return requestPromise; } }); }; qq.UploadSuccessAjaxRequester = function(o) { "use strict"; var requester, pendingRequests = [], options = { method: "POST", endpoint: null, maxConnections: 3, customHeaders: {}, paramsStore: {}, cors: { expected: false, sendCredentials: false }, log: function(str, level) {} }; qq.extend(options, o); function handleSuccessResponse(id, xhrOrXdr, isError) { var promise = pendingRequests[id], responseJson = xhrOrXdr.responseText, successIndicator = { success: true }, failureIndicator = { success: false }, parsedResponse; delete pendingRequests[id]; options.log(qq.format("Received the following response body to an upload success request for id {}: {}", id, responseJson)); try { parsedResponse = qq.parseJson(responseJson); if (isError || parsedResponse && (parsedResponse.error || parsedResponse.success === false)) { options.log("Upload success request was rejected by the server.", "error"); promise.failure(qq.extend(parsedResponse, failureIndicator)); } else { options.log("Upload success was acknowledged by the server."); promise.success(qq.extend(parsedResponse, successIndicator)); } } catch (error) { if (isError) { options.log(qq.format("Your server indicated failure in its upload success request response for id {}!", id), "error"); promise.failure(failureIndicator); } else { options.log("Upload success was acknowledged by the server."); promise.success(successIndicator); } } } requester = qq.extend(this, new qq.AjaxRequester({ acceptHeader: "application/json", method: options.method, endpointStore: { get: function() { return options.endpoint; } }, paramsStore: options.paramsStore, maxConnections: options.maxConnections, customHeaders: options.customHeaders, log: options.log, onComplete: handleSuccessResponse, cors: options.cors })); qq.extend(this, { sendSuccessRequest: function(id, spec) { var promise = new qq.Promise(); options.log("Submitting upload success request/notification for " + id); requester.initTransport(id).withParams(spec).send(); pendingRequests[id] = promise; return promise; } }); }; qq.azure.DeleteBlob = function(o) { "use strict"; var requester, method = "DELETE", options = { endpointStore: {}, onDelete: function(id) {}, onDeleteComplete: function(id, xhr, isError) {}, log: function(str, level) {} }; qq.extend(options, o); requester = qq.extend(this, new qq.AjaxRequester({ validMethods: [ method ], method: method, successfulResponseCodes: function() { var codes = {}; codes[method] = [ 202 ]; return codes; }(), contentType: null, endpointStore: options.endpointStore, allowXRequestedWithAndCacheControl: false, cors: { expected: true }, log: options.log, onSend: options.onDelete, onComplete: options.onDeleteComplete })); qq.extend(this, { method: method, send: function(id) { options.log("Submitting Delete Blob request for " + id); return requester.initTransport(id).send(); } }); }; qq.azure.PutBlob = function(o) { "use strict"; var requester, method = "PUT", options = { getBlobMetadata: function(id) {}, log: function(str, level) {} }, endpoints = {}, promises = {}, endpointHandler = { get: function(id) { return endpoints[id]; } }; qq.extend(options, o); requester = qq.extend(this, new qq.AjaxRequester({ validMethods: [ method ], method: method, successfulResponseCodes: function() { var codes = {}; codes[method] = [ 201 ]; return codes; }(), contentType: null, customHeaders: function(id) { var params = options.getBlobMetadata(id), headers = qq.azure.util.getParamsAsHeaders(params); headers["x-ms-blob-type"] = "BlockBlob"; return headers; }, endpointStore: endpointHandler, allowXRequestedWithAndCacheControl: false, cors: { expected: true }, log: options.log, onComplete: function(id, xhr, isError) { var promise = promises[id]; delete endpoints[id]; delete promises[id]; if (isError) { promise.failure(); } else { promise.success(); } } })); qq.extend(this, { method: method, upload: function(id, xhr, url, file) { var promise = new qq.Promise(); options.log("Submitting Put Blob request for " + id); promises[id] = promise; endpoints[id] = url; requester.initTransport(id).withPayload(file).withHeaders({ "Content-Type": file.type }).send(xhr); return promise; } }); }; qq.azure.PutBlock = function(o) { "use strict"; var requester, method = "PUT", blockIdEntries = {}, promises = {}, options = { log: function(str, level) {} }, endpoints = {}, endpointHandler = { get: function(id) { return endpoints[id]; } }; qq.extend(options, o); requester = qq.extend(this, new qq.AjaxRequester({ validMethods: [ method ], method: method, successfulResponseCodes: function() { var codes = {}; codes[method] = [ 201 ]; return codes; }(), contentType: null, endpointStore: endpointHandler, allowXRequestedWithAndCacheControl: false, cors: { expected: true }, log: options.log, onComplete: function(id, xhr, isError) { var promise = promises[id], blockIdEntry = blockIdEntries[id]; delete endpoints[id]; delete promises[id]; delete blockIdEntries[id]; if (isError) { promise.failure(); } else { promise.success(blockIdEntry); } } })); function createBlockId(partNum) { var digits = 5, zeros = new Array(digits + 1).join("0"), paddedPartNum = (zeros + partNum).slice(-digits); return btoa(paddedPartNum); } qq.extend(this, { method: method, upload: function(id, xhr, sasUri, partNum, blob) { var promise = new qq.Promise(), blockId = createBlockId(partNum); promises[id] = promise; options.log(qq.format("Submitting Put Block request for {} = part {}", id, partNum)); endpoints[id] = qq.format("{}&comp=block&blockid={}", sasUri, encodeURIComponent(blockId)); blockIdEntries[id] = { part: partNum, id: blockId }; requester.initTransport(id).withPayload(blob).send(xhr); return promise; } }); }; qq.azure.PutBlockList = function(o) { "use strict"; var requester, method = "PUT", promises = {}, options = { getBlobMetadata: function(id) {}, log: function(str, level) {} }, endpoints = {}, endpointHandler = { get: function(id) { return endpoints[id]; } }; qq.extend(options, o); requester = qq.extend(this, new qq.AjaxRequester({ validMethods: [ method ], method: method, successfulResponseCodes: function() { var codes = {}; codes[method] = [ 201 ]; return codes; }(), customHeaders: function(id) { var params = options.getBlobMetadata(id); return qq.azure.util.getParamsAsHeaders(params); }, contentType: "text/plain", endpointStore: endpointHandler, allowXRequestedWithAndCacheControl: false, cors: { expected: true }, log: options.log, onSend: function() {}, onComplete: function(id, xhr, isError) { var promise = promises[id]; delete endpoints[id]; delete promises[id]; if (isError) { promise.failure(xhr); } else { promise.success(xhr); } } })); function createRequestBody(blockIdEntries) { var doc = document.implementation.createDocument(null, "BlockList", null); blockIdEntries.sort(function(a, b) { return a.part - b.part; }); qq.each(blockIdEntries, function(idx, blockIdEntry) { var latestEl = doc.createElement("Latest"), latestTextEl = doc.createTextNode(blockIdEntry.id); latestEl.appendChild(latestTextEl); qq(doc).children()[0].appendChild(latestEl); }); return new XMLSerializer().serializeToString(doc); } qq.extend(this, { method: method, send: function(id, sasUri, blockIdEntries, fileMimeType, registerXhrCallback) { var promise = new qq.Promise(), blockIdsXml = createRequestBody(blockIdEntries), xhr; promises[id] = promise; options.log(qq.format("Submitting Put Block List request for {}", id)); endpoints[id] = qq.format("{}&comp=blocklist", sasUri); xhr = requester.initTransport(id).withPayload(blockIdsXml).withHeaders({ "x-ms-blob-content-type": fileMimeType }).send(); registerXhrCallback(xhr); return promise; } }); }; qq.DragAndDrop = function(o) { "use strict"; var options, HIDE_ZONES_EVENT_NAME = "qq-hidezones", HIDE_BEFORE_ENTER_ATTR = "qq-hide-dropzone", uploadDropZones = [], droppedFiles = [], disposeSupport = new qq.DisposeSupport(); options = { dropZoneElements: [], allowMultipleItems: true, classes: { dropActive: null }, callbacks: new qq.DragAndDrop.callbacks() }; qq.extend(options, o, true); function uploadDroppedFiles(files, uploadDropZone) { var filesAsArray = Array.prototype.slice.call(files); options.callbacks.dropLog("Grabbed " + files.length + " dropped files."); uploadDropZone.dropDisabled(false); options.callbacks.processingDroppedFilesComplete(filesAsArray, uploadDropZone.getElement()); } function traverseFileTree(entry) { var parseEntryPromise = new qq.Promise(); if (entry.isFile) { entry.file(function(file) { var name = entry.name, fullPath = entry.fullPath, indexOfNameInFullPath = fullPath.indexOf(name); fullPath = fullPath.substr(0, indexOfNameInFullPath); if (fullPath.charAt(0) === "/") { fullPath = fullPath.substr(1); } file.qqPath = fullPath; droppedFiles.push(file); parseEntryPromise.success(); }, function(fileError) { options.callbacks.dropLog("Problem parsing '" + entry.fullPath + "'. FileError code " + fileError.code + ".", "error"); parseEntryPromise.failure(); }); } else if (entry.isDirectory) { getFilesInDirectory(entry).then(function allEntriesRead(entries) { var entriesLeft = entries.length; qq.each(entries, function(idx, entry) { traverseFileTree(entry).done(function() { entriesLeft -= 1; if (entriesLeft === 0) { parseEntryPromise.success(); } }); }); if (!entries.length) { parseEntryPromise.success(); } }, function readFailure(fileError) { options.callbacks.dropLog("Problem parsing '" + entry.fullPath + "'. FileError code " + fileError.code + ".", "error"); parseEntryPromise.failure(); }); } return parseEntryPromise; } function getFilesInDirectory(entry, reader, accumEntries, existingPromise) { var promise = existingPromise || new qq.Promise(), dirReader = reader || entry.createReader(); dirReader.readEntries(function readSuccess(entries) { var newEntries = accumEntries ? accumEntries.concat(entries) : entries; if (entries.length) { setTimeout(function() { getFilesInDirectory(entry, dirReader, newEntries, promise); }, 0); } else { promise.success(newEntries); } }, promise.failure); return promise; } function handleDataTransfer(dataTransfer, uploadDropZone) { var pendingFolderPromises = [], handleDataTransferPromise = new qq.Promise(); options.callbacks.processingDroppedFiles(); uploadDropZone.dropDisabled(true); if (dataTransfer.files.length > 1 && !options.allowMultipleItems) { options.callbacks.processingDroppedFilesComplete([]); options.callbacks.dropError("tooManyFilesError", ""); uploadDropZone.dropDisabled(false); handleDataTransferPromise.failure(); } else { droppedFiles = []; if (qq.isFolderDropSupported(dataTransfer)) { qq.each(dataTransfer.items, function(idx, item) { var entry = item.webkitGetAsEntry(); if (entry) { if (entry.isFile) { droppedFiles.push(item.getAsFile()); } else { pendingFolderPromises.push(traverseFileTree(entry).done(function() { pendingFolderPromises.pop(); if (pendingFolderPromises.length === 0) { handleDataTransferPromise.success(); } })); } } }); } else { droppedFiles = dataTransfer.files; } if (pendingFolderPromises.length === 0) { handleDataTransferPromise.success(); } } return handleDataTransferPromise; } function setupDropzone(dropArea) { var dropZone = new qq.UploadDropZone({ HIDE_ZONES_EVENT_NAME: HIDE_ZONES_EVENT_NAME, element: dropArea, onEnter: function(e) { qq(dropArea).addClass(options.classes.dropActive); e.stopPropagation(); }, onLeaveNotDescendants: function(e) { qq(dropArea).removeClass(options.classes.dropActive); }, onDrop: function(e) { handleDataTransfer(e.dataTransfer, dropZone).then(function() { uploadDroppedFiles(droppedFiles, dropZone); }, function() { options.callbacks.dropLog("Drop event DataTransfer parsing failed. No files will be uploaded.", "error"); }); } }); disposeSupport.addDisposer(function() { dropZone.dispose(); }); qq(dropArea).hasAttribute(HIDE_BEFORE_ENTER_ATTR) && qq(dropArea).hide(); uploadDropZones.push(dropZone); return dropZone; } function isFileDrag(dragEvent) { var fileDrag; qq.each(dragEvent.dataTransfer.types, function(key, val) { if (val === "Files") { fileDrag = true; return false; } }); return fileDrag; } function leavingDocumentOut(e) { if (qq.firefox()) { return !e.relatedTarget; } if (qq.safari()) { return e.x < 0 || e.y < 0; } return e.x === 0 && e.y === 0; } function setupDragDrop() { var dropZones = options.dropZoneElements, maybeHideDropZones = function() { setTimeout(function() { qq.each(dropZones, function(idx, dropZone) { qq(dropZone).hasAttribute(HIDE_BEFORE_ENTER_ATTR) && qq(dropZone).hide(); qq(dropZone).removeClass(options.classes.dropActive); }); }, 10); }; qq.each(dropZones, function(idx, dropZone) { var uploadDropZone = setupDropzone(dropZone); if (dropZones.length && qq.supportedFeatures.fileDrop) { disposeSupport.attach(document, "dragenter", function(e) { if (!uploadDropZone.dropDisabled() && isFileDrag(e)) { qq.each(dropZones, function(idx, dropZone) { if (dropZone instanceof HTMLElement && qq(dropZone).hasAttribute(HIDE_BEFORE_ENTER_ATTR)) { qq(dropZone).css({ display: "block" }); } }); } }); } }); disposeSupport.attach(document, "dragleave", function(e) { if (leavingDocumentOut(e)) { maybeHideDropZones(); } }); disposeSupport.attach(qq(document).children()[0], "mouseenter", function(e) { maybeHideDropZones(); }); disposeSupport.attach(document, "drop", function(e) { e.preventDefault(); maybeHideDropZones(); }); disposeSupport.attach(document, HIDE_ZONES_EVENT_NAME, maybeHideDropZones); } setupDragDrop(); qq.extend(this, { setupExtraDropzone: function(element) { options.dropZoneElements.push(element); setupDropzone(element); }, removeDropzone: function(element) { var i, dzs = options.dropZoneElements; for (i in dzs) { if (dzs[i] === element) { return dzs.splice(i, 1); } } }, dispose: function() { disposeSupport.dispose(); qq.each(uploadDropZones, function(idx, dropZone) { dropZone.dispose(); }); } }); }; qq.DragAndDrop.callbacks = function() { "use strict"; return { processingDroppedFiles: function() {}, processingDroppedFilesComplete: function(files, targetEl) {}, dropError: function(code, errorSpecifics) { qq.log("Drag & drop error code '" + code + " with these specifics: '" + errorSpecifics + "'", "error"); }, dropLog: function(message, level) { qq.log(message, level); } }; }; qq.UploadDropZone = function(o) { "use strict"; var disposeSupport = new qq.DisposeSupport(), options, element, preventDrop, dropOutsideDisabled; options = { element: null, onEnter: function(e) {}, onLeave: function(e) {}, onLeaveNotDescendants: function(e) {}, onDrop: function(e) {} }; qq.extend(options, o); element = options.element; function dragoverShouldBeCanceled() { return qq.safari() || qq.firefox() && qq.windows(); } function disableDropOutside(e) { if (!dropOutsideDisabled) { if (dragoverShouldBeCanceled) { disposeSupport.attach(document, "dragover", function(e) { e.preventDefault(); }); } else { disposeSupport.attach(document, "dragover", function(e) { if (e.dataTransfer) { e.dataTransfer.dropEffect = "none"; e.preventDefault(); } }); } dropOutsideDisabled = true; } } function isValidFileDrag(e) { if (!qq.supportedFeatures.fileDrop) { return false; } var effectTest, dt = e.dataTransfer, isSafari = qq.safari(); effectTest = qq.ie() && qq.supportedFeatures.fileDrop ? true : dt.effectAllowed !== "none"; return dt && effectTest && (dt.files || !isSafari && dt.types.contains && dt.types.contains("Files")); } function isOrSetDropDisabled(isDisabled) { if (isDisabled !== undefined) { preventDrop = isDisabled; } return preventDrop; } function triggerHidezonesEvent() { var hideZonesEvent; function triggerUsingOldApi() { hideZonesEvent = document.createEvent("Event"); hideZonesEvent.initEvent(options.HIDE_ZONES_EVENT_NAME, true, true); } if (window.CustomEvent) { try { hideZonesEvent = new CustomEvent(options.HIDE_ZONES_EVENT_NAME); } catch (err) { triggerUsingOldApi(); } } else { triggerUsingOldApi(); } document.dispatchEvent(hideZonesEvent); } function attachEvents() { disposeSupport.attach(element, "dragover", function(e) { if (!isValidFileDrag(e)) { return; } var effect = qq.ie() && qq.supportedFeatures.fileDrop ? null : e.dataTransfer.effectAllowed; if (effect === "move" || effect === "linkMove") { e.dataTransfer.dropEffect = "move"; } else { e.dataTransfer.dropEffect = "copy"; } e.stopPropagation(); e.preventDefault(); }); disposeSupport.attach(element, "dragenter", function(e) { if (!isOrSetDropDisabled()) { if (!isValidFileDrag(e)) { return; } options.onEnter(e); } }); disposeSupport.attach(element, "dragleave", function(e) { if (!isValidFileDrag(e)) { return; } options.onLeave(e); var relatedTarget = document.elementFromPoint(e.clientX, e.clientY); if (qq(this).contains(relatedTarget)) { return; } options.onLeaveNotDescendants(e); }); disposeSupport.attach(element, "drop", function(e) { if (!isOrSetDropDisabled()) { if (!isValidFileDrag(e)) { return; } e.preventDefault(); e.stopPropagation(); options.onDrop(e); triggerHidezonesEvent(); } }); } disableDropOutside(); attachEvents(); qq.extend(this, { dropDisabled: function(isDisabled) { return isOrSetDropDisabled(isDisabled); }, dispose: function() { disposeSupport.dispose(); }, getElement: function() { return element; } }); }; (function() { "use strict"; qq.uiPublicApi = { addInitialFiles: function(cannedFileList) { this._parent.prototype.addInitialFiles.apply(this, arguments); this._templating.addCacheToDom(); }, clearStoredFiles: function() { this._parent.prototype.clearStoredFiles.apply(this, arguments); this._templating.clearFiles(); }, addExtraDropzone: function(element) { this._dnd && this._dnd.setupExtraDropzone(element); }, removeExtraDropzone: function(element) { if (this._dnd) { return this._dnd.removeDropzone(element); } }, getItemByFileId: function(id) { if (!this._templating.isHiddenForever(id)) { return this._templating.getFileContainer(id); } }, reset: function() { this._parent.prototype.reset.apply(this, arguments); this._templating.reset(); if (!this._options.button && this._templating.getButton()) { this._defaultButtonId = this._createUploadButton({ element: this._templating.getButton(), title: this._options.text.fileInputTitle }).getButtonId(); } if (this._dnd) { this._dnd.dispose(); this._dnd = this._setupDragAndDrop(); } this._totalFilesInBatch = 0; this._filesInBatchAddedToUi = 0; this._setupClickAndEditEventHandlers(); }, setName: function(id, newName) { var formattedFilename = this._options.formatFileName(newName); this._parent.prototype.setName.apply(this, arguments); this._templating.updateFilename(id, formattedFilename); }, pauseUpload: function(id) { var paused = this._parent.prototype.pauseUpload.apply(this, arguments); paused && this._templating.uploadPaused(id); return paused; }, continueUpload: function(id) { var continued = this._parent.prototype.continueUpload.apply(this, arguments); continued && this._templating.uploadContinued(id); return continued; }, getId: function(fileContainerOrChildEl) { return this._templating.getFileId(fileContainerOrChildEl); }, getDropTarget: function(fileId) { var file = this.getFile(fileId); return file.qqDropTarget; } }; qq.uiPrivateApi = { _getButton: function(buttonId) { var button = this._parent.prototype._getButton.apply(this, arguments); if (!button) { if (buttonId === this._defaultButtonId) { button = this._templating.getButton(); } } return button; }, _removeFileItem: function(fileId) { this._templating.removeFile(fileId); }, _setupClickAndEditEventHandlers: function() { this._fileButtonsClickHandler = qq.FileButtonsClickHandler && this._bindFileButtonsClickEvent(); this._focusinEventSupported = !qq.firefox(); if (this._isEditFilenameEnabled()) { this._filenameClickHandler = this._bindFilenameClickEvent(); this._filenameInputFocusInHandler = this._bindFilenameInputFocusInEvent(); this._filenameInputFocusHandler = this._bindFilenameInputFocusEvent(); } }, _setupDragAndDrop: function() { var self = this, dropZoneElements = this._options.dragAndDrop.extraDropzones, templating = this._templating, defaultDropZone = templating.getDropZone(); defaultDropZone && dropZoneElements.push(defaultDropZone); return new qq.DragAndDrop({ dropZoneElements: dropZoneElements, allowMultipleItems: this._options.multiple, classes: { dropActive: this._options.classes.dropActive }, callbacks: { processingDroppedFiles: function() { templating.showDropProcessing(); }, processingDroppedFilesComplete: function(files, targetEl) { templating.hideDropProcessing(); qq.each(files, function(idx, file) { file.qqDropTarget = targetEl; }); if (files.length) { self.addFiles(files, null, null); } }, dropError: function(code, errorData) { self._itemError(code, errorData); }, dropLog: function(message, level) { self.log(message, level); } } }); }, _bindFileButtonsClickEvent: function() { var self = this; return new qq.FileButtonsClickHandler({ templating: this._templating, log: function(message, lvl) { self.log(message, lvl); }, onDeleteFile: function(fileId) { self.deleteFile(fileId); }, onCancel: function(fileId) { self.cancel(fileId); }, onRetry: function(fileId) { self.retry(fileId); }, onPause: function(fileId) { self.pauseUpload(fileId); }, onContinue: function(fileId) { self.continueUpload(fileId); }, onGetName: function(fileId) { return self.getName(fileId); } }); }, _isEditFilenameEnabled: function() { return this._templating.isEditFilenamePossible() && !this._options.autoUpload && qq.FilenameClickHandler && qq.FilenameInputFocusHandler && qq.FilenameInputFocusHandler; }, _filenameEditHandler: function() { var self = this, templating = this._templating; return { templating: templating, log: function(message, lvl) { self.log(message, lvl); }, onGetUploadStatus: function(fileId) { return self.getUploads({ id: fileId }).status; }, onGetName: function(fileId) { return self.getName(fileId); }, onSetName: function(id, newName) { self.setName(id, newName); }, onEditingStatusChange: function(id, isEditing) { var qqInput = qq(templating.getEditInput(id)), qqFileContainer = qq(templating.getFileContainer(id)); if (isEditing) { qqInput.addClass("qq-editing"); templating.hideFilename(id); templating.hideEditIcon(id); } else { qqInput.removeClass("qq-editing"); templating.showFilename(id); templating.showEditIcon(id); } qqFileContainer.addClass("qq-temp").removeClass("qq-temp"); } }; }, _onUploadStatusChange: function(id, oldStatus, newStatus) { this._parent.prototype._onUploadStatusChange.apply(this, arguments); if (this._isEditFilenameEnabled()) { if (this._templating.getFileContainer(id) && newStatus !== qq.status.SUBMITTED) { this._templating.markFilenameEditable(id); this._templating.hideEditIcon(id); } } if (oldStatus === qq.status.UPLOAD_RETRYING && newStatus === qq.status.UPLOADING) { this._templating.hideRetry(id); this._templating.setStatusText(id); qq(this._templating.getFileContainer(id)).removeClass(this._classes.retrying); } else if (newStatus === qq.status.UPLOAD_FAILED) { this._templating.hidePause(id); } }, _bindFilenameInputFocusInEvent: function() { var spec = qq.extend({}, this._filenameEditHandler()); return new qq.FilenameInputFocusInHandler(spec); }, _bindFilenameInputFocusEvent: function() { var spec = qq.extend({}, this._filenameEditHandler()); return new qq.FilenameInputFocusHandler(spec); }, _bindFilenameClickEvent: function() { var spec = qq.extend({}, this._filenameEditHandler()); return new qq.FilenameClickHandler(spec); }, _storeForLater: function(id) { this._parent.prototype._storeForLater.apply(this, arguments); this._templating.hideSpinner(id); }, _onAllComplete: function(successful, failed) { this._parent.prototype._onAllComplete.apply(this, arguments); this._templating.resetTotalProgress(); }, _onSubmit: function(id, name) { var file = this.getFile(id); if (file && file.qqPath && this._options.dragAndDrop.reportDirectoryPaths) { this._paramsStore.addReadOnly(id, { qqpath: file.qqPath }); } this._parent.prototype._onSubmit.apply(this, arguments); this._addToList(id, name); }, _onSubmitted: function(id) { if (this._isEditFilenameEnabled()) { this._templating.markFilenameEditable(id); this._templating.showEditIcon(id); if (!this._focusinEventSupported) { this._filenameInputFocusHandler.addHandler(this._templating.getEditInput(id)); } } }, _onProgress: function(id, name, loaded, total) { this._parent.prototype._onProgress.apply(this, arguments); this._templating.updateProgress(id, loaded, total); if (total === 0 || Math.round(loaded / total * 100) === 100) { this._templating.hideCancel(id); this._templating.hidePause(id); this._templating.hideProgress(id); this._templating.setStatusText(id, this._options.text.waitingForResponse); this._displayFileSize(id); } else { this._displayFileSize(id, loaded, total); } }, _onTotalProgress: function(loaded, total) { this._parent.prototype._onTotalProgress.apply(this, arguments); this._templating.updateTotalProgress(loaded, total); }, _onComplete: function(id, name, result, xhr) { var parentRetVal = this._parent.prototype._onComplete.apply(this, arguments), templating = this._templating, fileContainer = templating.getFileContainer(id), self = this; function completeUpload(result) { if (!fileContainer) { return; } templating.setStatusText(id); qq(fileContainer).removeClass(self._classes.retrying); templating.hideProgress(id); if (self.getUploads({ id: id }).status !== qq.status.UPLOAD_FAILED) { templating.hideCancel(id); } templating.hideSpinner(id); if (result.success) { self._markFileAsSuccessful(id); } else { qq(fileContainer).addClass(self._classes.fail); templating.showCancel(id); if (templating.isRetryPossible() && !self._preventRetries[id]) { qq(fileContainer).addClass(self._classes.retryable); templating.showRetry(id); } self._controlFailureTextDisplay(id, result); } } if (parentRetVal instanceof qq.Promise) { parentRetVal.done(function(newResult) { completeUpload(newResult); }); } else { completeUpload(result); } return parentRetVal; }, _markFileAsSuccessful: function(id) { var templating = this._templating; if (this._isDeletePossible()) { templating.showDeleteButton(id); } qq(templating.getFileContainer(id)).addClass(this._classes.success); this._maybeUpdateThumbnail(id); }, _onUploadPrep: function(id) { this._parent.prototype._onUploadPrep.apply(this, arguments); this._templating.showSpinner(id); }, _onUpload: function(id, name) { var parentRetVal = this._parent.prototype._onUpload.apply(this, arguments); this._templating.showSpinner(id); return parentRetVal; }, _onUploadChunk: function(id, chunkData) { this._parent.prototype._onUploadChunk.apply(this, arguments); if (chunkData.partIndex > 0 && this._handler.isResumable(id)) { this._templating.allowPause(id); } }, _onCancel: function(id, name) { this._parent.prototype._onCancel.apply(this, arguments); this._removeFileItem(id); if (this._getNotFinished() === 0) { this._templating.resetTotalProgress(); } }, _onBeforeAutoRetry: function(id) { var retryNumForDisplay, maxAuto, retryNote; this._parent.prototype._onBeforeAutoRetry.apply(this, arguments); this._showCancelLink(id); if (this._options.retry.showAutoRetryNote) { retryNumForDisplay = this._autoRetries[id]; maxAuto = this._options.retry.maxAutoAttempts; retryNote = this._options.retry.autoRetryNote.replace(/\{retryNum\}/g, retryNumForDisplay); retryNote = retryNote.replace(/\{maxAuto\}/g, maxAuto); this._templating.setStatusText(id, retryNote); qq(this._templating.getFileContainer(id)).addClass(this._classes.retrying); } }, _onBeforeManualRetry: function(id) { if (this._parent.prototype._onBeforeManualRetry.apply(this, arguments)) { this._templating.resetProgress(id); qq(this._templating.getFileContainer(id)).removeClass(this._classes.fail); this._templating.setStatusText(id); this._templating.showSpinner(id); this._showCancelLink(id); return true; } else { qq(this._templating.getFileContainer(id)).addClass(this._classes.retryable); this._templating.showRetry(id); return false; } }, _onSubmitDelete: function(id) { var onSuccessCallback = qq.bind(this._onSubmitDeleteSuccess, this); this._parent.prototype._onSubmitDelete.call(this, id, onSuccessCallback); }, _onSubmitDeleteSuccess: function(id, uuid, additionalMandatedParams) { if (this._options.deleteFile.forceConfirm) { this._showDeleteConfirm.apply(this, arguments); } else { this._sendDeleteRequest.apply(this, arguments); } }, _onDeleteComplete: function(id, xhr, isError) { this._parent.prototype._onDeleteComplete.apply(this, arguments); this._templating.hideSpinner(id); if (isError) { this._templating.setStatusText(id, this._options.deleteFile.deletingFailedText); this._templating.showDeleteButton(id); } else { this._removeFileItem(id); } }, _sendDeleteRequest: function(id, uuid, additionalMandatedParams) { this._templating.hideDeleteButton(id); this._templating.showSpinner(id); this._templating.setStatusText(id, this._options.deleteFile.deletingStatusText); this._deleteHandler.sendDelete.apply(this, arguments); }, _showDeleteConfirm: function(id, uuid, mandatedParams) { var fileName = this.getName(id), confirmMessage = this._options.deleteFile.confirmMessage.replace(/\{filename\}/g, fileName), uuid = this.getUuid(id), deleteRequestArgs = arguments, self = this, retVal; retVal = this._options.showConfirm(confirmMessage); if (qq.isGenericPromise(retVal)) { retVal.then(function() { self._sendDeleteRequest.apply(self, deleteRequestArgs); }); } else if (retVal !== false) { self._sendDeleteRequest.apply(self, deleteRequestArgs); } }, _addToList: function(id, name, canned) { var prependData, prependIndex = 0, dontDisplay = this._handler.isProxied(id) && this._options.scaling.hideScaled, record; if (this._options.display.prependFiles) { if (this._totalFilesInBatch > 1 && this._filesInBatchAddedToUi > 0) { prependIndex = this._filesInBatchAddedToUi - 1; } prependData = { index: prependIndex }; } if (!canned) { if (this._options.disableCancelForFormUploads && !qq.supportedFeatures.ajaxUploading) { this._templating.disableCancel(); } if (!this._options.multiple) { record = this.getUploads({ id: id }); this._handledProxyGroup = this._handledProxyGroup || record.proxyGroupId; if (record.proxyGroupId !== this._handledProxyGroup || !record.proxyGroupId) { this._handler.cancelAll(); this._clearList(); this._handledProxyGroup = null; } } } if (canned) { this._templating.addFileToCache(id, this._options.formatFileName(name), prependData, dontDisplay); this._templating.updateThumbnail(id, this._thumbnailUrls[id], true, this._options.thumbnails.customResizer); } else { this._templating.addFile(id, this._options.formatFileName(name), prependData, dontDisplay); this._templating.generatePreview(id, this.getFile(id), this._options.thumbnails.customResizer); } this._filesInBatchAddedToUi += 1; if (canned || this._options.display.fileSizeOnSubmit && qq.supportedFeatures.ajaxUploading) { this._displayFileSize(id); } }, _clearList: function() { this._templating.clearFiles(); this.clearStoredFiles(); }, _displayFileSize: function(id, loadedSize, totalSize) { var size = this.getSize(id), sizeForDisplay = this._formatSize(size); if (size >= 0) { if (loadedSize !== undefined && totalSize !== undefined) { sizeForDisplay = this._formatProgress(loadedSize, totalSize); } this._templating.updateSize(id, sizeForDisplay); } }, _formatProgress: function(uploadedSize, totalSize) { var message = this._options.text.formatProgress; function r(name, replacement) { message = message.replace(name, replacement); } r("{percent}", Math.round(uploadedSize / totalSize * 100)); r("{total_size}", this._formatSize(totalSize)); return message; }, _controlFailureTextDisplay: function(id, response) { var mode, responseProperty, failureReason; mode = this._options.failedUploadTextDisplay.mode; responseProperty = this._options.failedUploadTextDisplay.responseProperty; if (mode === "custom") { failureReason = response[responseProperty]; if (!failureReason) { failureReason = this._options.text.failUpload; } this._templating.setStatusText(id, failureReason); if (this._options.failedUploadTextDisplay.enableTooltip) { this._showTooltip(id, failureReason); } } else if (mode === "default") { this._templating.setStatusText(id, this._options.text.failUpload); } else if (mode !== "none") { this.log("failedUploadTextDisplay.mode value of '" + mode + "' is not valid", "warn"); } }, _showTooltip: function(id, text) { this._templating.getFileContainer(id).title = text; }, _showCancelLink: function(id) { if (!this._options.disableCancelForFormUploads || qq.supportedFeatures.ajaxUploading) { this._templating.showCancel(id); } }, _itemError: function(code, name, item) { var message = this._parent.prototype._itemError.apply(this, arguments); this._options.showMessage(message); }, _batchError: function(message) { this._parent.prototype._batchError.apply(this, arguments); this._options.showMessage(message); }, _setupPastePrompt: function() { var self = this; this._options.callbacks.onPasteReceived = function() { var message = self._options.paste.namePromptMessage, defaultVal = self._options.paste.defaultName; return self._options.showPrompt(message, defaultVal); }; }, _fileOrBlobRejected: function(id, name) { this._totalFilesInBatch -= 1; this._parent.prototype._fileOrBlobRejected.apply(this, arguments); }, _prepareItemsForUpload: function(items, params, endpoint) { this._totalFilesInBatch = items.length; this._filesInBatchAddedToUi = 0; this._parent.prototype._prepareItemsForUpload.apply(this, arguments); }, _maybeUpdateThumbnail: function(fileId) { var thumbnailUrl = this._thumbnailUrls[fileId], fileStatus = this.getUploads({ id: fileId }).status; if (fileStatus !== qq.status.DELETED && (thumbnailUrl || this._options.thumbnails.placeholders.waitUntilResponse || !qq.supportedFeatures.imagePreviews)) { this._templating.updateThumbnail(fileId, thumbnailUrl, this._options.thumbnails.customResizer); } }, _addCannedFile: function(sessionData) { var id = this._parent.prototype._addCannedFile.apply(this, arguments); this._addToList(id, this.getName(id), true); this._templating.hideSpinner(id); this._templating.hideCancel(id); this._markFileAsSuccessful(id); return id; }, _setSize: function(id, newSize) { this._parent.prototype._setSize.apply(this, arguments); this._templating.updateSize(id, this._formatSize(newSize)); }, _sessionRequestComplete: function() { this._templating.addCacheToDom(); this._parent.prototype._sessionRequestComplete.apply(this, arguments); } }; })(); qq.FineUploader = function(o, namespace) { "use strict"; var self = this; this._parent = namespace ? qq[namespace].FineUploaderBasic : qq.FineUploaderBasic; this._parent.apply(this, arguments); qq.extend(this._options, { element: null, button: null, listElement: null, dragAndDrop: { extraDropzones: [], reportDirectoryPaths: false }, text: { formatProgress: "{percent}% of {total_size}", failUpload: "Upload failed", waitingForResponse: "Processing...", paused: "Paused" }, template: "qq-template", classes: { retrying: "qq-upload-retrying", retryable: "qq-upload-retryable", success: "qq-upload-success", fail: "qq-upload-fail", editable: "qq-editable", hide: "qq-hide", dropActive: "qq-upload-drop-area-active" }, failedUploadTextDisplay: { mode: "default", responseProperty: "error", enableTooltip: true }, messages: { tooManyFilesError: "You may only drop one file", unsupportedBrowser: "Unrecoverable error - this browser does not permit file uploading of any kind." }, retry: { showAutoRetryNote: true, autoRetryNote: "Retrying {retryNum}/{maxAuto}..." }, deleteFile: { forceConfirm: false, confirmMessage: "Are you sure you want to delete {filename}?", deletingStatusText: "Deleting...", deletingFailedText: "Delete failed" }, display: { fileSizeOnSubmit: false, prependFiles: false }, paste: { promptForName: false, namePromptMessage: "Please name this image" }, thumbnails: { customResizer: null, maxCount: 0, placeholders: { waitUntilResponse: false, notAvailablePath: null, waitingPath: null }, timeBetweenThumbs: 750 }, scaling: { hideScaled: false }, showMessage: function(message) { if (self._templating.hasDialog("alert")) { return self._templating.showDialog("alert", message); } else { setTimeout(function() { window.alert(message); }, 0); } }, showConfirm: function(message) { if (self._templating.hasDialog("confirm")) { return self._templating.showDialog("confirm", message); } else { return window.confirm(message); } }, showPrompt: function(message, defaultValue) { if (self._templating.hasDialog("prompt")) { return self._templating.showDialog("prompt", message, defaultValue); } else { return window.prompt(message, defaultValue); } } }, true); qq.extend(this._options, o, true); this._templating = new qq.Templating({ log: qq.bind(this.log, this), templateIdOrEl: this._options.template, containerEl: this._options.element, fileContainerEl: this._options.listElement, button: this._options.button, imageGenerator: this._imageGenerator, classes: { hide: this._options.classes.hide, editable: this._options.classes.editable }, limits: { maxThumbs: this._options.thumbnails.maxCount, timeBetweenThumbs: this._options.thumbnails.timeBetweenThumbs }, placeholders: { waitUntilUpdate: this._options.thumbnails.placeholders.waitUntilResponse, thumbnailNotAvailable: this._options.thumbnails.placeholders.notAvailablePath, waitingForThumbnail: this._options.thumbnails.placeholders.waitingPath }, text: this._options.text }); if (this._options.workarounds.ios8SafariUploads && qq.ios800() && qq.iosSafari()) { this._templating.renderFailure(this._options.messages.unsupportedBrowserIos8Safari); } else if (!qq.supportedFeatures.uploading || this._options.cors.expected && !qq.supportedFeatures.uploadCors) { this._templating.renderFailure(this._options.messages.unsupportedBrowser); } else { this._wrapCallbacks(); this._templating.render(); this._classes = this._options.classes; if (!this._options.button && this._templating.getButton()) { this._defaultButtonId = this._createUploadButton({ element: this._templating.getButton(), title: this._options.text.fileInputTitle }).getButtonId(); } this._setupClickAndEditEventHandlers(); if (qq.DragAndDrop && qq.supportedFeatures.fileDrop) { this._dnd = this._setupDragAndDrop(); } if (this._options.paste.targetElement && this._options.paste.promptForName) { if (qq.PasteSupport) { this._setupPastePrompt(); } else { this.log("Paste support module not found.", "error"); } } this._totalFilesInBatch = 0; this._filesInBatchAddedToUi = 0; } }; qq.extend(qq.FineUploader.prototype, qq.basePublicApi); qq.extend(qq.FineUploader.prototype, qq.basePrivateApi); qq.extend(qq.FineUploader.prototype, qq.uiPublicApi); qq.extend(qq.FineUploader.prototype, qq.uiPrivateApi); qq.Templating = function(spec) { "use strict"; var FILE_ID_ATTR = "qq-file-id", FILE_CLASS_PREFIX = "qq-file-id-", THUMBNAIL_MAX_SIZE_ATTR = "qq-max-size", THUMBNAIL_SERVER_SCALE_ATTR = "qq-server-scale", HIDE_DROPZONE_ATTR = "qq-hide-dropzone", DROPZPONE_TEXT_ATTR = "qq-drop-area-text", IN_PROGRESS_CLASS = "qq-in-progress", HIDDEN_FOREVER_CLASS = "qq-hidden-forever", fileBatch = { content: document.createDocumentFragment(), map: {} }, isCancelDisabled = false, generatedThumbnails = 0, thumbnailQueueMonitorRunning = false, thumbGenerationQueue = [], thumbnailMaxSize = -1, options = { log: null, limits: { maxThumbs: 0, timeBetweenThumbs: 750 }, templateIdOrEl: "qq-template", containerEl: null, fileContainerEl: null, button: null, imageGenerator: null, classes: { hide: "qq-hide", editable: "qq-editable" }, placeholders: { waitUntilUpdate: false, thumbnailNotAvailable: null, waitingForThumbnail: null }, text: { paused: "Paused" } }, selectorClasses = { button: "qq-upload-button-selector", alertDialog: "qq-alert-dialog-selector", dialogCancelButton: "qq-cancel-button-selector", confirmDialog: "qq-confirm-dialog-selector", dialogMessage: "qq-dialog-message-selector", dialogOkButton: "qq-ok-button-selector", promptDialog: "qq-prompt-dialog-selector", uploader: "qq-uploader-selector", drop: "qq-upload-drop-area-selector", list: "qq-upload-list-selector", progressBarContainer: "qq-progress-bar-container-selector", progressBar: "qq-progress-bar-selector", totalProgressBarContainer: "qq-total-progress-bar-container-selector", totalProgressBar: "qq-total-progress-bar-selector", file: "qq-upload-file-selector", spinner: "qq-upload-spinner-selector", size: "qq-upload-size-selector", cancel: "qq-upload-cancel-selector", pause: "qq-upload-pause-selector", continueButton: "qq-upload-continue-selector", deleteButton: "qq-upload-delete-selector", retry: "qq-upload-retry-selector", statusText: "qq-upload-status-text-selector", editFilenameInput: "qq-edit-filename-selector", editNameIcon: "qq-edit-filename-icon-selector", dropText: "qq-upload-drop-area-text-selector", dropProcessing: "qq-drop-processing-selector", dropProcessingSpinner: "qq-drop-processing-spinner-selector", thumbnail: "qq-thumbnail-selector" }, previewGeneration = {}, cachedThumbnailNotAvailableImg = new qq.Promise(), cachedWaitingForThumbnailImg = new qq.Promise(), log, isEditElementsExist, isRetryElementExist, templateHtml, container, fileList, showThumbnails, serverScale, cacheThumbnailPlaceholders = function() { var notAvailableUrl = options.placeholders.thumbnailNotAvailable, waitingUrl = options.placeholders.waitingForThumbnail, spec = { maxSize: thumbnailMaxSize, scale: serverScale }; if (showThumbnails) { if (notAvailableUrl) { options.imageGenerator.generate(notAvailableUrl, new Image(), spec).then(function(updatedImg) { cachedThumbnailNotAvailableImg.success(updatedImg); }, function() { cachedThumbnailNotAvailableImg.failure(); log("Problem loading 'not available' placeholder image at " + notAvailableUrl, "error"); }); } else { cachedThumbnailNotAvailableImg.failure(); } if (waitingUrl) { options.imageGenerator.generate(waitingUrl, new Image(), spec).then(function(updatedImg) { cachedWaitingForThumbnailImg.success(updatedImg); }, function() { cachedWaitingForThumbnailImg.failure(); log("Problem loading 'waiting for thumbnail' placeholder image at " + waitingUrl, "error"); }); } else { cachedWaitingForThumbnailImg.failure(); } } }, displayWaitingImg = function(thumbnail) { var waitingImgPlacement = new qq.Promise(); cachedWaitingForThumbnailImg.then(function(img) { maybeScalePlaceholderViaCss(img, thumbnail); if (!thumbnail.src) { thumbnail.src = img.src; thumbnail.onload = function() { thumbnail.onload = null; show(thumbnail); waitingImgPlacement.success(); }; } else { waitingImgPlacement.success(); } }, function() { hide(thumbnail); waitingImgPlacement.success(); }); return waitingImgPlacement; }, generateNewPreview = function(id, blob, spec) { var thumbnail = getThumbnail(id); log("Generating new thumbnail for " + id); blob.qqThumbnailId = id; return options.imageGenerator.generate(blob, thumbnail, spec).then(function() { generatedThumbnails++; show(thumbnail); previewGeneration[id].success(); }, function() { previewGeneration[id].failure(); if (!options.placeholders.waitUntilUpdate) { maybeSetDisplayNotAvailableImg(id, thumbnail); } }); }, generateNextQueuedPreview = function() { if (thumbGenerationQueue.length) { thumbnailQueueMonitorRunning = true; var queuedThumbRequest = thumbGenerationQueue.shift(); if (queuedThumbRequest.update) { processUpdateQueuedPreviewRequest(queuedThumbRequest); } else { processNewQueuedPreviewRequest(queuedThumbRequest); } } else { thumbnailQueueMonitorRunning = false; } }, getCancel = function(id) { return getTemplateEl(getFile(id), selectorClasses.cancel); }, getContinue = function(id) { return getTemplateEl(getFile(id), selectorClasses.continueButton); }, getDialog = function(type) { return getTemplateEl(container, selectorClasses[type + "Dialog"]); }, getDelete = function(id) { return getTemplateEl(getFile(id), selectorClasses.deleteButton); }, getDropProcessing = function() { return getTemplateEl(container, selectorClasses.dropProcessing); }, getEditIcon = function(id) { return getTemplateEl(getFile(id), selectorClasses.editNameIcon); }, getFile = function(id) { return fileBatch.map[id] || qq(fileList).getFirstByClass(FILE_CLASS_PREFIX + id); }, getFilename = function(id) { return getTemplateEl(getFile(id), selectorClasses.file); }, getPause = function(id) { return getTemplateEl(getFile(id), selectorClasses.pause); }, getProgress = function(id) { if (id == null) { return getTemplateEl(container, selectorClasses.totalProgressBarContainer) || getTemplateEl(container, selectorClasses.totalProgressBar); } return getTemplateEl(getFile(id), selectorClasses.progressBarContainer) || getTemplateEl(getFile(id), selectorClasses.progressBar); }, getRetry = function(id) { return getTemplateEl(getFile(id), selectorClasses.retry); }, getSize = function(id) { return getTemplateEl(getFile(id), selectorClasses.size); }, getSpinner = function(id) { return getTemplateEl(getFile(id), selectorClasses.spinner); }, getTemplateEl = function(context, cssClass) { return context && qq(context).getFirstByClass(cssClass); }, getThumbnail = function(id) { return showThumbnails && getTemplateEl(getFile(id), selectorClasses.thumbnail); }, hide = function(el) { el && qq(el).addClass(options.classes.hide); }, maybeScalePlaceholderViaCss = function(placeholder, thumbnail) { var maxWidth = placeholder.style.maxWidth, maxHeight = placeholder.style.maxHeight; if (maxHeight && maxWidth && !thumbnail.style.maxWidth && !thumbnail.style.maxHeight) { qq(thumbnail).css({ maxWidth: maxWidth, maxHeight: maxHeight }); } }, maybeSetDisplayNotAvailableImg = function(id, thumbnail) { var previewing = previewGeneration[id] || new qq.Promise().failure(), notAvailableImgPlacement = new qq.Promise(); cachedThumbnailNotAvailableImg.then(function(img) { previewing.then(function() { notAvailableImgPlacement.success(); }, function() { maybeScalePlaceholderViaCss(img, thumbnail); thumbnail.onload = function() { thumbnail.onload = null; notAvailableImgPlacement.success(); }; thumbnail.src = img.src; show(thumbnail); }); }); return notAvailableImgPlacement; }, parseAndGetTemplate = function() { var scriptEl, scriptHtml, fileListNode, tempTemplateEl, fileListHtml, defaultButton, dropArea, thumbnail, dropProcessing, dropTextEl, uploaderEl; log("Parsing template"); if (options.templateIdOrEl == null) { throw new Error("You MUST specify either a template element or ID!"); } if (qq.isString(options.templateIdOrEl)) { scriptEl = document.getElementById(options.templateIdOrEl); if (scriptEl === null) { throw new Error(qq.format("Cannot find template script at ID '{}'!", options.templateIdOrEl)); } scriptHtml = scriptEl.innerHTML; } else { if (options.templateIdOrEl.innerHTML === undefined) { throw new Error("You have specified an invalid value for the template option! " + "It must be an ID or an Element."); } scriptHtml = options.templateIdOrEl.innerHTML; } scriptHtml = qq.trimStr(scriptHtml); tempTemplateEl = document.createElement("div"); tempTemplateEl.appendChild(qq.toElement(scriptHtml)); uploaderEl = qq(tempTemplateEl).getFirstByClass(selectorClasses.uploader); if (options.button) { defaultButton = qq(tempTemplateEl).getFirstByClass(selectorClasses.button); if (defaultButton) { qq(defaultButton).remove(); } } if (!qq.DragAndDrop || !qq.supportedFeatures.fileDrop) { dropProcessing = qq(tempTemplateEl).getFirstByClass(selectorClasses.dropProcessing); if (dropProcessing) { qq(dropProcessing).remove(); } } dropArea = qq(tempTemplateEl).getFirstByClass(selectorClasses.drop); if (dropArea && !qq.DragAndDrop) { log("DnD module unavailable.", "info"); qq(dropArea).remove(); } if (!qq.supportedFeatures.fileDrop) { uploaderEl.removeAttribute(DROPZPONE_TEXT_ATTR); if (dropArea && qq(dropArea).hasAttribute(HIDE_DROPZONE_ATTR)) { qq(dropArea).css({ display: "none" }); } } else if (qq(uploaderEl).hasAttribute(DROPZPONE_TEXT_ATTR) && dropArea) { dropTextEl = qq(dropArea).getFirstByClass(selectorClasses.dropText); dropTextEl && qq(dropTextEl).remove(); } thumbnail = qq(tempTemplateEl).getFirstByClass(selectorClasses.thumbnail); if (!showThumbnails) { thumbnail && qq(thumbnail).remove(); } else if (thumbnail) { thumbnailMaxSize = parseInt(thumbnail.getAttribute(THUMBNAIL_MAX_SIZE_ATTR)); thumbnailMaxSize = thumbnailMaxSize > 0 ? thumbnailMaxSize : null; serverScale = qq(thumbnail).hasAttribute(THUMBNAIL_SERVER_SCALE_ATTR); } showThumbnails = showThumbnails && thumbnail; isEditElementsExist = qq(tempTemplateEl).getByClass(selectorClasses.editFilenameInput).length > 0; isRetryElementExist = qq(tempTemplateEl).getByClass(selectorClasses.retry).length > 0; fileListNode = qq(tempTemplateEl).getFirstByClass(selectorClasses.list); if (fileListNode == null) { throw new Error("Could not find the file list container in the template!"); } fileListHtml = fileListNode.innerHTML; fileListNode.innerHTML = ""; if (tempTemplateEl.getElementsByTagName("DIALOG").length) { document.createElement("dialog"); } log("Template parsing complete"); return { template: qq.trimStr(tempTemplateEl.innerHTML), fileTemplate: qq.trimStr(fileListHtml) }; }, prependFile = function(el, index, fileList) { var parentEl = fileList, beforeEl = parentEl.firstChild; if (index > 0) { beforeEl = qq(parentEl).children()[index].nextSibling; } parentEl.insertBefore(el, beforeEl); }, processNewQueuedPreviewRequest = function(queuedThumbRequest) { var id = queuedThumbRequest.id, optFileOrBlob = queuedThumbRequest.optFileOrBlob, relatedThumbnailId = optFileOrBlob && optFileOrBlob.qqThumbnailId, thumbnail = getThumbnail(id), spec = { customResizeFunction: queuedThumbRequest.customResizeFunction, maxSize: thumbnailMaxSize, orient: true, scale: true }; if (qq.supportedFeatures.imagePreviews) { if (thumbnail) { if (options.limits.maxThumbs && options.limits.maxThumbs <= generatedThumbnails) { maybeSetDisplayNotAvailableImg(id, thumbnail); generateNextQueuedPreview(); } else { displayWaitingImg(thumbnail).done(function() { previewGeneration[id] = new qq.Promise(); previewGeneration[id].done(function() { setTimeout(generateNextQueuedPreview, options.limits.timeBetweenThumbs); }); if (relatedThumbnailId != null) { useCachedPreview(id, relatedThumbnailId); } else { generateNewPreview(id, optFileOrBlob, spec); } }); } } else { generateNextQueuedPreview(); } } else if (thumbnail) { displayWaitingImg(thumbnail); generateNextQueuedPreview(); } }, processUpdateQueuedPreviewRequest = function(queuedThumbRequest) { var id = queuedThumbRequest.id, thumbnailUrl = queuedThumbRequest.thumbnailUrl, showWaitingImg = queuedThumbRequest.showWaitingImg, thumbnail = getThumbnail(id), spec = { customResizeFunction: queuedThumbRequest.customResizeFunction, scale: serverScale, maxSize: thumbnailMaxSize }; if (thumbnail) { if (thumbnailUrl) { if (options.limits.maxThumbs && options.limits.maxThumbs <= generatedThumbnails) { maybeSetDisplayNotAvailableImg(id, thumbnail); generateNextQueuedPreview(); } else { if (showWaitingImg) { displayWaitingImg(thumbnail); } return options.imageGenerator.generate(thumbnailUrl, thumbnail, spec).then(function() { show(thumbnail); generatedThumbnails++; setTimeout(generateNextQueuedPreview, options.limits.timeBetweenThumbs); }, function() { maybeSetDisplayNotAvailableImg(id, thumbnail); setTimeout(generateNextQueuedPreview, options.limits.timeBetweenThumbs); }); } } else { maybeSetDisplayNotAvailableImg(id, thumbnail); generateNextQueuedPreview(); } } }, setProgressBarWidth = function(id, percent) { var bar = getProgress(id), progressBarSelector = id == null ? selectorClasses.totalProgressBar : selectorClasses.progressBar; if (bar && !qq(bar).hasClass(progressBarSelector)) { bar = qq(bar).getFirstByClass(progressBarSelector); } if (bar) { qq(bar).css({ width: percent + "%" }); bar.setAttribute("aria-valuenow", percent); } }, show = function(el) { el && qq(el).removeClass(options.classes.hide); }, useCachedPreview = function(targetThumbnailId, cachedThumbnailId) { var targetThumbnail = getThumbnail(targetThumbnailId), cachedThumbnail = getThumbnail(cachedThumbnailId); log(qq.format("ID {} is the same file as ID {}. Will use generated thumbnail from ID {} instead.", targetThumbnailId, cachedThumbnailId, cachedThumbnailId)); previewGeneration[cachedThumbnailId].then(function() { generatedThumbnails++; previewGeneration[targetThumbnailId].success(); log(qq.format("Now using previously generated thumbnail created for ID {} on ID {}.", cachedThumbnailId, targetThumbnailId)); targetThumbnail.src = cachedThumbnail.src; show(targetThumbnail); }, function() { previewGeneration[targetThumbnailId].failure(); if (!options.placeholders.waitUntilUpdate) { maybeSetDisplayNotAvailableImg(targetThumbnailId, targetThumbnail); } }); }; qq.extend(options, spec); log = options.log; if (!qq.supportedFeatures.imagePreviews) { options.limits.timeBetweenThumbs = 0; options.limits.maxThumbs = 0; } container = options.containerEl; showThumbnails = options.imageGenerator !== undefined; templateHtml = parseAndGetTemplate(); cacheThumbnailPlaceholders(); qq.extend(this, { render: function() { log("Rendering template in DOM."); generatedThumbnails = 0; container.innerHTML = templateHtml.template; hide(getDropProcessing()); this.hideTotalProgress(); fileList = options.fileContainerEl || getTemplateEl(container, selectorClasses.list); log("Template rendering complete"); }, renderFailure: function(message) { var cantRenderEl = qq.toElement(message); container.innerHTML = ""; container.appendChild(cantRenderEl); }, reset: function() { this.render(); }, clearFiles: function() { fileList.innerHTML = ""; }, disableCancel: function() { isCancelDisabled = true; }, addFile: function(id, name, prependInfo, hideForever, batch) { var fileEl = qq.toElement(templateHtml.fileTemplate), fileNameEl = getTemplateEl(fileEl, selectorClasses.file), uploaderEl = getTemplateEl(container, selectorClasses.uploader), fileContainer = batch ? fileBatch.content : fileList, thumb; if (batch) { fileBatch.map[id] = fileEl; } qq(fileEl).addClass(FILE_CLASS_PREFIX + id); uploaderEl.removeAttribute(DROPZPONE_TEXT_ATTR); if (fileNameEl) { qq(fileNameEl).setText(name); fileNameEl.setAttribute("title", name); } fileEl.setAttribute(FILE_ID_ATTR, id); if (prependInfo) { prependFile(fileEl, prependInfo.index, fileContainer); } else { fileContainer.appendChild(fileEl); } if (hideForever) { fileEl.style.display = "none"; qq(fileEl).addClass(HIDDEN_FOREVER_CLASS); } else { hide(getProgress(id)); hide(getSize(id)); hide(getDelete(id)); hide(getRetry(id)); hide(getPause(id)); hide(getContinue(id)); if (isCancelDisabled) { this.hideCancel(id); } thumb = getThumbnail(id); if (thumb && !thumb.src) { cachedWaitingForThumbnailImg.then(function(waitingImg) { thumb.src = waitingImg.src; if (waitingImg.style.maxHeight && waitingImg.style.maxWidth) { qq(thumb).css({ maxHeight: waitingImg.style.maxHeight, maxWidth: waitingImg.style.maxWidth }); } show(thumb); }); } } }, addFileToCache: function(id, name, prependInfo, hideForever) { this.addFile(id, name, prependInfo, hideForever, true); }, addCacheToDom: function() { fileList.appendChild(fileBatch.content); fileBatch.content = document.createDocumentFragment(); fileBatch.map = {}; }, removeFile: function(id) { qq(getFile(id)).remove(); }, getFileId: function(el) { var currentNode = el; if (currentNode) { while (currentNode.getAttribute(FILE_ID_ATTR) == null) { currentNode = currentNode.parentNode; } return parseInt(currentNode.getAttribute(FILE_ID_ATTR)); } }, getFileList: function() { return fileList; }, markFilenameEditable: function(id) { var filename = getFilename(id); filename && qq(filename).addClass(options.classes.editable); }, updateFilename: function(id, name) { var filenameEl = getFilename(id); if (filenameEl) { qq(filenameEl).setText(name); filenameEl.setAttribute("title", name); } }, hideFilename: function(id) { hide(getFilename(id)); }, showFilename: function(id) { show(getFilename(id)); }, isFileName: function(el) { return qq(el).hasClass(selectorClasses.file); }, getButton: function() { return options.button || getTemplateEl(container, selectorClasses.button); }, hideDropProcessing: function() { hide(getDropProcessing()); }, showDropProcessing: function() { show(getDropProcessing()); }, getDropZone: function() { return getTemplateEl(container, selectorClasses.drop); }, isEditFilenamePossible: function() { return isEditElementsExist; }, hideRetry: function(id) { hide(getRetry(id)); }, isRetryPossible: function() { return isRetryElementExist; }, showRetry: function(id) { show(getRetry(id)); }, getFileContainer: function(id) { return getFile(id); }, showEditIcon: function(id) { var icon = getEditIcon(id); icon && qq(icon).addClass(options.classes.editable); }, isHiddenForever: function(id) { return qq(getFile(id)).hasClass(HIDDEN_FOREVER_CLASS); }, hideEditIcon: function(id) { var icon = getEditIcon(id); icon && qq(icon).removeClass(options.classes.editable); }, isEditIcon: function(el) { return qq(el).hasClass(selectorClasses.editNameIcon, true); }, getEditInput: function(id) { return getTemplateEl(getFile(id), selectorClasses.editFilenameInput); }, isEditInput: function(el) { return qq(el).hasClass(selectorClasses.editFilenameInput, true); }, updateProgress: function(id, loaded, total) { var bar = getProgress(id), percent; if (bar && total > 0) { percent = Math.round(loaded / total * 100); if (percent === 100) { hide(bar); } else { show(bar); } setProgressBarWidth(id, percent); } }, updateTotalProgress: function(loaded, total) { this.updateProgress(null, loaded, total); }, hideProgress: function(id) { var bar = getProgress(id); bar && hide(bar); }, hideTotalProgress: function() { this.hideProgress(); }, resetProgress: function(id) { setProgressBarWidth(id, 0); this.hideTotalProgress(id); }, resetTotalProgress: function() { this.resetProgress(); }, showCancel: function(id) { if (!isCancelDisabled) { var cancel = getCancel(id); cancel && qq(cancel).removeClass(options.classes.hide); } }, hideCancel: function(id) { hide(getCancel(id)); }, isCancel: function(el) { return qq(el).hasClass(selectorClasses.cancel, true); }, allowPause: function(id) { show(getPause(id)); hide(getContinue(id)); }, uploadPaused: function(id) { this.setStatusText(id, options.text.paused); this.allowContinueButton(id); hide(getSpinner(id)); }, hidePause: function(id) { hide(getPause(id)); }, isPause: function(el) { return qq(el).hasClass(selectorClasses.pause, true); }, isContinueButton: function(el) { return qq(el).hasClass(selectorClasses.continueButton, true); }, allowContinueButton: function(id) { show(getContinue(id)); hide(getPause(id)); }, uploadContinued: function(id) { this.setStatusText(id, ""); this.allowPause(id); show(getSpinner(id)); }, showDeleteButton: function(id) { show(getDelete(id)); }, hideDeleteButton: function(id) { hide(getDelete(id)); }, isDeleteButton: function(el) { return qq(el).hasClass(selectorClasses.deleteButton, true); }, isRetry: function(el) { return qq(el).hasClass(selectorClasses.retry, true); }, updateSize: function(id, text) { var size = getSize(id); if (size) { show(size); qq(size).setText(text); } }, setStatusText: function(id, text) { var textEl = getTemplateEl(getFile(id), selectorClasses.statusText); if (textEl) { if (text == null) { qq(textEl).clearText(); } else { qq(textEl).setText(text); } } }, hideSpinner: function(id) { qq(getFile(id)).removeClass(IN_PROGRESS_CLASS); hide(getSpinner(id)); }, showSpinner: function(id) { qq(getFile(id)).addClass(IN_PROGRESS_CLASS); show(getSpinner(id)); }, generatePreview: function(id, optFileOrBlob, customResizeFunction) { if (!this.isHiddenForever(id)) { thumbGenerationQueue.push({ id: id, customResizeFunction: customResizeFunction, optFileOrBlob: optFileOrBlob }); !thumbnailQueueMonitorRunning && generateNextQueuedPreview(); } }, updateThumbnail: function(id, thumbnailUrl, showWaitingImg, customResizeFunction) { if (!this.isHiddenForever(id)) { thumbGenerationQueue.push({ customResizeFunction: customResizeFunction, update: true, id: id, thumbnailUrl: thumbnailUrl, showWaitingImg: showWaitingImg }); !thumbnailQueueMonitorRunning && generateNextQueuedPreview(); } }, hasDialog: function(type) { return qq.supportedFeatures.dialogElement && !!getDialog(type); }, showDialog: function(type, message, defaultValue) { var dialog = getDialog(type), messageEl = getTemplateEl(dialog, selectorClasses.dialogMessage), inputEl = dialog.getElementsByTagName("INPUT")[0], cancelBtn = getTemplateEl(dialog, selectorClasses.dialogCancelButton), okBtn = getTemplateEl(dialog, selectorClasses.dialogOkButton), promise = new qq.Promise(), closeHandler = function() { cancelBtn.removeEventListener("click", cancelClickHandler); okBtn && okBtn.removeEventListener("click", okClickHandler); promise.failure(); }, cancelClickHandler = function() { cancelBtn.removeEventListener("click", cancelClickHandler); dialog.close(); }, okClickHandler = function() { dialog.removeEventListener("close", closeHandler); okBtn.removeEventListener("click", okClickHandler); dialog.close(); promise.success(inputEl && inputEl.value); }; dialog.addEventListener("close", closeHandler); cancelBtn.addEventListener("click", cancelClickHandler); okBtn && okBtn.addEventListener("click", okClickHandler); if (inputEl) { inputEl.value = defaultValue; } messageEl.textContent = message; dialog.showModal(); return promise; } }); }; qq.UiEventHandler = function(s, protectedApi) { "use strict"; var disposer = new qq.DisposeSupport(), spec = { eventType: "click", attachTo: null, onHandled: function(target, event) {} }; qq.extend(this, { addHandler: function(element) { addHandler(element); }, dispose: function() { disposer.dispose(); } }); function addHandler(element) { disposer.attach(element, spec.eventType, function(event) { event = event || window.event; var target = event.target || event.srcElement; spec.onHandled(target, event); }); } qq.extend(protectedApi, { getFileIdFromItem: function(item) { return item.qqFileId; }, getDisposeSupport: function() { return disposer; } }); qq.extend(spec, s); if (spec.attachTo) { addHandler(spec.attachTo); } }; qq.FileButtonsClickHandler = function(s) { "use strict"; var inheritedInternalApi = {}, spec = { templating: null, log: function(message, lvl) {}, onDeleteFile: function(fileId) {}, onCancel: function(fileId) {}, onRetry: function(fileId) {}, onPause: function(fileId) {}, onContinue: function(fileId) {}, onGetName: function(fileId) {} }, buttonHandlers = { cancel: function(id) { spec.onCancel(id); }, retry: function(id) { spec.onRetry(id); }, deleteButton: function(id) { spec.onDeleteFile(id); }, pause: function(id) { spec.onPause(id); }, continueButton: function(id) { spec.onContinue(id); } }; function examineEvent(target, event) { qq.each(buttonHandlers, function(buttonType, handler) { var firstLetterCapButtonType = buttonType.charAt(0).toUpperCase() + buttonType.slice(1), fileId; if (spec.templating["is" + firstLetterCapButtonType](target)) { fileId = spec.templating.getFileId(target); qq.preventDefault(event); spec.log(qq.format("Detected valid file button click event on file '{}', ID: {}.", spec.onGetName(fileId), fileId)); handler(fileId); return false; } }); } qq.extend(spec, s); spec.eventType = "click"; spec.onHandled = examineEvent; spec.attachTo = spec.templating.getFileList(); qq.extend(this, new qq.UiEventHandler(spec, inheritedInternalApi)); }; qq.FilenameClickHandler = function(s) { "use strict"; var inheritedInternalApi = {}, spec = { templating: null, log: function(message, lvl) {}, classes: { file: "qq-upload-file", editNameIcon: "qq-edit-filename-icon" }, onGetUploadStatus: function(fileId) {}, onGetName: function(fileId) {} }; qq.extend(spec, s); function examineEvent(target, event) { if (spec.templating.isFileName(target) || spec.templating.isEditIcon(target)) { var fileId = spec.templating.getFileId(target), status = spec.onGetUploadStatus(fileId); if (status === qq.status.SUBMITTED) { spec.log(qq.format("Detected valid filename click event on file '{}', ID: {}.", spec.onGetName(fileId), fileId)); qq.preventDefault(event); inheritedInternalApi.handleFilenameEdit(fileId, target, true); } } } spec.eventType = "click"; spec.onHandled = examineEvent; qq.extend(this, new qq.FilenameEditHandler(spec, inheritedInternalApi)); }; qq.FilenameInputFocusInHandler = function(s, inheritedInternalApi) { "use strict"; var spec = { templating: null, onGetUploadStatus: function(fileId) {}, log: function(message, lvl) {} }; if (!inheritedInternalApi) { inheritedInternalApi = {}; } function handleInputFocus(target, event) { if (spec.templating.isEditInput(target)) { var fileId = spec.templating.getFileId(target), status = spec.onGetUploadStatus(fileId); if (status === qq.status.SUBMITTED) { spec.log(qq.format("Detected valid filename input focus event on file '{}', ID: {}.", spec.onGetName(fileId), fileId)); inheritedInternalApi.handleFilenameEdit(fileId, target); } } } spec.eventType = "focusin"; spec.onHandled = handleInputFocus; qq.extend(spec, s); qq.extend(this, new qq.FilenameEditHandler(spec, inheritedInternalApi)); }; qq.FilenameInputFocusHandler = function(spec) { "use strict"; spec.eventType = "focus"; spec.attachTo = null; qq.extend(this, new qq.FilenameInputFocusInHandler(spec, {})); }; qq.FilenameEditHandler = function(s, inheritedInternalApi) { "use strict"; var spec = { templating: null, log: function(message, lvl) {}, onGetUploadStatus: function(fileId) {}, onGetName: function(fileId) {}, onSetName: function(fileId, newName) {}, onEditingStatusChange: function(fileId, isEditing) {} }; function getFilenameSansExtension(fileId) { var filenameSansExt = spec.onGetName(fileId), extIdx = filenameSansExt.lastIndexOf("."); if (extIdx > 0) { filenameSansExt = filenameSansExt.substr(0, extIdx); } return filenameSansExt; } function getOriginalExtension(fileId) { var origName = spec.onGetName(fileId); return qq.getExtension(origName); } function handleNameUpdate(newFilenameInputEl, fileId) { var newName = newFilenameInputEl.value, origExtension; if (newName !== undefined && qq.trimStr(newName).length > 0) { origExtension = getOriginalExtension(fileId); if (origExtension !== undefined) { newName = newName + "." + origExtension; } spec.onSetName(fileId, newName); } spec.onEditingStatusChange(fileId, false); } function registerInputBlurHandler(inputEl, fileId) { inheritedInternalApi.getDisposeSupport().attach(inputEl, "blur", function() { handleNameUpdate(inputEl, fileId); }); } function registerInputEnterKeyHandler(inputEl, fileId) { inheritedInternalApi.getDisposeSupport().attach(inputEl, "keyup", function(event) { var code = event.keyCode || event.which; if (code === 13) { handleNameUpdate(inputEl, fileId); } }); } qq.extend(spec, s); spec.attachTo = spec.templating.getFileList(); qq.extend(this, new qq.UiEventHandler(spec, inheritedInternalApi)); qq.extend(inheritedInternalApi, { handleFilenameEdit: function(id, target, focusInput) { var newFilenameInputEl = spec.templating.getEditInput(id); spec.onEditingStatusChange(id, true); newFilenameInputEl.value = getFilenameSansExtension(id); if (focusInput) { newFilenameInputEl.focus(); } registerInputBlurHandler(newFilenameInputEl, id); registerInputEnterKeyHandler(newFilenameInputEl, id); } }); }; (function() { "use strict"; qq.azure.FineUploader = function(o) { var options = { failedUploadTextDisplay: { mode: "custom" } }; qq.extend(options, o, true); qq.FineUploader.call(this, options, "azure"); }; qq.extend(qq.azure.FineUploader.prototype, qq.azure.FineUploaderBasic.prototype); qq.extend(qq.azure.FineUploader.prototype, qq.uiPublicApi); qq.extend(qq.azure.FineUploader.prototype, qq.uiPrivateApi); qq.extend(qq.azure.FineUploader.prototype, {}); })(); })(window); //# sourceMappingURL=azure.jquery.fine-uploader.js.map
define(function() { var theme = { // 默认色板 color: [ '#2ec7c9','#b6a2de','#5ab1ef','#ffb980','#d87a80', '#8d98b3','#e5cf0d','#97b552','#95706d','#dc69aa', '#07a2a4','#9a7fd1','#588dd5','#f5994e','#c05050', '#59678c','#c9ab00','#7eb00a','#6f5553','#c14089' ], // 图表标题 title: { itemGap: 8, textStyle: { fontWeight: 'normal', color: '#008acd' // 主标题文字颜色 } }, // 图例 legend: { itemGap: 8 }, // 值域 dataRange: { itemWidth: 15, //color:['#1e90ff','#afeeee'] color: ['#2ec7c9','#b6a2de'] }, toolbox: { color : ['#1e90ff', '#1e90ff', '#1e90ff', '#1e90ff'], effectiveColor : '#ff4500', itemGap: 8 }, // 提示框 tooltip: { backgroundColor: 'rgba(50,50,50,0.5)', // 提示背景颜色,默认为透明度为0.7的黑色 axisPointer : { // 坐标轴指示器,坐标轴触发有效 type : 'line', // 默认为直线,可选为:'line' | 'shadow' lineStyle : { // 直线指示器样式设置 color: '#008acd' }, crossStyle: { color: '#008acd' }, shadowStyle : { // 阴影指示器样式设置 color: 'rgba(200,200,200,0.2)' } } }, // 区域缩放控制器 dataZoom: { dataBackgroundColor: '#efefff', // 数据背景颜色 fillerColor: 'rgba(182,162,222,0.2)', // 填充颜色 handleColor: '#008acd' // 手柄颜色 }, // 网格 grid: { borderColor: '#eee' }, // 类目轴 categoryAxis: { axisLine: { // 坐标轴线 lineStyle: { // 属性lineStyle控制线条样式 color: '#008acd' } }, splitLine: { // 分隔线 lineStyle: { // 属性lineStyle(详见lineStyle)控制线条样式 color: ['#eee'] } } }, // 数值型坐标轴默认参数 valueAxis: { axisLine: { // 坐标轴线 lineStyle: { // 属性lineStyle控制线条样式 color: '#008acd' } }, splitArea : { show : true, areaStyle : { color: ['rgba(250,250,250,0.1)','rgba(200,200,200,0.1)'] } }, splitLine: { // 分隔线 lineStyle: { // 属性lineStyle(详见lineStyle)控制线条样式 color: ['#eee'] } } }, polar : { axisLine: { // 坐标轴线 lineStyle: { // 属性lineStyle控制线条样式 color: '#ddd' } }, splitArea : { show : true, areaStyle : { color: ['rgba(250,250,250,0.2)','rgba(200,200,200,0.2)'] } }, splitLine : { lineStyle : { color : '#ddd' } } }, timeline : { lineStyle : { color : '#008acd' }, controlStyle : { normal : { color : '#008acd'}, emphasis : { color : '#008acd'} }, symbol : 'emptyCircle', symbolSize : 3 }, // 柱形图默认参数 bar: { itemStyle: { normal: { barBorderRadius: 5 }, emphasis: { barBorderRadius: 5 } } }, // 折线图默认参数 line: { smooth : true, symbol: 'emptyCircle', // 拐点图形类型 symbolSize: 3 // 拐点图形大小 }, // K线图默认参数 k: { itemStyle: { normal: { color: '#d87a80', // 阳线填充颜色 color0: '#2ec7c9', // 阴线填充颜色 lineStyle: { width: 1, color: '#d87a80', // 阳线边框颜色 color0: '#2ec7c9' // 阴线边框颜色 } } } }, // 散点图默认参数 scatter: { symbol: 'circle', // 图形类型 symbolSize: 4 // 图形大小,半宽(半径)参数,当图形为方向或菱形则总宽度为symbolSize * 2 }, // 雷达图默认参数 radar : { symbol: 'emptyCircle', // 图形类型 symbolSize:3 //symbol: null, // 拐点图形类型 //symbolRotate : null, // 图形旋转控制 }, map: { itemStyle: { normal: { areaStyle: { color: '#ddd' }, label: { textStyle: { color: '#d87a80' } } }, emphasis: { // 也是选中样式 areaStyle: { color: '#fe994e' }, label: { textStyle: { color: 'rgb(100,0,0)' } } } } }, force : { itemStyle: { normal: { linkStyle : { strokeColor : '#1e90ff' } } } }, chord : { padding : 4, itemStyle : { normal : { lineStyle : { width : 1, color : 'rgba(128, 128, 128, 0.5)' }, chordStyle : { lineStyle : { width : 1, color : 'rgba(128, 128, 128, 0.5)' } } }, emphasis : { lineStyle : { width : 1, color : 'rgba(128, 128, 128, 0.5)' }, chordStyle : { lineStyle : { width : 1, color : 'rgba(128, 128, 128, 0.5)' } } } } }, gauge : { startAngle: 225, endAngle : -45, axisLine: { // 坐标轴线 show: true, // 默认显示,属性show控制显示与否 lineStyle: { // 属性lineStyle控制线条样式 color: [[0.2, '#2ec7c9'],[0.8, '#5ab1ef'],[1, '#d87a80']], width: 10 } }, axisTick: { // 坐标轴小标记 splitNumber: 10, // 每份split细分多少段 length :15, // 属性length控制线长 lineStyle: { // 属性lineStyle控制线条样式 color: 'auto' } }, axisLabel: { // 坐标轴文本标签,详见axis.axisLabel textStyle: { // 其余属性默认使用全局文本样式,详见TEXTSTYLE color: 'auto' } }, splitLine: { // 分隔线 length :22, // 属性length控制线长 lineStyle: { // 属性lineStyle(详见lineStyle)控制线条样式 color: 'auto' } }, pointer : { width : 5, color : 'auto' }, title : { textStyle: { // 其余属性默认使用全局文本样式,详见TEXTSTYLE color: '#333' } }, detail : { textStyle: { // 其余属性默认使用全局文本样式,详见TEXTSTYLE color: 'auto' } } }, textStyle: { fontFamily: '微软雅黑, Arial, Verdana, sans-serif' } } return theme; });
"use strict"; var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard"); var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); var _exportNames = { accordionDetailsClasses: true }; Object.defineProperty(exports, "default", { enumerable: true, get: function () { return _AccordionDetails.default; } }); Object.defineProperty(exports, "accordionDetailsClasses", { enumerable: true, get: function () { return _accordionDetailsClasses.default; } }); var _AccordionDetails = _interopRequireDefault(require("./AccordionDetails")); var _accordionDetailsClasses = _interopRequireWildcard(require("./accordionDetailsClasses")); Object.keys(_accordionDetailsClasses).forEach(function (key) { if (key === "default" || key === "__esModule") return; if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; if (key in exports && exports[key] === _accordionDetailsClasses[key]) return; Object.defineProperty(exports, key, { enumerable: true, get: function () { return _accordionDetailsClasses[key]; } }); });
'use strict'; exports.__esModule = true; var _postcssSelectorParser = require('postcss-selector-parser'); var _postcssSelectorParser2 = _interopRequireDefault(_postcssSelectorParser); var _exists = require('../exists'); var _exists2 = _interopRequireDefault(_exists); var _isMixin = require('../isMixin'); var _isMixin2 = _interopRequireDefault(_isMixin); var _plugin = require('../plugin'); var _plugin2 = _interopRequireDefault(_plugin); var _browsers = require('../dictionary/browsers'); var _identifiers = require('../dictionary/identifiers'); var _postcss = require('../dictionary/postcss'); var _tags = require('../dictionary/tags'); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function analyse(ctx, rule) { return function (selectors) { selectors.each(function (selector) { if ((0, _exists2.default)(selector, 0, _tags.HTML) && ((0, _exists2.default)(selector, 1, '>') || (0, _exists2.default)(selector, 1, '~')) && selector.at(2) && selector.at(2).type === 'comment' && (0, _exists2.default)(selector, 3, ' ') && (0, _exists2.default)(selector, 4, _tags.BODY) && (0, _exists2.default)(selector, 5, ' ') && selector.at(6)) { ctx.push(rule, { identifier: _identifiers.SELECTOR, hack: selector.toString() }); } }); }; } exports.default = (0, _plugin2.default)([_browsers.IE_5_5, _browsers.IE_6, _browsers.IE_7], [_postcss.RULE], function (rule) { if ((0, _isMixin2.default)(rule)) { return; } if (rule.raws.selector && rule.raws.selector.raw) { (0, _postcssSelectorParser2.default)(analyse(this, rule)).process(rule.raws.selector.raw); } }); module.exports = exports['default'];
angular.module('material.core') .factory('$mdConstant', MdConstantFactory); /** * Factory function that creates the grab-bag $mdConstant service. * @ngInject */ function MdConstantFactory($sniffer) { var webkit = /webkit/i.test($sniffer.vendorPrefix); function vendorProperty(name) { return webkit ? ('webkit' + name.charAt(0).toUpperCase() + name.substring(1)) : name; } return { KEY_CODE: { COMMA: 188, SEMICOLON : 186, ENTER: 13, ESCAPE: 27, SPACE: 32, PAGE_UP: 33, PAGE_DOWN: 34, END: 35, HOME: 36, LEFT_ARROW : 37, UP_ARROW : 38, RIGHT_ARROW : 39, DOWN_ARROW : 40, TAB : 9, BACKSPACE: 8, DELETE: 46 }, CSS: { /* Constants */ TRANSITIONEND: 'transitionend' + (webkit ? ' webkitTransitionEnd' : ''), ANIMATIONEND: 'animationend' + (webkit ? ' webkitAnimationEnd' : ''), TRANSFORM: vendorProperty('transform'), TRANSFORM_ORIGIN: vendorProperty('transformOrigin'), TRANSITION: vendorProperty('transition'), TRANSITION_DURATION: vendorProperty('transitionDuration'), ANIMATION_PLAY_STATE: vendorProperty('animationPlayState'), ANIMATION_DURATION: vendorProperty('animationDuration'), ANIMATION_NAME: vendorProperty('animationName'), ANIMATION_TIMING: vendorProperty('animationTimingFunction'), ANIMATION_DIRECTION: vendorProperty('animationDirection') }, /** * As defined in core/style/variables.scss * * $layout-breakpoint-xs: 600px !default; * $layout-breakpoint-sm: 960px !default; * $layout-breakpoint-md: 1280px !default; * $layout-breakpoint-lg: 1920px !default; * */ MEDIA: { 'xs' : '(max-width: 599px)' , 'gt-xs' : '(min-width: 600px)' , 'sm' : '(min-width: 600px) and (max-width: 959px)' , 'gt-sm' : '(min-width: 960px)' , 'md' : '(min-width: 960px) and (max-width: 1279px)' , 'gt-md' : '(min-width: 1280px)' , 'lg' : '(min-width: 1280px) and (max-width: 1919px)', 'gt-lg' : '(min-width: 1920px)' , 'xl' : '(min-width: 1920px)' , 'print' : 'print' }, MEDIA_PRIORITY: [ 'xl', 'gt-lg', 'lg', 'gt-md', 'md', 'gt-sm', 'sm', 'gt-xs', 'xs', 'print' ] }; }
/*! instantsearch-googlemaps 1.2.3 | © Algolia | github.com/instantsearch/instantsearch-googlemaps */(function webpackUniversalModuleDefinition(root, factory) { if(typeof exports === 'object' && typeof module === 'object') module.exports = factory(require("React"), require("ReactDOM"), require("instantsearch")); else if(typeof define === 'function' && define.amd) define(["React", "ReactDOM", "instantsearch"], factory); else if(typeof exports === 'object') exports["instantsearchGoogleMaps"] = factory(require("React"), require("ReactDOM"), require("instantsearch")); else root["instantsearchGoogleMaps"] = factory(root["React"], root["ReactDOM"], root["instantsearch"]); })(this, function(__WEBPACK_EXTERNAL_MODULE_1__, __WEBPACK_EXTERNAL_MODULE_2__, __WEBPACK_EXTERNAL_MODULE_58__) { return /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) /******/ return installedModules[moduleId].exports; /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ exports: {}, /******/ id: moduleId, /******/ loaded: false /******/ }; /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ // Flag the module as loaded /******/ module.loaded = true; /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ // Load entry module and return exports /******/ return __webpack_require__(0); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /***/ function(module, exports, __webpack_require__) { /* global google */ 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _react = __webpack_require__(1); var _react2 = _interopRequireDefault(_react); var _reactDom = __webpack_require__(2); var _reactDom2 = _interopRequireDefault(_reactDom); var _srcGoogleMapsJs = __webpack_require__(3); var _srcGoogleMapsJs2 = _interopRequireDefault(_srcGoogleMapsJs); var _instantsearchJs = __webpack_require__(58); var _instantsearchJs2 = _interopRequireDefault(_instantsearchJs); /** * algolia/instantsearch.js widget to display your Algolia geo hits on a map using Google Maps APIs * @param {DOMElement} options.container Where to insert the map in the document. This is required. * @param {function} [options.prepareMarkerData] Function Called for every hit, * this is the moment where you can select the label and title * for the marker. This function should return an object in the form of `{label, title}`. * * Example: * * ```js * function prepareMarkerData(hit, index, hits) { * return { * label: hit.name, * title: hit.description * } * } * ``` * * The `label` first letter will be displayed on the marker on the map. * * The `title` will be displayed when hovering the marker. * * By default we use the current hit index in the results as the label and the hit `ObjectID` for the title. * when hovering the marker * @param {boolean} [options.refineOnMapInteraction=false] Should we refine the search * on map interaction, default to false * @return {Object} */ function googleMaps(_ref) { var container = _ref.container; var _ref$refineOnMapInteraction = _ref.refineOnMapInteraction; var refineOnMapInteraction = _ref$refineOnMapInteraction === undefined ? false : _ref$refineOnMapInteraction; var _ref$prepareMarkerData = _ref.prepareMarkerData; var prepareMarkerData = _ref$prepareMarkerData === undefined ? function (hit, index) { return { label: '' + index, title: hit.objectID }; } : _ref$prepareMarkerData; var widget = { _refine: function _refine(_ref2, userRefine) { var helper = _ref2.helper; var p1 = userRefine.bounds.getNorthEast(); var p2 = userRefine.bounds.getSouthWest(); var box = [p1.lat(), p1.lng(), p2.lat(), p2.lng()]; this._lastUserRefine = userRefine; helper.setQueryParameter('insideBoundingBox', box.join(',')).search().setQueryParameter('insideBoundingBox', undefined); }, render: function render(_ref3) { var _this = this; var results = _ref3.results; var helper = _ref3.helper; var zoom = undefined; var center = undefined; var markers = results.hits.map(function (hit, index) { return _extends({ position: new google.maps.LatLng(hit._geoloc), id: hit.objectID }, prepareMarkerData(hit, index, results.hits)); }); if (markers.length === 0) { zoom = 1; center = new google.maps.LatLng({ lat: 48.797885, lng: 2.337034 }); } else if (this._lastUserRefine) { zoom = this._lastUserRefine.zoom; center = this._lastUserRefine.center; this._lastUserRefine = false; } else { (function () { var bounds = new google.maps.LatLngBounds(); markers.forEach(function (marker) { return bounds.extend(marker.position); }); zoom = _this._getBestZoomLevel(bounds, container.getBoundingClientRect()); center = bounds.getCenter(); })(); } _reactDom2['default'].render(_react2['default'].createElement(_srcGoogleMapsJs2['default'], { center: center, markers: markers, refine: this._refine.bind(this, { helper: helper }), refineOnMapInteraction: refineOnMapInteraction, zoom: zoom }), container); }, // http://stackoverflow.com/a/13274361/147079 // We cannot use map.fitBounds because we are in a React world // where you should not (and it does not works) try to modify // the rendering once rendered // You need to recompute the right props // It's actually a lot easier than the previous implementation // that was using a LOT of state _getBestZoomLevel: function _getBestZoomLevel(bounds, mapDim) { var WORLD_DIM = { height: 256, width: 256 }; var ZOOM_MAX = 21; function latRad(lat) { var sin = Math.sin(lat * Math.PI / 180); var radX2 = Math.log((1 + sin) / (1 - sin)) / 2; return Math.max(Math.min(radX2, Math.PI), -Math.PI) / 2; } function zoom(mapPx, worldPx, fraction) { return Math.floor(Math.log(mapPx / worldPx / fraction) / Math.LN2); } var ne = bounds.getNorthEast(); var sw = bounds.getSouthWest(); var latFraction = (latRad(ne.lat()) - latRad(sw.lat())) / Math.PI; var lngDiff = ne.lng() - sw.lng(); var lngFraction = (lngDiff < 0 ? lngDiff + 360 : lngDiff) / 360; var latZoom = zoom(mapDim.height, WORLD_DIM.height, latFraction); var lngZoom = zoom(mapDim.width, WORLD_DIM.width, lngFraction); return Math.min(latZoom, lngZoom, ZOOM_MAX); } }; return widget; } _instantsearchJs2['default'].widgets.googleMaps = googleMaps; exports['default'] = googleMaps; module.exports = exports['default']; /***/ }, /* 1 */ /***/ function(module, exports) { module.exports = __WEBPACK_EXTERNAL_MODULE_1__; /***/ }, /* 2 */ /***/ function(module, exports) { module.exports = __WEBPACK_EXTERNAL_MODULE_2__; /***/ }, /* 3 */ /***/ function(module, exports, __webpack_require__) { /* global google */ 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _react = __webpack_require__(1); var _react2 = _interopRequireDefault(_react); var _reactGoogleMaps = __webpack_require__(4); var _reactGoogleMapsLibAddonsMarkerClusterer = __webpack_require__(54); var _reactGoogleMapsLibAddonsMarkerClusterer2 = _interopRequireDefault(_reactGoogleMapsLibAddonsMarkerClusterer); var GoogleMaps = (function (_React$Component) { _inherits(GoogleMaps, _React$Component); function GoogleMaps() { _classCallCheck(this, GoogleMaps); _get(Object.getPrototypeOf(GoogleMaps.prototype), 'constructor', this).apply(this, arguments); } _createClass(GoogleMaps, [{ key: 'shouldComponentUpdate', value: function shouldComponentUpdate(nextProps) { var _this = this; return nextProps.zoom !== this.props.zoom || // user has changed zoom nextProps.markers.length !== this.props.markers.length || // different results number nextProps.markers.some(function (marker, markerIndex) { return (// same number of results, but different markers? _this.props.markers[markerIndex] === undefined || marker.id !== _this.props.markers[markerIndex].id ); }); } }, { key: '_shouldRefineOnMapInteraction', value: function _shouldRefineOnMapInteraction(fn) { if (this.props.refineOnMapInteraction === true) { return fn; } return function noop() {}; } }, { key: '_userRefine', value: function _userRefine() { if (this.props.refineOnMapInteraction) { this.props.refine({ bounds: this._map.getBounds(), center: this._map.getCenter(), zoom: this._map.getZoom() }); } } }, { key: 'render', value: function render() { var _this2 = this; return _react2['default'].createElement(_reactGoogleMaps.GoogleMapLoader, { containerElement: _react2['default'].createElement('div', { style: { height: '100%' } }), googleMapElement: _react2['default'].createElement( _reactGoogleMaps.GoogleMap, _extends({ onDragend: this._userRefine.bind(this), onZoomChanged: this._userRefine.bind(this), ref: function (map) { return _this2._map = map; } }, this.props), _react2['default'].createElement( _reactGoogleMapsLibAddonsMarkerClusterer2['default'], { averageCenter: true, enableRetinaIcons: true, gridSize: 30 }, this.props.markers.map(function (marker) { return _react2['default'].createElement(_reactGoogleMaps.Marker, _extends({ key: marker.id }, marker)); }) ) ) }); } }]); return GoogleMaps; })(_react2['default'].Component); GoogleMaps.propTypes = { center: _react2['default'].PropTypes.object, // google.maps.LatLng, markers: _react2['default'].PropTypes.arrayOf(_react2['default'].PropTypes.shape({ id: _react2['default'].PropTypes.oneOfType([_react2['default'].PropTypes.number, _react2['default'].PropTypes.string]), label: _react2['default'].PropTypes.string, position: _react2['default'].PropTypes.object, // google.maps.LatLng title: _react2['default'].PropTypes.string })).isRequired, refine: _react2['default'].PropTypes.func.isRequired, refineOnMapInteraction: _react2['default'].PropTypes.bool, zoom: _react2['default'].PropTypes.number }; exports['default'] = GoogleMaps; module.exports = exports['default']; /***/ }, /* 4 */ /***/ function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); function _interopRequire(obj) { return obj && obj.__esModule ? obj["default"] : obj; } var _GoogleMapLoader = __webpack_require__(5); exports.GoogleMapLoader = _interopRequire(_GoogleMapLoader); var _GoogleMap = __webpack_require__(21); exports.GoogleMap = _interopRequire(_GoogleMap); var _Circle = __webpack_require__(22); exports.Circle = _interopRequire(_Circle); var _DirectionsRenderer = __webpack_require__(26); exports.DirectionsRenderer = _interopRequire(_DirectionsRenderer); var _DrawingManager = __webpack_require__(29); exports.DrawingManager = _interopRequire(_DrawingManager); var _InfoWindow = __webpack_require__(32); exports.InfoWindow = _interopRequire(_InfoWindow); var _Marker = __webpack_require__(36); exports.Marker = _interopRequire(_Marker); var _OverlayView = __webpack_require__(39); exports.OverlayView = _interopRequire(_OverlayView); var _Polygon = __webpack_require__(42); exports.Polygon = _interopRequire(_Polygon); var _Polyline = __webpack_require__(45); exports.Polyline = _interopRequire(_Polyline); var _Rectangle = __webpack_require__(48); exports.Rectangle = _interopRequire(_Rectangle); var _SearchBox = __webpack_require__(51); exports.SearchBox = _interopRequire(_SearchBox); /***/ }, /* 5 */ /***/ function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _react = __webpack_require__(1); var _react2 = _interopRequireDefault(_react); var _reactPropTypesElementOfType = __webpack_require__(6); var _reactPropTypesElementOfType2 = _interopRequireDefault(_reactPropTypesElementOfType); var _creatorsGoogleMapHolder = __webpack_require__(12); var _creatorsGoogleMapHolder2 = _interopRequireDefault(_creatorsGoogleMapHolder); var USE_NEW_BEHAVIOR_TAG_NAME = "__new_behavior__"; /* CIRCULAR_DEPENDENCY */ var GoogleMapLoader = (function (_Component) { _inherits(GoogleMapLoader, _Component); function GoogleMapLoader() { _classCallCheck(this, GoogleMapLoader); _get(Object.getPrototypeOf(GoogleMapLoader.prototype), "constructor", this).apply(this, arguments); this.state = { map: null }; } _createClass(GoogleMapLoader, [{ key: "mountGoogleMap", value: function mountGoogleMap(domEl) { if (this.state.map) { return; } var _props$googleMapElement$props = this.props.googleMapElement.props; var children = _props$googleMapElement$props.children; var mapProps = _objectWithoutProperties(_props$googleMapElement$props, ["children"]); // // Create google.maps.Map instance so that dom is initialized before // React's children creators. // var map = _creatorsGoogleMapHolder2["default"]._createMap(domEl, mapProps); this.setState({ map: map }); } }, { key: "renderChild", value: function renderChild() { if (this.state.map) { // Notice: implementation details // // In this state, the DOM of google.maps.Map is already initialized in // my innerHTML. Adding extra React components will not clean it // in current version*. It will use prepend to add DOM of // GoogleMapHolder and become a sibling of the DOM of google.maps.Map // Not sure this is subject to change // // *current version: 0.13.3, 0.14.2 // return _react2["default"].cloneElement(this.props.googleMapElement, { map: this.state.map, //------------ Deprecated ------------ containerTagName: USE_NEW_BEHAVIOR_TAG_NAME }); } } }, { key: "render", value: function render() { return _react2["default"].cloneElement(this.props.containerElement, { ref: this.mountGoogleMap.bind(this) }, this.renderChild()); } }], [{ key: "propTypes", value: { containerElement: _react.PropTypes.node.isRequired, googleMapElement: _react.PropTypes.element.isRequired }, enumerable: true }, { key: "defaultProps", /* CIRCULAR_DEPENDENCY. Uncomment when 5.0.0 comes: propTypesElementOfType(GoogleMap).isRequired, */ value: { containerElement: _react2["default"].createElement("div", null) }, enumerable: true }]); return GoogleMapLoader; })(_react.Component); exports["default"] = GoogleMapLoader; module.exports = exports["default"]; /***/ }, /* 6 */ /***/ function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports["default"] = createComponentTypeChecker; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } var _reactLibReactElement = __webpack_require__(7); var _reactLibReactElement2 = _interopRequireDefault(_reactLibReactElement); var _reactLibReactPropTypeLocationNames = __webpack_require__(11); var _reactLibReactPropTypeLocationNames2 = _interopRequireDefault(_reactLibReactPropTypeLocationNames); var ANONYMOUS = "<<anonymous>>"; /* Check if the given element is created by specific Component. i.e., * `element = React.createElement(Component, {})` * * @author: @cassiozen * @origin: https://github.com/facebook/react/pull/4716 */ function createComponentTypeChecker(expectedComponent) { function validate(isRequired, props, propName, componentName, location) { var propFullName = arguments.length <= 5 || arguments[5] === undefined ? propName : arguments[5]; return (function () { var locationName = _reactLibReactPropTypeLocationNames2["default"][location]; if (null == props[propName]) { if (isRequired) { return new Error("Required " + locationName + " `" + propFullName + "` was not specified in " + ("`" + componentName + "`.")); } else { return null; } } var actualComponent = props[propName].type; if (!_reactLibReactElement2["default"].isValidElement(props[propName]) || actualComponent !== expectedComponent) { var expectedComponentName = getComponentName(expectedComponent); var actualComponentName = getComponentName(actualComponent); var extraMessage = getExtraMessage(expectedComponent, actualComponent); return new Error("Invalid " + locationName + " `" + propFullName + "` of element type " + ("`" + actualComponentName + "` supplied to `" + componentName + "`, expected ") + ("element type `" + expectedComponentName + "`." + extraMessage)); } return null; })(); } var validator = validate.bind(null, false); validator.isRequired = validate.bind(null, true); return validator; } // Returns class name of the object, if any. function getComponentName(componentClass) { return componentClass && componentClass.name || ANONYMOUS; } function getExtraMessage(expectedComponent, actualComponent) { if (expectedComponent.prototype.isPrototypeOf(actualComponent.prototype)) { return " " + ("Notice that component inheritance is discouraged in React. " + "See discussions here: " + "https://github.com/facebook/react/pull/4716#issuecomment-135145263"); } return ""; } module.exports = exports["default"]; /***/ }, /* 7 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2014-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactElement */ 'use strict'; var ReactCurrentOwner = __webpack_require__(8); var assign = __webpack_require__(9); var canDefineProperty = __webpack_require__(10); // The Symbol used to tag the ReactElement type. If there is no native Symbol // nor polyfill, then a plain number is used for performance. var REACT_ELEMENT_TYPE = typeof Symbol === 'function' && Symbol['for'] && Symbol['for']('react.element') || 0xeac7; var RESERVED_PROPS = { key: true, ref: true, __self: true, __source: true }; /** * Base constructor for all React elements. This is only used to make this * work with a dynamic instanceof check. Nothing should live on this prototype. * * @param {*} type * @param {*} key * @param {string|object} ref * @param {*} self A *temporary* helper to detect places where `this` is * different from the `owner` when React.createElement is called, so that we * can warn. We want to get rid of owner and replace string `ref`s with arrow * functions, and as long as `this` and owner are the same, there will be no * change in behavior. * @param {*} source An annotation object (added by a transpiler or otherwise) * indicating filename, line number, and/or other information. * @param {*} owner * @param {*} props * @internal */ var ReactElement = function (type, key, ref, self, source, owner, props) { var element = { // This tag allow us to uniquely identify this as a React Element $$typeof: REACT_ELEMENT_TYPE, // Built-in properties that belong on the element type: type, key: key, ref: ref, props: props, // Record the component responsible for creating this element. _owner: owner }; if (false) { // The validation flag is currently mutative. We put it on // an external backing store so that we can freeze the whole object. // This can be replaced with a WeakMap once they are implemented in // commonly used development environments. element._store = {}; // To make comparing ReactElements easier for testing purposes, we make // the validation flag non-enumerable (where possible, which should // include every environment we run tests in), so the test framework // ignores it. if (canDefineProperty) { Object.defineProperty(element._store, 'validated', { configurable: false, enumerable: false, writable: true, value: false }); // self and source are DEV only properties. Object.defineProperty(element, '_self', { configurable: false, enumerable: false, writable: false, value: self }); // Two elements created in two different places should be considered // equal for testing purposes and therefore we hide it from enumeration. Object.defineProperty(element, '_source', { configurable: false, enumerable: false, writable: false, value: source }); } else { element._store.validated = false; element._self = self; element._source = source; } Object.freeze(element.props); Object.freeze(element); } return element; }; ReactElement.createElement = function (type, config, children) { var propName; // Reserved names are extracted var props = {}; var key = null; var ref = null; var self = null; var source = null; if (config != null) { ref = config.ref === undefined ? null : config.ref; key = config.key === undefined ? null : '' + config.key; self = config.__self === undefined ? null : config.__self; source = config.__source === undefined ? null : config.__source; // Remaining properties are added to a new props object for (propName in config) { if (config.hasOwnProperty(propName) && !RESERVED_PROPS.hasOwnProperty(propName)) { props[propName] = config[propName]; } } } // Children can be more than one argument, and those are transferred onto // the newly allocated props object. var childrenLength = arguments.length - 2; if (childrenLength === 1) { props.children = children; } else if (childrenLength > 1) { var childArray = Array(childrenLength); for (var i = 0; i < childrenLength; i++) { childArray[i] = arguments[i + 2]; } props.children = childArray; } // Resolve default props if (type && type.defaultProps) { var defaultProps = type.defaultProps; for (propName in defaultProps) { if (typeof props[propName] === 'undefined') { props[propName] = defaultProps[propName]; } } } return ReactElement(type, key, ref, self, source, ReactCurrentOwner.current, props); }; ReactElement.createFactory = function (type) { var factory = ReactElement.createElement.bind(null, type); // Expose the type on the factory and the prototype so that it can be // easily accessed on elements. E.g. `<Foo />.type === Foo`. // This should not be named `constructor` since this may not be the function // that created the element, and it may not even be a constructor. // Legacy hook TODO: Warn if this is accessed factory.type = type; return factory; }; ReactElement.cloneAndReplaceKey = function (oldElement, newKey) { var newElement = ReactElement(oldElement.type, newKey, oldElement.ref, oldElement._self, oldElement._source, oldElement._owner, oldElement.props); return newElement; }; ReactElement.cloneAndReplaceProps = function (oldElement, newProps) { var newElement = ReactElement(oldElement.type, oldElement.key, oldElement.ref, oldElement._self, oldElement._source, oldElement._owner, newProps); if (false) { // If the key on the original is valid, then the clone is valid newElement._store.validated = oldElement._store.validated; } return newElement; }; ReactElement.cloneElement = function (element, config, children) { var propName; // Original props are copied var props = assign({}, element.props); // Reserved names are extracted var key = element.key; var ref = element.ref; // Self is preserved since the owner is preserved. var self = element._self; // Source is preserved since cloneElement is unlikely to be targeted by a // transpiler, and the original source is probably a better indicator of the // true owner. var source = element._source; // Owner will be preserved, unless ref is overridden var owner = element._owner; if (config != null) { if (config.ref !== undefined) { // Silently steal the ref from the parent. ref = config.ref; owner = ReactCurrentOwner.current; } if (config.key !== undefined) { key = '' + config.key; } // Remaining properties override existing props for (propName in config) { if (config.hasOwnProperty(propName) && !RESERVED_PROPS.hasOwnProperty(propName)) { props[propName] = config[propName]; } } } // Children can be more than one argument, and those are transferred onto // the newly allocated props object. var childrenLength = arguments.length - 2; if (childrenLength === 1) { props.children = children; } else if (childrenLength > 1) { var childArray = Array(childrenLength); for (var i = 0; i < childrenLength; i++) { childArray[i] = arguments[i + 2]; } props.children = childArray; } return ReactElement(element.type, key, ref, self, source, owner, props); }; /** * @param {?object} object * @return {boolean} True if `object` is a valid component. * @final */ ReactElement.isValidElement = function (object) { return typeof object === 'object' && object !== null && object.$$typeof === REACT_ELEMENT_TYPE; }; module.exports = ReactElement; /***/ }, /* 8 */ /***/ function(module, exports) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactCurrentOwner */ 'use strict'; /** * Keeps track of the current owner. * * The current owner is the component who should own any components that are * currently being constructed. */ var ReactCurrentOwner = { /** * @internal * @type {ReactComponent} */ current: null }; module.exports = ReactCurrentOwner; /***/ }, /* 9 */ /***/ function(module, exports) { /** * Copyright 2014-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule Object.assign */ // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-object.assign 'use strict'; function assign(target, sources) { if (target == null) { throw new TypeError('Object.assign target cannot be null or undefined'); } var to = Object(target); var hasOwnProperty = Object.prototype.hasOwnProperty; for (var nextIndex = 1; nextIndex < arguments.length; nextIndex++) { var nextSource = arguments[nextIndex]; if (nextSource == null) { continue; } var from = Object(nextSource); // We don't currently support accessors nor proxies. Therefore this // copy cannot throw. If we ever supported this then we must handle // exceptions and side-effects. We don't support symbols so they won't // be transferred. for (var key in from) { if (hasOwnProperty.call(from, key)) { to[key] = from[key]; } } } return to; } module.exports = assign; /***/ }, /* 10 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule canDefineProperty */ 'use strict'; var canDefineProperty = false; if (false) { try { Object.defineProperty({}, 'x', { get: function () {} }); canDefineProperty = true; } catch (x) { // IE will fail on defineProperty } } module.exports = canDefineProperty; /***/ }, /* 11 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactPropTypeLocationNames */ 'use strict'; var ReactPropTypeLocationNames = {}; if (false) { ReactPropTypeLocationNames = { prop: 'prop', context: 'context', childContext: 'child context' }; } module.exports = ReactPropTypeLocationNames; /***/ }, /* 12 */ /***/ function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _react = __webpack_require__(1); var _react2 = _interopRequireDefault(_react); var _warning = __webpack_require__(13); var _warning2 = _interopRequireDefault(_warning); var _eventListsGoogleMapEventList = __webpack_require__(14); var _eventListsGoogleMapEventList2 = _interopRequireDefault(_eventListsGoogleMapEventList); var _utilsEventHandlerCreator = __webpack_require__(15); var _utilsEventHandlerCreator2 = _interopRequireDefault(_utilsEventHandlerCreator); var _utilsDefaultPropsCreator = __webpack_require__(16); var _utilsDefaultPropsCreator2 = _interopRequireDefault(_utilsDefaultPropsCreator); var _utilsComposeOptions = __webpack_require__(18); var _utilsComposeOptions2 = _interopRequireDefault(_utilsComposeOptions); var _utilsComponentLifecycleDecorator = __webpack_require__(20); var _utilsComponentLifecycleDecorator2 = _interopRequireDefault(_utilsComponentLifecycleDecorator); var mapControlledPropTypes = { // NOTICE!!!!!! // // Only expose those with getters & setters in the table as controlled props. // // [].map.call($0.querySelectorAll("tr>td>code"), function(it){ return it.textContent; }).filter(function(it){ return it.match(/^set/) && !it.match(/^setMap/); }) // // https://developers.google.com/maps/documentation/javascript/3.exp/reference#Map center: _react.PropTypes.object, heading: _react.PropTypes.number, mapTypeId: _react.PropTypes.any, options: _react.PropTypes.object, streetView: _react.PropTypes.any, tilt: _react.PropTypes.number, zoom: _react.PropTypes.number }; exports.mapControlledPropTypes = mapControlledPropTypes; var mapDefaultPropTypes = (0, _utilsDefaultPropsCreator2["default"])(mapControlledPropTypes); exports.mapDefaultPropTypes = mapDefaultPropTypes; var mapUpdaters = { center: function center(_center, component) { component.getMap().setCenter(_center); }, heading: function heading(_heading, component) { component.getMap().setHeading(_heading); }, mapTypeId: function mapTypeId(_mapTypeId, component) { component.getMap().setMapTypeId(_mapTypeId); }, options: function options(_options, component) { component.getMap().setOptions(_options); }, streetView: function streetView(_streetView, component) { component.getMap().setStreetView(_streetView); }, tilt: function tilt(_tilt, component) { component.getMap().setTilt(_tilt); }, zoom: function zoom(_zoom, component) { component.getMap().setZoom(_zoom); } }; var _eventHandlerCreator = (0, _utilsEventHandlerCreator2["default"])(_eventListsGoogleMapEventList2["default"]); var eventPropTypes = _eventHandlerCreator.eventPropTypes; var registerEvents = _eventHandlerCreator.registerEvents; var mapEventPropTypes = eventPropTypes; exports.mapEventPropTypes = mapEventPropTypes; var GoogleMapHolder = (function (_Component) { _inherits(GoogleMapHolder, _Component); function GoogleMapHolder() { _classCallCheck(this, _GoogleMapHolder); _get(Object.getPrototypeOf(_GoogleMapHolder.prototype), "constructor", this).apply(this, arguments); } _createClass(GoogleMapHolder, [{ key: "getMap", value: function getMap() { return this.props.map; } }, { key: "render", value: function render() { var _this = this; return _react2["default"].createElement( "div", null, _react.Children.map(this.props.children, function (childElement) { if (_react2["default"].isValidElement(childElement)) { return _react2["default"].cloneElement(childElement, { mapHolderRef: _this }); } else { return childElement; } }) ); } }], [{ key: "_createMap", value: function _createMap(domEl, mapProps) { (0, _warning2["default"])("undefined" !== typeof google, "Make sure you've put a <script> tag in your <head> element to load Google Maps JavaScript API v3.\n If you're looking for built-in support to load it for you, use the \"async/ScriptjsLoader\" instead.\n See https://github.com/tomchentw/react-google-maps/pull/168"); // https://developers.google.com/maps/documentation/javascript/3.exp/reference#Map return new google.maps.Map(domEl, (0, _utilsComposeOptions2["default"])(mapProps, mapControlledPropTypes)); } }, { key: "propTypes", value: { map: _react.PropTypes.object.isRequired }, enumerable: true }]); var _GoogleMapHolder = GoogleMapHolder; GoogleMapHolder = (0, _utilsComponentLifecycleDecorator2["default"])({ registerEvents: registerEvents, instanceMethodName: "getMap", updaters: mapUpdaters })(GoogleMapHolder) || GoogleMapHolder; return GoogleMapHolder; })(_react.Component); exports["default"] = GoogleMapHolder; /***/ }, /* 13 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2014-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ 'use strict'; /** * Similar to invariant but only logs a warning if the condition is not met. * This can be used to log issues in development environments in critical * paths. Removing the logging code for production environments will keep the * same logic and follow the same code paths. */ var warning = function() {}; if (false) { warning = function(condition, format, args) { var len = arguments.length; args = new Array(len > 2 ? len - 2 : 0); for (var key = 2; key < len; key++) { args[key - 2] = arguments[key]; } if (format === undefined) { throw new Error( '`warning(condition, format, ...args)` requires a warning ' + 'message argument' ); } if (format.length < 10 || (/^[s\W]*$/).test(format)) { throw new Error( 'The warning format should be able to uniquely identify this ' + 'warning. Please, use a more descriptive format than: ' + format ); } if (!condition) { var argIndex = 0; var message = 'Warning: ' + format.replace(/%s/g, function() { return args[argIndex++]; }); if (typeof console !== 'undefined') { console.error(message); } try { // This error was thrown as a convenience so that you can use this stack // to find the callsite that caused this warning to fire. throw new Error(message); } catch(x) {} } }; } module.exports = warning; /***/ }, /* 14 */ /***/ function(module, exports) { // https://developers.google.com/maps/documentation/javascript/3.exp/reference#Map // [].map.call($0.querySelectorAll("tr>td>code"), function(it){ return it.textContent; }) "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports["default"] = ["bounds_changed", "center_changed", "click", "dblclick", "drag", "dragend", "dragstart", "heading_changed", "idle", "maptypeid_changed", "mousemove", "mouseout", "mouseover", "projection_changed", "resize", "rightclick", "tilesloaded", "tilt_changed", "zoom_changed"]; module.exports = exports["default"]; /***/ }, /* 15 */ /***/ function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports["default"] = eventHandlerCreator; var _react = __webpack_require__(1); function groupToUpperCase(match, group) { return group.toUpperCase(); } function toOnEventName(rawName) { return "on" + rawName.replace(/^(.)/, groupToUpperCase).replace(/_(.)/g, groupToUpperCase); } function eventHandlerCreator(rawNameList) { var eventPropTypes = {}; var onEventNameByRawName = {}; rawNameList.forEach(function (rawName) { var onEventName = toOnEventName(rawName); eventPropTypes[onEventName] = _react.PropTypes.func; onEventNameByRawName[rawName] = onEventName; }); function registerEvents(event, props, googleMapInstance) { var registered = rawNameList.reduce(function (acc, rawName) { var onEventName = onEventNameByRawName[rawName]; if (Object.prototype.hasOwnProperty.call(props, onEventName)) { acc.push(event.addListener(googleMapInstance, rawName, props[onEventName])); } return acc; }, []); return registered.forEach.bind(registered, event.removeListener, event); } return { eventPropTypes: eventPropTypes, registerEvents: registerEvents }; } module.exports = exports["default"]; /***/ }, /* 16 */ /***/ function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports["default"] = defaultPropsCreator; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } var _addDefaultPrefix = __webpack_require__(17); var _addDefaultPrefix2 = _interopRequireDefault(_addDefaultPrefix); function defaultPropsCreator(propTypes) { return Object.keys(propTypes).reduce(function (acc, name) { acc[(0, _addDefaultPrefix2["default"])(name)] = propTypes[name]; return acc; }, {}); } module.exports = exports["default"]; /***/ }, /* 17 */ /***/ function(module, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports["default"] = addDefaultPrefix; function addDefaultPrefix(name) { return "default" + (name[0].toUpperCase() + name.slice(1)); } module.exports = exports["default"]; /***/ }, /* 18 */ /***/ function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; exports["default"] = composeOptions; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } var _controlledOrDefault = __webpack_require__(19); var _controlledOrDefault2 = _interopRequireDefault(_controlledOrDefault); function composeOptions(props, controlledPropTypes) { var optionNameList = Object.keys(controlledPropTypes); var getter = (0, _controlledOrDefault2["default"])(props); // props from arguments may contain unknow props. // We only interested those in optionNameList return optionNameList.reduce(function (acc, optionName) { if ("options" !== optionName) { var value = getter(optionName); if ("undefined" !== typeof value) { acc[optionName] = value; } } return acc; }, _extends({}, getter("options"))); } module.exports = exports["default"]; /***/ }, /* 19 */ /***/ function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports["default"] = controlledOrDefault; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } var _addDefaultPrefix = __webpack_require__(17); var _addDefaultPrefix2 = _interopRequireDefault(_addDefaultPrefix); function controlledOrDefault(props) { return function (name) { if (Object.prototype.hasOwnProperty.call(props, name)) { return props[name]; } else { return props[(0, _addDefaultPrefix2["default"])(name)]; } }; } module.exports = exports["default"]; /***/ }, /* 20 */ /***/ function(module, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports["default"] = componentLifecycleDecorator; function componentLifecycleDecorator(_ref) { var registerEvents = _ref.registerEvents; var instanceMethodName = _ref.instanceMethodName; var updaters = _ref.updaters; // This modify the Component.prototype directly return function (Component) { function register() { this._unregisterEvents = registerEvents(google.maps.event, this.props, this[instanceMethodName]()); } function unregister() { this._unregisterEvents(); this._unregisterEvents = null; } function noop() {} // Stash component's own lifecycle methods to be invoked later var componentDidMount = Component.prototype.hasOwnProperty("componentDidMount") ? Component.prototype.componentDidMount : noop; var componentDidUpdate = Component.prototype.hasOwnProperty("componentDidUpdate") ? Component.prototype.componentDidUpdate : noop; var componentWillUnmount = Component.prototype.hasOwnProperty("componentWillUnmount") ? Component.prototype.componentWillUnmount : noop; Object.defineProperty(Component.prototype, "componentDidMount", { enumerable: false, configurable: true, writable: true, value: function value() { // Hook into client's implementation, if it has any componentDidMount.call(this); register.call(this); } }); Object.defineProperty(Component.prototype, "componentDidUpdate", { enumerable: false, configurable: true, writable: true, value: function value(prevProps) { unregister.call(this); for (var _name in updaters) { if (Object.prototype.hasOwnProperty.call(this.props, _name)) { updaters[_name](this.props[_name], this); } } // Hook into client's implementation, if it has any componentDidUpdate.call(this, prevProps); register.call(this); } }); Object.defineProperty(Component.prototype, "componentWillUnmount", { enumerable: false, configurable: true, writable: true, value: function value() { // Hook into client's implementation, if it has any componentWillUnmount.call(this); unregister.call(this); var instance = this[instanceMethodName](); if ("setMap" in instance) { instance.setMap(null); } } }); return Component; }; } module.exports = exports["default"]; /***/ }, /* 21 */ /***/ function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _react = __webpack_require__(1); var _react2 = _interopRequireDefault(_react); var _warning = __webpack_require__(13); var _warning2 = _interopRequireDefault(_warning); var _creatorsGoogleMapHolder = __webpack_require__(12); var _creatorsGoogleMapHolder2 = _interopRequireDefault(_creatorsGoogleMapHolder); var _GoogleMapLoader = __webpack_require__(5); var _GoogleMapLoader2 = _interopRequireDefault(_GoogleMapLoader); var USE_NEW_BEHAVIOR_TAG_NAME = "__new_behavior__"; var GoogleMap = (function (_Component) { _inherits(GoogleMap, _Component); function GoogleMap() { _classCallCheck(this, GoogleMap); _get(Object.getPrototypeOf(GoogleMap.prototype), "constructor", this).apply(this, arguments); } _createClass(GoogleMap, [{ key: "getBounds", // Public APIs // // https://developers.google.com/maps/documentation/javascript/3.exp/reference#Map // // [].map.call($0.querySelectorAll("tr>td>code"), function(it){ return it.textContent; }).filter(function(it){ return it.match(/^get/) && !it.match(/Map$/); }) value: function getBounds() { return (this.props.map || this.refs.delegate).getBounds(); } }, { key: "getCenter", value: function getCenter() { return (this.props.map || this.refs.delegate).getCenter(); } }, { key: "getDiv", value: function getDiv() { return (this.props.map || this.refs.delegate).getDiv(); } }, { key: "getHeading", value: function getHeading() { return (this.props.map || this.refs.delegate).getHeading(); } }, { key: "getMapTypeId", value: function getMapTypeId() { return (this.props.map || this.refs.delegate).getMapTypeId(); } }, { key: "getProjection", value: function getProjection() { return (this.props.map || this.refs.delegate).getProjection(); } }, { key: "getStreetView", value: function getStreetView() { return (this.props.map || this.refs.delegate).getStreetView(); } }, { key: "getTilt", value: function getTilt() { return (this.props.map || this.refs.delegate).getTilt(); } }, { key: "getZoom", value: function getZoom() { return (this.props.map || this.refs.delegate).getZoom(); } // END - Public APIs // // https://developers.google.com/maps/documentation/javascript/3.exp/reference#Map // // Public APIs - Use this carefully // See discussion in https://github.com/tomchentw/react-google-maps/issues/62 // // https://developers.google.com/maps/documentation/javascript/3.exp/reference#Map // // [].map.call($0.querySelectorAll("tr>td>code"), function(it){ return it.textContent; }).filter(function(it){ return !it.match(/^get/) && !it.match(/^set/) && !it.match(/Map$/); }) }, { key: "fitBounds", value: function fitBounds(bounds) { return (this.props.map || this.refs.delegate).fitBounds(bounds); } }, { key: "panBy", value: function panBy(x, y) { return (this.props.map || this.refs.delegate).panBy(x, y); } }, { key: "panTo", value: function panTo(latLng) { return (this.props.map || this.refs.delegate).panTo(latLng); } }, { key: "panToBounds", value: function panToBounds(latLngBounds) { return (this.props.map || this.refs.delegate).panToBounds(latLngBounds); } // END - Public APIs - Use this carefully // // https://developers.google.com/maps/documentation/javascript/3.exp/reference#Map }, { key: "componentWillMount", value: function componentWillMount() { var containerTagName = this.props.containerTagName; var isUsingNewBehavior = USE_NEW_BEHAVIOR_TAG_NAME === containerTagName; (0, _warning2["default"])(isUsingNewBehavior, "\"GoogleMap\" with containerTagName is deprecated now and will be removed in next major release (5.0.0). \nUse \"GoogleMapLoader\" instead. See https://github.com/tomchentw/react-google-maps/pull/157 for more details."); } }, { key: "render", value: function render() { var _props = this.props; var containerTagName = _props.containerTagName; var _props$containerProps = _props.containerProps; var containerProps = _props$containerProps === undefined ? {} : _props$containerProps; var children = _props.children; var mapProps = _objectWithoutProperties(_props, ["containerTagName", "containerProps", "children"]); var isUsingNewBehavior = USE_NEW_BEHAVIOR_TAG_NAME === containerTagName; if (isUsingNewBehavior) { return _react2["default"].createElement( _creatorsGoogleMapHolder2["default"], mapProps, children ); } else { //------------ Deprecated ------------ var realContainerTagName = null == containerTagName ? "div" : containerTagName; return _react2["default"].createElement(_GoogleMapLoader2["default"], { ref: "loader", containerElement: _react2["default"].createElement(realContainerTagName, containerProps), googleMapElement: _react2["default"].createElement( GoogleMap, _extends({ ref: "delegate", containerTagName: USE_NEW_BEHAVIOR_TAG_NAME }, mapProps), children ) }); } } }], [{ key: "propTypes", value: _extends({ containerTagName: _react.PropTypes.string, containerProps: _react.PropTypes.object, map: _react.PropTypes.object }, _creatorsGoogleMapHolder.mapDefaultPropTypes, _creatorsGoogleMapHolder.mapControlledPropTypes, _creatorsGoogleMapHolder.mapEventPropTypes), enumerable: true }]); return GoogleMap; })(_react.Component); exports["default"] = GoogleMap; module.exports = exports["default"]; // Uncontrolled default[props] - used only in componentDidMount // Controlled [props] - used in componentDidMount/componentDidUpdate // Event [onEventName] /***/ }, /* 22 */ /***/ function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _react = __webpack_require__(1); var _react2 = _interopRequireDefault(_react); var _canUseDom = __webpack_require__(23); var _canUseDom2 = _interopRequireDefault(_canUseDom); var _creatorsCircleCreator = __webpack_require__(24); var _creatorsCircleCreator2 = _interopRequireDefault(_creatorsCircleCreator); var Circle = (function (_Component) { _inherits(Circle, _Component); function Circle() { _classCallCheck(this, Circle); _get(Object.getPrototypeOf(Circle.prototype), "constructor", this).apply(this, arguments); this.state = {}; } _createClass(Circle, [{ key: "getBounds", // Public APIs // // https://developers.google.com/maps/documentation/javascript/3.exp/reference#Circle // // [].map.call($0.querySelectorAll("tr>td>code"), function(it){ return it.textContent; }).filter(function(it){ return it.match(/^get/) && !it.match(/^getMap/); }) value: function getBounds() { return this.state.circle.getBounds(); } }, { key: "getCenter", value: function getCenter() { return this.state.circle.getCenter(); } }, { key: "getDraggable", value: function getDraggable() { return this.state.circle.getDraggable(); } }, { key: "getEditable", value: function getEditable() { return this.state.circle.getEditable(); } }, { key: "getMap", value: function getMap() { return this.state.circle.getMap(); } }, { key: "getRadius", value: function getRadius() { return this.state.circle.getRadius(); } }, { key: "getVisible", value: function getVisible() { return this.state.circle.getVisible(); } // END - Public APIs // // https://developers.google.com/maps/documentation/javascript/3.exp/reference#Circle }, { key: "componentWillMount", value: function componentWillMount() { if (!_canUseDom2["default"]) { return; } var circle = _creatorsCircleCreator2["default"]._createCircle(this.props); this.setState({ circle: circle }); } }, { key: "render", value: function render() { if (this.state.circle) { return _react2["default"].createElement( _creatorsCircleCreator2["default"], _extends({ circle: this.state.circle }, this.props), this.props.children ); } else { return _react2["default"].createElement("noscript", null); } } }], [{ key: "propTypes", value: _extends({}, _creatorsCircleCreator.circleDefaultPropTypes, _creatorsCircleCreator.circleControlledPropTypes, _creatorsCircleCreator.circleEventPropTypes), enumerable: true }]); return Circle; })(_react.Component); exports["default"] = Circle; module.exports = exports["default"]; // Uncontrolled default[props] - used only in componentDidMount // Controlled [props] - used in componentDidMount/componentDidUpdate // Event [onEventName] /***/ }, /* 23 */ /***/ function(module, exports) { var canUseDOM = !!( typeof window !== 'undefined' && window.document && window.document.createElement ); module.exports = canUseDOM; /***/ }, /* 24 */ /***/ function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _react = __webpack_require__(1); var _react2 = _interopRequireDefault(_react); var _eventListsCircleEventList = __webpack_require__(25); var _eventListsCircleEventList2 = _interopRequireDefault(_eventListsCircleEventList); var _utilsEventHandlerCreator = __webpack_require__(15); var _utilsEventHandlerCreator2 = _interopRequireDefault(_utilsEventHandlerCreator); var _utilsDefaultPropsCreator = __webpack_require__(16); var _utilsDefaultPropsCreator2 = _interopRequireDefault(_utilsDefaultPropsCreator); var _utilsComposeOptions = __webpack_require__(18); var _utilsComposeOptions2 = _interopRequireDefault(_utilsComposeOptions); var _utilsComponentLifecycleDecorator = __webpack_require__(20); var _utilsComponentLifecycleDecorator2 = _interopRequireDefault(_utilsComponentLifecycleDecorator); var _GoogleMapHolder = __webpack_require__(12); var _GoogleMapHolder2 = _interopRequireDefault(_GoogleMapHolder); var circleControlledPropTypes = { // NOTICE!!!!!! // // Only expose those with getters & setters in the table as controlled props. // // [].map.call($0.querySelectorAll("tr>td>code"), function(it){ return it.textContent; }).filter(function(it){ return it.match(/^set/) && !it.match(/^setMap/); }) // // https://developers.google.com/maps/documentation/javascript/3.exp/reference#Circle center: _react.PropTypes.any, draggable: _react.PropTypes.bool, editable: _react.PropTypes.bool, options: _react.PropTypes.object, radius: _react.PropTypes.number, visible: _react.PropTypes.bool }; exports.circleControlledPropTypes = circleControlledPropTypes; var circleDefaultPropTypes = (0, _utilsDefaultPropsCreator2["default"])(circleControlledPropTypes); exports.circleDefaultPropTypes = circleDefaultPropTypes; var circleUpdaters = { center: function center(_center, component) { component.getCircle().setCenter(_center); }, draggable: function draggable(_draggable, component) { component.getCircle().setDraggable(_draggable); }, editable: function editable(_editable, component) { component.getCircle().setEditable(_editable); }, options: function options(_options, component) { component.getCircle().setOptions(_options); }, radius: function radius(_radius, component) { component.getCircle().setRadius(_radius); }, visible: function visible(_visible, component) { component.getCircle().setVisible(_visible); } }; var _eventHandlerCreator = (0, _utilsEventHandlerCreator2["default"])(_eventListsCircleEventList2["default"]); var eventPropTypes = _eventHandlerCreator.eventPropTypes; var registerEvents = _eventHandlerCreator.registerEvents; var circleEventPropTypes = eventPropTypes; exports.circleEventPropTypes = circleEventPropTypes; var CircleCreator = (function (_Component) { _inherits(CircleCreator, _Component); function CircleCreator() { _classCallCheck(this, _CircleCreator); _get(Object.getPrototypeOf(_CircleCreator.prototype), "constructor", this).apply(this, arguments); } _createClass(CircleCreator, [{ key: "getCircle", value: function getCircle() { return this.props.circle; } }, { key: "render", value: function render() { return _react2["default"].createElement("noscript", null); } }], [{ key: "_createCircle", value: function _createCircle(circleProps) { var mapHolderRef = circleProps.mapHolderRef; // https://developers.google.com/maps/documentation/javascript/3.exp/reference#Circle var circle = new google.maps.Circle((0, _utilsComposeOptions2["default"])(circleProps, circleControlledPropTypes)); circle.setMap(mapHolderRef.getMap()); return circle; } }, { key: "propTypes", value: { mapHolderRef: _react.PropTypes.instanceOf(_GoogleMapHolder2["default"]).isRequired, circle: _react.PropTypes.object.isRequired }, enumerable: true }]); var _CircleCreator = CircleCreator; CircleCreator = (0, _utilsComponentLifecycleDecorator2["default"])({ registerEvents: registerEvents, instanceMethodName: "getCircle", updaters: circleUpdaters })(CircleCreator) || CircleCreator; return CircleCreator; })(_react.Component); exports["default"] = CircleCreator; /***/ }, /* 25 */ /***/ function(module, exports) { // https://developers.google.com/maps/documentation/javascript/3.exp/reference#Circle // [].map.call($0.querySelectorAll("tr>td>code"), function(it){ return it.textContent; }) "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports["default"] = ["center_changed", "click", "dblclick", "drag", "dragend", "dragstart", "mousedown", "mousemove", "mouseout", "mouseover", "mouseup", "radius_changed", "rightclick"]; module.exports = exports["default"]; /***/ }, /* 26 */ /***/ function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _react = __webpack_require__(1); var _react2 = _interopRequireDefault(_react); var _canUseDom = __webpack_require__(23); var _canUseDom2 = _interopRequireDefault(_canUseDom); var _creatorsDirectionsRendererCreator = __webpack_require__(27); var _creatorsDirectionsRendererCreator2 = _interopRequireDefault(_creatorsDirectionsRendererCreator); /* * Original author: @alexishevia * Original PR: https://github.com/tomchentw/react-google-maps/pull/22 */ var DirectionsRenderer = (function (_Component) { _inherits(DirectionsRenderer, _Component); function DirectionsRenderer() { _classCallCheck(this, DirectionsRenderer); _get(Object.getPrototypeOf(DirectionsRenderer.prototype), "constructor", this).apply(this, arguments); this.state = {}; } _createClass(DirectionsRenderer, [{ key: "getDirections", // Public APIs // // https://developers.google.com/maps/documentation/javascript/3.exp/reference#DirectionsRenderer // // [].map.call($0.querySelectorAll("tr>td>code"), function(it){ return it.textContent; }).filter(function(it){ return it.match(/^get/) && !it.match(/^getMap/); }) value: function getDirections() { return this.state.directionsRenderer.getDirections(); } }, { key: "getPanel", value: function getPanel() { return this.state.directionsRenderer.getPanel(); } }, { key: "getRouteIndex", value: function getRouteIndex() { return this.state.directionsRenderer.getRouteIndex(); } // END - Public APIs // // https://developers.google.com/maps/documentation/javascript/3.exp/reference#DirectionsRenderer }, { key: "componentWillMount", value: function componentWillMount() { if (!_canUseDom2["default"]) { return; } var directionsRenderer = _creatorsDirectionsRendererCreator2["default"]._createDirectionsRenderer(this.props); this.setState({ directionsRenderer: directionsRenderer }); } }, { key: "render", value: function render() { if (this.state.directionsRenderer) { return _react2["default"].createElement( _creatorsDirectionsRendererCreator2["default"], _extends({ directionsRenderer: this.state.directionsRenderer }, this.props), this.props.children ); } else { return _react2["default"].createElement("noscript", null); } } }], [{ key: "propTypes", value: _extends({}, _creatorsDirectionsRendererCreator.directionsRendererDefaultPropTypes, _creatorsDirectionsRendererCreator.directionsRendererControlledPropTypes, _creatorsDirectionsRendererCreator.directionsRendererEventPropTypes), enumerable: true }]); return DirectionsRenderer; })(_react.Component); exports["default"] = DirectionsRenderer; module.exports = exports["default"]; // Uncontrolled default[props] - used only in componentDidMount // Controlled [props] - used in componentDidMount/componentDidUpdate // Event [onEventName] /***/ }, /* 27 */ /***/ function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _react = __webpack_require__(1); var _react2 = _interopRequireDefault(_react); var _eventListsDirectionsRendererEventList = __webpack_require__(28); var _eventListsDirectionsRendererEventList2 = _interopRequireDefault(_eventListsDirectionsRendererEventList); var _utilsEventHandlerCreator = __webpack_require__(15); var _utilsEventHandlerCreator2 = _interopRequireDefault(_utilsEventHandlerCreator); var _utilsDefaultPropsCreator = __webpack_require__(16); var _utilsDefaultPropsCreator2 = _interopRequireDefault(_utilsDefaultPropsCreator); var _utilsComposeOptions = __webpack_require__(18); var _utilsComposeOptions2 = _interopRequireDefault(_utilsComposeOptions); var _utilsComponentLifecycleDecorator = __webpack_require__(20); var _utilsComponentLifecycleDecorator2 = _interopRequireDefault(_utilsComponentLifecycleDecorator); var _GoogleMapHolder = __webpack_require__(12); var _GoogleMapHolder2 = _interopRequireDefault(_GoogleMapHolder); var directionsRendererControlledPropTypes = { // NOTICE!!!!!! // // Only expose those with getters & setters in the table as controlled props. // // [].map.call($0.querySelectorAll("tr>td>code"), function(it){ return it.textContent; }).filter(function(it){ return it.match(/^set/) && !it.match(/^setMap/); }) // // https://developers.google.com/maps/documentation/javascript/3.exp/reference#DirectionsRenderer directions: _react.PropTypes.any, options: _react.PropTypes.object, panel: _react.PropTypes.object, routeIndex: _react.PropTypes.number }; exports.directionsRendererControlledPropTypes = directionsRendererControlledPropTypes; var directionsRendererDefaultPropTypes = (0, _utilsDefaultPropsCreator2["default"])(directionsRendererControlledPropTypes); exports.directionsRendererDefaultPropTypes = directionsRendererDefaultPropTypes; var directionsRendererUpdaters = { directions: function directions(_directions, component) { component.getDirectionsRenderer().setDirections(_directions); }, options: function options(_options, component) { component.getDirectionsRenderer().setOptions(_options); }, panel: function panel(_panel, component) { component.getDirectionsRenderer().setPanel(_panel); }, routeIndex: function routeIndex(_routeIndex, component) { component.getDirectionsRenderer().setRouteIndex(_routeIndex); } }; var _eventHandlerCreator = (0, _utilsEventHandlerCreator2["default"])(_eventListsDirectionsRendererEventList2["default"]); var eventPropTypes = _eventHandlerCreator.eventPropTypes; var registerEvents = _eventHandlerCreator.registerEvents; var directionsRendererEventPropTypes = eventPropTypes; exports.directionsRendererEventPropTypes = directionsRendererEventPropTypes; var DirectionsRendererCreator = (function (_Component) { _inherits(DirectionsRendererCreator, _Component); function DirectionsRendererCreator() { _classCallCheck(this, _DirectionsRendererCreator); _get(Object.getPrototypeOf(_DirectionsRendererCreator.prototype), "constructor", this).apply(this, arguments); } _createClass(DirectionsRendererCreator, [{ key: "getDirectionsRenderer", value: function getDirectionsRenderer() { return this.props.directionsRenderer; } }, { key: "render", value: function render() { var children = this.props.children; if (0 < _react.Children.count(children)) { // TODO: take a look at DirectionsRendererOptions#infoWindow and DirectionsRendererOptions#markerOptions ? return _react2["default"].createElement( "div", null, children ); } else { return _react2["default"].createElement("noscript", null); } } }], [{ key: "_createDirectionsRenderer", value: function _createDirectionsRenderer(directionsRendererProps) { var mapHolderRef = directionsRendererProps.mapHolderRef; // https://developers.google.com/maps/documentation/javascript/3.exp/reference#DirectionsRenderer var directionsRenderer = new google.maps.DirectionsRenderer((0, _utilsComposeOptions2["default"])(directionsRendererProps, directionsRendererControlledPropTypes)); directionsRenderer.setMap(mapHolderRef.getMap()); return directionsRenderer; } }, { key: "propTypes", value: { mapHolderRef: _react.PropTypes.instanceOf(_GoogleMapHolder2["default"]).isRequired, directionsRenderer: _react.PropTypes.object.isRequired }, enumerable: true }]); var _DirectionsRendererCreator = DirectionsRendererCreator; DirectionsRendererCreator = (0, _utilsComponentLifecycleDecorator2["default"])({ registerEvents: registerEvents, instanceMethodName: "getDirectionsRenderer", updaters: directionsRendererUpdaters })(DirectionsRendererCreator) || DirectionsRendererCreator; return DirectionsRendererCreator; })(_react.Component); exports["default"] = DirectionsRendererCreator; /***/ }, /* 28 */ /***/ function(module, exports) { // https://developers.google.com/maps/documentation/javascript/3.exp/reference#DirectionsRenderer // [].map.call($0.querySelectorAll("tr>td>code"), function(it){ return it.textContent; }) "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports["default"] = ["directions_changed"]; module.exports = exports["default"]; /***/ }, /* 29 */ /***/ function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _react = __webpack_require__(1); var _react2 = _interopRequireDefault(_react); var _canUseDom = __webpack_require__(23); var _canUseDom2 = _interopRequireDefault(_canUseDom); var _creatorsDrawingManagerCreator = __webpack_require__(30); var _creatorsDrawingManagerCreator2 = _interopRequireDefault(_creatorsDrawingManagerCreator); /* * Original author: @idolize * Original PR: https://github.com/tomchentw/react-google-maps/pull/46 */ var DrawingManager = (function (_Component) { _inherits(DrawingManager, _Component); function DrawingManager() { _classCallCheck(this, DrawingManager); _get(Object.getPrototypeOf(DrawingManager.prototype), "constructor", this).apply(this, arguments); this.state = {}; } _createClass(DrawingManager, [{ key: "getDrawingMode", // Public APIs // // https://developers.google.com/maps/documentation/javascript/3.exp/reference#DrawingManager // // [].map.call($0.querySelectorAll("tr>td>code"), function(it){ return it.textContent; }).filter(function(it){ return it.match(/^get/) && !it.match(/^getMap/); }) value: function getDrawingMode() { return this.state.drawingManager.getDrawingMode(); } // END - Public APIs // // https://developers.google.com/maps/documentation/javascript/3.exp/reference#DrawingManager }, { key: "componentWillMount", value: function componentWillMount() { if (!_canUseDom2["default"]) { return; } var drawingManager = _creatorsDrawingManagerCreator2["default"]._createDrawingManager(this.props); this.setState({ drawingManager: drawingManager }); } }, { key: "render", value: function render() { if (this.state.drawingManager) { return _react2["default"].createElement( _creatorsDrawingManagerCreator2["default"], _extends({ drawingManager: this.state.drawingManager }, this.props), this.props.children ); } else { return _react2["default"].createElement("noscript", null); } } }], [{ key: "propTypes", value: _extends({}, _creatorsDrawingManagerCreator.drawingManagerDefaultPropTypes, _creatorsDrawingManagerCreator.drawingManagerControlledPropTypes, _creatorsDrawingManagerCreator.drawingManagerEventPropTypes), enumerable: true }]); return DrawingManager; })(_react.Component); exports["default"] = DrawingManager; module.exports = exports["default"]; // Uncontrolled default[props] - used only in componentDidMount // Controlled [props] - used in componentDidMount/componentDidUpdate // Event [onEventName] /***/ }, /* 30 */ /***/ function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _react = __webpack_require__(1); var _react2 = _interopRequireDefault(_react); var _eventListsDrawingManagerEventList = __webpack_require__(31); var _eventListsDrawingManagerEventList2 = _interopRequireDefault(_eventListsDrawingManagerEventList); var _utilsEventHandlerCreator = __webpack_require__(15); var _utilsEventHandlerCreator2 = _interopRequireDefault(_utilsEventHandlerCreator); var _utilsDefaultPropsCreator = __webpack_require__(16); var _utilsDefaultPropsCreator2 = _interopRequireDefault(_utilsDefaultPropsCreator); var _utilsComposeOptions = __webpack_require__(18); var _utilsComposeOptions2 = _interopRequireDefault(_utilsComposeOptions); var _utilsComponentLifecycleDecorator = __webpack_require__(20); var _utilsComponentLifecycleDecorator2 = _interopRequireDefault(_utilsComponentLifecycleDecorator); var _GoogleMapHolder = __webpack_require__(12); var _GoogleMapHolder2 = _interopRequireDefault(_GoogleMapHolder); var drawingManagerControlledPropTypes = { // NOTICE!!!!!! // // Only expose those with getters & setters in the table as controlled props. // // [].map.call($0.querySelectorAll("tr>td>code"), function(it){ return it.textContent; }).filter(function(it){ return it.match(/^set/) && !it.match(/^setMap/); }) // // https://developers.google.com/maps/documentation/javascript/3.exp/reference#DrawingManager drawingMode: _react.PropTypes.any, options: _react.PropTypes.object }; exports.drawingManagerControlledPropTypes = drawingManagerControlledPropTypes; var drawingManagerDefaultPropTypes = (0, _utilsDefaultPropsCreator2["default"])(drawingManagerControlledPropTypes); exports.drawingManagerDefaultPropTypes = drawingManagerDefaultPropTypes; var drawingManagerUpdaters = { drawingMode: function drawingMode(_drawingMode, component) { component.getDrawingManager().setDrawingMode(_drawingMode); }, options: function options(_options, component) { component.getDrawingManager().setOptions(_options); } }; var _eventHandlerCreator = (0, _utilsEventHandlerCreator2["default"])(_eventListsDrawingManagerEventList2["default"]); var eventPropTypes = _eventHandlerCreator.eventPropTypes; var registerEvents = _eventHandlerCreator.registerEvents; var drawingManagerEventPropTypes = eventPropTypes; exports.drawingManagerEventPropTypes = drawingManagerEventPropTypes; var DrawingManagerCreator = (function (_Component) { _inherits(DrawingManagerCreator, _Component); function DrawingManagerCreator() { _classCallCheck(this, _DrawingManagerCreator); _get(Object.getPrototypeOf(_DrawingManagerCreator.prototype), "constructor", this).apply(this, arguments); } _createClass(DrawingManagerCreator, [{ key: "getDrawingManager", value: function getDrawingManager() { return this.props.drawingManager; } }, { key: "render", value: function render() { return _react2["default"].createElement("noscript", null); } }], [{ key: "_createDrawingManager", value: function _createDrawingManager(drawingManagerProps) { var mapHolderRef = drawingManagerProps.mapHolderRef; // https://developers.google.com/maps/documentation/javascript/3.exp/reference#DrawingManager var drawingManager = new google.maps.drawing.DrawingManager((0, _utilsComposeOptions2["default"])(drawingManagerProps, drawingManagerControlledPropTypes)); drawingManager.setMap(mapHolderRef.getMap()); return drawingManager; } }, { key: "propTypes", value: { mapHolderRef: _react.PropTypes.instanceOf(_GoogleMapHolder2["default"]).isRequired, drawingManager: _react.PropTypes.object.isRequired }, enumerable: true }]); var _DrawingManagerCreator = DrawingManagerCreator; DrawingManagerCreator = (0, _utilsComponentLifecycleDecorator2["default"])({ registerEvents: registerEvents, instanceMethodName: "getDrawingManager", updaters: drawingManagerUpdaters })(DrawingManagerCreator) || DrawingManagerCreator; return DrawingManagerCreator; })(_react.Component); exports["default"] = DrawingManagerCreator; /***/ }, /* 31 */ /***/ function(module, exports) { // https://developers.google.com/maps/documentation/javascript/3.exp/reference#DrawingManager // [].map.call($0.querySelectorAll("tr>td>code"), function(it){ return it.textContent; }) "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports["default"] = ["circlecomplete", "markercomplete", "overlaycomplete", "polygoncomplete", "polylinecomplete", "rectanglecomplete"]; module.exports = exports["default"]; /***/ }, /* 32 */ /***/ function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _react = __webpack_require__(1); var _react2 = _interopRequireDefault(_react); var _canUseDom = __webpack_require__(23); var _canUseDom2 = _interopRequireDefault(_canUseDom); var _creatorsInfoWindowCreator = __webpack_require__(33); var _creatorsInfoWindowCreator2 = _interopRequireDefault(_creatorsInfoWindowCreator); var InfoWindow = (function (_Component) { _inherits(InfoWindow, _Component); function InfoWindow() { _classCallCheck(this, InfoWindow); _get(Object.getPrototypeOf(InfoWindow.prototype), "constructor", this).apply(this, arguments); this.state = {}; } _createClass(InfoWindow, [{ key: "getContent", // Public APIs // // https://developers.google.com/maps/documentation/javascript/3.exp/reference#InfoWindow // // [].map.call($0.querySelectorAll("tr>td>code"), function(it){ return it.textContent; }).filter(function(it){ return it.match(/^get/) && !it.match(/^getMap/); }) value: function getContent() {/* TODO: children */} }, { key: "getPosition", value: function getPosition() { return this.state.infoWindow.getPosition(); } }, { key: "getZIndex", value: function getZIndex() { return this.state.infoWindow.getZIndex(); } // END - Public APIs // // https://developers.google.com/maps/documentation/javascript/3.exp/reference#InfoWindow }, { key: "componentWillMount", value: function componentWillMount() { if (!_canUseDom2["default"]) { return; } var infoWindow = _creatorsInfoWindowCreator2["default"]._createInfoWindow(this.props); this.setState({ infoWindow: infoWindow }); } }, { key: "render", value: function render() { if (this.state.infoWindow) { return _react2["default"].createElement( _creatorsInfoWindowCreator2["default"], _extends({ infoWindow: this.state.infoWindow }, this.props), this.props.children ); } else { return _react2["default"].createElement("noscript", null); } } }], [{ key: "propTypes", value: _extends({}, _creatorsInfoWindowCreator.infoWindowDefaultPropTypes, _creatorsInfoWindowCreator.infoWindowControlledPropTypes, _creatorsInfoWindowCreator.infoWindowEventPropTypes), enumerable: true }]); return InfoWindow; })(_react.Component); exports["default"] = InfoWindow; module.exports = exports["default"]; // Uncontrolled default[props] - used only in componentDidMount // Controlled [props] - used in componentDidMount/componentDidUpdate // Event [onEventName] /***/ }, /* 33 */ /***/ function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _react = __webpack_require__(1); var _react2 = _interopRequireDefault(_react); var _eventListsInfoWindowEventList = __webpack_require__(34); var _eventListsInfoWindowEventList2 = _interopRequireDefault(_eventListsInfoWindowEventList); var _utilsEventHandlerCreator = __webpack_require__(15); var _utilsEventHandlerCreator2 = _interopRequireDefault(_utilsEventHandlerCreator); var _utilsDefaultPropsCreator = __webpack_require__(16); var _utilsDefaultPropsCreator2 = _interopRequireDefault(_utilsDefaultPropsCreator); var _utilsComposeOptions = __webpack_require__(18); var _utilsComposeOptions2 = _interopRequireDefault(_utilsComposeOptions); var _utilsSetContentForOptionalReactElement = __webpack_require__(35); var _utilsSetContentForOptionalReactElement2 = _interopRequireDefault(_utilsSetContentForOptionalReactElement); var _utilsComponentLifecycleDecorator = __webpack_require__(20); var _utilsComponentLifecycleDecorator2 = _interopRequireDefault(_utilsComponentLifecycleDecorator); var _GoogleMapHolder = __webpack_require__(12); var _GoogleMapHolder2 = _interopRequireDefault(_GoogleMapHolder); var infoWindowControlledPropTypes = { // NOTICE!!!!!! // // Only expose those with getters & setters in the table as controlled props. // // [].map.call($0.querySelectorAll("tr>td>code"), function(it){ return it.textContent; }).filter(function(it){ return it.match(/^set/) && !it.match(/^setMap/); }) // // https://developers.google.com/maps/documentation/javascript/3.exp/reference#InfoWindow content: _react.PropTypes.any, options: _react.PropTypes.object, position: _react.PropTypes.any, zIndex: _react.PropTypes.number }; exports.infoWindowControlledPropTypes = infoWindowControlledPropTypes; var infoWindowDefaultPropTypes = (0, _utilsDefaultPropsCreator2["default"])(infoWindowControlledPropTypes); exports.infoWindowDefaultPropTypes = infoWindowDefaultPropTypes; var infoWindowUpdaters = { children: function children(_children, component) { (0, _utilsSetContentForOptionalReactElement2["default"])(_children, component.getInfoWindow()); }, content: function content(_content, component) { component.getInfoWindow().setContent(_content); }, options: function options(_options, component) { component.getInfoWindow().setOptions(_options); }, position: function position(_position, component) { component.getInfoWindow().setPosition(_position); }, zIndex: function zIndex(_zIndex, component) { component.getInfoWindow().setZIndex(_zIndex); } }; var _eventHandlerCreator = (0, _utilsEventHandlerCreator2["default"])(_eventListsInfoWindowEventList2["default"]); var eventPropTypes = _eventHandlerCreator.eventPropTypes; var registerEvents = _eventHandlerCreator.registerEvents; var infoWindowEventPropTypes = eventPropTypes; exports.infoWindowEventPropTypes = infoWindowEventPropTypes; var InfoWindowCreator = (function (_Component) { _inherits(InfoWindowCreator, _Component); function InfoWindowCreator() { _classCallCheck(this, _InfoWindowCreator); _get(Object.getPrototypeOf(_InfoWindowCreator.prototype), "constructor", this).apply(this, arguments); } _createClass(InfoWindowCreator, [{ key: "getInfoWindow", value: function getInfoWindow() { return this.props.infoWindow; } }, { key: "render", value: function render() { return _react2["default"].createElement("noscript", null); } }], [{ key: "_createInfoWindow", value: function _createInfoWindow(infoWindowProps) { var mapHolderRef = infoWindowProps.mapHolderRef; var anchorHolderRef = infoWindowProps.anchorHolderRef; // https://developers.google.com/maps/documentation/javascript/3.exp/reference#InfoWindow var infoWindow = new google.maps.InfoWindow((0, _utilsComposeOptions2["default"])(infoWindowProps, infoWindowControlledPropTypes)); if (infoWindowProps.children) { (0, _utilsSetContentForOptionalReactElement2["default"])(infoWindowProps.children, infoWindow); } if (anchorHolderRef) { infoWindow.open(mapHolderRef.getMap(), anchorHolderRef.getAnchor()); } else { infoWindow.setMap(mapHolderRef.getMap()); } return infoWindow; } }, { key: "propTypes", value: { mapHolderRef: _react.PropTypes.instanceOf(_GoogleMapHolder2["default"]).isRequired, infoWindow: _react.PropTypes.object.isRequired, anchorHolderRef: _react.PropTypes.object }, enumerable: true }]); var _InfoWindowCreator = InfoWindowCreator; InfoWindowCreator = (0, _utilsComponentLifecycleDecorator2["default"])({ registerEvents: registerEvents, instanceMethodName: "getInfoWindow", updaters: infoWindowUpdaters })(InfoWindowCreator) || InfoWindowCreator; return InfoWindowCreator; })(_react.Component); exports["default"] = InfoWindowCreator; /***/ }, /* 34 */ /***/ function(module, exports) { // https://developers.google.com/maps/documentation/javascript/3.exp/reference#InfoWindow // [].map.call($0.querySelectorAll("tr>td>code"), function(it){ return it.textContent; }) "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports["default"] = ["closeclick", "content_changed", "domready", "position_changed", "zindex_changed"]; module.exports = exports["default"]; /***/ }, /* 35 */ /***/ function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports["default"] = setContentForOptionalReactElement; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } var _react = __webpack_require__(1); var _react2 = _interopRequireDefault(_react); var _reactDom = __webpack_require__(2); function renderElement(contentElement, prevContent) { if ("[object HTMLDivElement]" !== Object.prototype.toString.call(prevContent)) { prevContent = document.createElement("div"); } (0, _reactDom.render)(contentElement, prevContent); return prevContent; } function setContentForOptionalReactElement(contentOptionalReactElement, infoWindowLikeInstance) { if (_react2["default"].isValidElement(contentOptionalReactElement)) { var contentElement = _react.Children.only(contentOptionalReactElement); var prevContent = infoWindowLikeInstance.getContent(); var domEl = renderElement(contentOptionalReactElement, prevContent); infoWindowLikeInstance.setContent(domEl); } else { infoWindowLikeInstance.setContent(contentOptionalReactElement); } } module.exports = exports["default"]; /***/ }, /* 36 */ /***/ function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _react = __webpack_require__(1); var _react2 = _interopRequireDefault(_react); var _canUseDom = __webpack_require__(23); var _canUseDom2 = _interopRequireDefault(_canUseDom); var _creatorsMarkerCreator = __webpack_require__(37); var _creatorsMarkerCreator2 = _interopRequireDefault(_creatorsMarkerCreator); var Marker = (function (_Component) { _inherits(Marker, _Component); function Marker() { _classCallCheck(this, Marker); _get(Object.getPrototypeOf(Marker.prototype), "constructor", this).apply(this, arguments); this.state = {}; } _createClass(Marker, [{ key: "getAnimation", // Public APIs // // https://developers.google.com/maps/documentation/javascript/3.exp/reference#Marker // // [].map.call($0.querySelectorAll("tr>td>code"), function(it){ return it.textContent; }).filter(function(it){ return it.match(/^get/) && !it.match(/Map$/); }) value: function getAnimation() { return this.state.marker.getAnimation(); } }, { key: "getAttribution", value: function getAttribution() { return this.state.marker.getAttribution(); } }, { key: "getClickable", value: function getClickable() { return this.state.marker.getClickable(); } }, { key: "getCursor", value: function getCursor() { return this.state.marker.getCursor(); } }, { key: "getDraggable", value: function getDraggable() { return this.state.marker.getDraggable(); } }, { key: "getIcon", value: function getIcon() { return this.state.marker.getIcon(); } }, { key: "getLabel", value: function getLabel() { return this.state.marker.getLabel(); } }, { key: "getOpacity", value: function getOpacity() { return this.state.marker.getOpacity(); } }, { key: "getPlace", value: function getPlace() { return this.state.marker.getPlace(); } }, { key: "getPosition", value: function getPosition() { return this.state.marker.getPosition(); } }, { key: "getShape", value: function getShape() { return this.state.marker.getShape(); } }, { key: "getTitle", value: function getTitle() { return this.state.marker.getTitle(); } }, { key: "getVisible", value: function getVisible() { return this.state.marker.getVisible(); } }, { key: "getZIndex", value: function getZIndex() { return this.state.marker.getZIndex(); } // END - Public APIs // // https://developers.google.com/maps/documentation/javascript/3.exp/reference#Marker }, { key: "componentWillMount", value: function componentWillMount() { if (!_canUseDom2["default"]) { return; } var marker = _creatorsMarkerCreator2["default"]._createMarker(this.props); this.setState({ marker: marker }); } }, { key: "componentWillUnmount", value: function componentWillUnmount() { if (!_canUseDom2["default"]) { return; } var anchorHolderRef = this.props.anchorHolderRef; var marker = this.state.marker; if (anchorHolderRef) { if ("MarkerClusterer" === anchorHolderRef.getAnchorType()) { anchorHolderRef.getAnchor().removeMarker(marker); } } } }, { key: "render", value: function render() { if (this.state.marker) { return _react2["default"].createElement( _creatorsMarkerCreator2["default"], _extends({ marker: this.state.marker }, this.props), this.props.children ); } else { return _react2["default"].createElement("noscript", null); } } }], [{ key: "propTypes", value: _extends({}, _creatorsMarkerCreator.markerDefaultPropTypes, _creatorsMarkerCreator.markerControlledPropTypes, _creatorsMarkerCreator.markerEventPropTypes), enumerable: true }]); return Marker; })(_react.Component); exports["default"] = Marker; module.exports = exports["default"]; // Uncontrolled default[props] - used only in componentDidMount // Controlled [props] - used in componentDidMount/componentDidUpdate // Event [onEventName] /***/ }, /* 37 */ /***/ function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _react = __webpack_require__(1); var _react2 = _interopRequireDefault(_react); var _eventListsMarkerEventList = __webpack_require__(38); var _eventListsMarkerEventList2 = _interopRequireDefault(_eventListsMarkerEventList); var _utilsEventHandlerCreator = __webpack_require__(15); var _utilsEventHandlerCreator2 = _interopRequireDefault(_utilsEventHandlerCreator); var _utilsDefaultPropsCreator = __webpack_require__(16); var _utilsDefaultPropsCreator2 = _interopRequireDefault(_utilsDefaultPropsCreator); var _utilsComposeOptions = __webpack_require__(18); var _utilsComposeOptions2 = _interopRequireDefault(_utilsComposeOptions); var _utilsComponentLifecycleDecorator = __webpack_require__(20); var _utilsComponentLifecycleDecorator2 = _interopRequireDefault(_utilsComponentLifecycleDecorator); var _GoogleMapHolder = __webpack_require__(12); var _GoogleMapHolder2 = _interopRequireDefault(_GoogleMapHolder); var markerControlledPropTypes = { // NOTICE!!!!!! // // Only expose those with getters & setters in the table as controlled props. // // [].map.call($0.querySelectorAll("tr>td>code", function(it){ return it.textContent; }).filter(function(it){ return it.match(/^set/) && !it.match(/^setMap/); }) // // https://developers.google.com/maps/documentation/javascript/3.exp/reference#Marker animation: _react.PropTypes.any, attribution: _react.PropTypes.any, clickable: _react.PropTypes.bool, cursor: _react.PropTypes.string, draggable: _react.PropTypes.bool, icon: _react.PropTypes.any, label: _react.PropTypes.any, opacity: _react.PropTypes.number, options: _react.PropTypes.object, place: _react.PropTypes.any, position: _react.PropTypes.any, shape: _react.PropTypes.any, title: _react.PropTypes.string, visible: _react.PropTypes.bool, zIndex: _react.PropTypes.number }; exports.markerControlledPropTypes = markerControlledPropTypes; var markerDefaultPropTypes = (0, _utilsDefaultPropsCreator2["default"])(markerControlledPropTypes); exports.markerDefaultPropTypes = markerDefaultPropTypes; var markerUpdaters = { animation: function animation(_animation, component) { component.getMarker().setAnimation(_animation); }, attribution: function attribution(_attribution, component) { component.getMarker().setAttribution(_attribution); }, clickable: function clickable(_clickable, component) { component.getMarker().setClickable(_clickable); }, cursor: function cursor(_cursor, component) { component.getMarker().setCursor(_cursor); }, draggable: function draggable(_draggable, component) { component.getMarker().setDraggable(_draggable); }, icon: function icon(_icon, component) { component.getMarker().setIcon(_icon); }, label: function label(_label, component) { component.getMarker().setLabel(_label); }, opacity: function opacity(_opacity, component) { component.getMarker().setOpacity(_opacity); }, options: function options(_options, component) { component.getMarker().setOptions(_options); }, place: function place(_place, component) { component.getMarker().setPlace(_place); }, position: function position(_position, component) { component.getMarker().setPosition(_position); }, shape: function shape(_shape, component) { component.getMarker().setShape(_shape); }, title: function title(_title, component) { component.getMarker().setTitle(_title); }, visible: function visible(_visible, component) { component.getMarker().setVisible(_visible); }, zIndex: function zIndex(_zIndex, component) { component.getMarker().setZIndex(_zIndex); } }; var _eventHandlerCreator = (0, _utilsEventHandlerCreator2["default"])(_eventListsMarkerEventList2["default"]); var eventPropTypes = _eventHandlerCreator.eventPropTypes; var registerEvents = _eventHandlerCreator.registerEvents; var markerEventPropTypes = eventPropTypes; exports.markerEventPropTypes = markerEventPropTypes; var MarkerCreator = (function (_Component) { _inherits(MarkerCreator, _Component); function MarkerCreator() { _classCallCheck(this, _MarkerCreator); _get(Object.getPrototypeOf(_MarkerCreator.prototype), "constructor", this).apply(this, arguments); } _createClass(MarkerCreator, [{ key: "getMarker", value: function getMarker() { return this.props.marker; } // https://developers.google.com/maps/documentation/javascript/3.exp/reference#InfoWindowOptions // In the core API, the only anchor is the Marker class. }, { key: "getAnchor", value: function getAnchor() { return this.props.marker; } }, { key: "render", value: function render() { var _this = this; var _props = this.props; var mapHolderRef = _props.mapHolderRef; var children = _props.children; if (0 < _react.Children.count(children)) { return _react2["default"].createElement( "div", null, _react.Children.map(children, function (childElement) { return childElement && _react2["default"].cloneElement(childElement, { mapHolderRef: mapHolderRef, anchorHolderRef: _this }); }) ); } else { return _react2["default"].createElement("noscript", null); } } }], [{ key: "_createMarker", value: function _createMarker(markerProps) { var mapHolderRef = markerProps.mapHolderRef; var anchorHolderRef = markerProps.anchorHolderRef; // https://developers.google.com/maps/documentation/javascript/3.exp/reference#Marker var marker = new google.maps.Marker((0, _utilsComposeOptions2["default"])(markerProps, markerControlledPropTypes)); if (anchorHolderRef) { if ("MarkerClusterer" === anchorHolderRef.getAnchorType()) { anchorHolderRef.getAnchor().addMarker(marker); } } else { marker.setMap(mapHolderRef.getMap()); } return marker; } }, { key: "propTypes", value: { mapHolderRef: _react.PropTypes.instanceOf(_GoogleMapHolder2["default"]).isRequired, marker: _react.PropTypes.object.isRequired }, enumerable: true }]); var _MarkerCreator = MarkerCreator; MarkerCreator = (0, _utilsComponentLifecycleDecorator2["default"])({ registerEvents: registerEvents, instanceMethodName: "getMarker", updaters: markerUpdaters })(MarkerCreator) || MarkerCreator; return MarkerCreator; })(_react.Component); exports["default"] = MarkerCreator; /***/ }, /* 38 */ /***/ function(module, exports) { // https://developers.google.com/maps/documentation/javascript/3.exp/reference#Marker // [].map.call($0.querySelectorAll("tr>td>code"), function(it){ return it.textContent; }) "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports["default"] = ["animation_changed", "click", "clickable_changed", "cursor_changed", "dblclick", "drag", "dragend", "draggable_changed", "dragstart", "flat_changed", "icon_changed", "mousedown", "mouseout", "mouseover", "mouseup", "position_changed", "rightclick", "shape_changed", "title_changed", "visible_changed", "zindex_changed"]; module.exports = exports["default"]; /***/ }, /* 39 */ /***/ function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _react = __webpack_require__(1); var _react2 = _interopRequireDefault(_react); var _canUseDom = __webpack_require__(23); var _canUseDom2 = _interopRequireDefault(_canUseDom); var _creatorsOverlayViewCreator = __webpack_require__(40); var _creatorsOverlayViewCreator2 = _interopRequireDefault(_creatorsOverlayViewCreator); /* * Original author: @petebrowne * Original PR: https://github.com/tomchentw/react-google-maps/pull/63 */ var OverlayView = (function (_Component) { _inherits(OverlayView, _Component); function OverlayView() { _classCallCheck(this, OverlayView); _get(Object.getPrototypeOf(OverlayView.prototype), "constructor", this).apply(this, arguments); this.state = {}; } _createClass(OverlayView, [{ key: "getPanes", // Public APIs // // https://developers.google.com/maps/documentation/javascript/3.exp/reference#OverlayView // // [].map.call($0.querySelectorAll("tr>td>code"), function(it){ return it.textContent; }).filter(function(it){ return it.match(/^get/) && !it.match(/^getMap/); }) value: function getPanes() { return this.state.overlayView.getPanes(); } }, { key: "getProjection", value: function getProjection() { return this.state.overlayView.getProjection(); } // END - Public APIs // // https://developers.google.com/maps/documentation/javascript/3.exp/reference#OverlayView }, { key: "componentWillMount", value: function componentWillMount() { if (!_canUseDom2["default"]) { return; } var overlayView = _creatorsOverlayViewCreator2["default"]._createOverlayView(this.props); this.setState({ overlayView: overlayView }); } }, { key: "render", value: function render() { if (this.state.overlayView) { return _react2["default"].createElement( _creatorsOverlayViewCreator2["default"], _extends({ overlayView: this.state.overlayView }, this.props), this.props.children ); } else { return _react2["default"].createElement("noscript", null); } } }], [{ key: "FLOAT_PANE", value: "floatPane", enumerable: true }, { key: "MAP_PANE", value: "mapPane", enumerable: true }, { key: "MARKER_LAYER", value: "markerLayer", enumerable: true }, { key: "OVERLAY_LAYER", value: "overlayLayer", enumerable: true }, { key: "OVERLAY_MOUSE_TARGET", value: "overlayMouseTarget", enumerable: true }, { key: "propTypes", value: _extends({}, _creatorsOverlayViewCreator.overlayViewDefaultPropTypes, _creatorsOverlayViewCreator.overlayViewControlledPropTypes), enumerable: true }, { key: "defaultProps", value: { mapPaneName: OverlayView.OVERLAY_LAYER }, enumerable: true }]); return OverlayView; })(_react.Component); exports["default"] = OverlayView; module.exports = exports["default"]; // Uncontrolled default[props] - used only in componentDidMount // Controlled [props] - used in componentDidMount/componentDidUpdate /***/ }, /* 40 */ /***/ function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _react = __webpack_require__(1); var _react2 = _interopRequireDefault(_react); var _reactDom = __webpack_require__(2); var _invariant = __webpack_require__(41); var _invariant2 = _interopRequireDefault(_invariant); var _utilsDefaultPropsCreator = __webpack_require__(16); var _utilsDefaultPropsCreator2 = _interopRequireDefault(_utilsDefaultPropsCreator); var _utilsComposeOptions = __webpack_require__(18); var _utilsComposeOptions2 = _interopRequireDefault(_utilsComposeOptions); var _GoogleMapHolder = __webpack_require__(12); var _GoogleMapHolder2 = _interopRequireDefault(_GoogleMapHolder); var overlayViewControlledPropTypes = { // CustomProps mapPaneName: _react.PropTypes.string, getPixelPositionOffset: _react.PropTypes.func, position: _react.PropTypes.object, children: _react.PropTypes.node }; exports.overlayViewControlledPropTypes = overlayViewControlledPropTypes; // NOTICE!!!!!! // // Only expose those with getters & setters in the table as controlled props. // // [].map.call($0.querySelectorAll("tr>td>code"), function(it){ return it.textContent; }).filter(function(it){ return it.match(/^set/) && !it.match(/^setMap/); }) // // https://developers.google.com/maps/documentation/javascript/3.exp/reference var overlayViewDefaultPropTypes = (0, _utilsDefaultPropsCreator2["default"])(overlayViewControlledPropTypes); exports.overlayViewDefaultPropTypes = overlayViewDefaultPropTypes; var OverlayViewCreator = (function (_Component) { _inherits(OverlayViewCreator, _Component); function OverlayViewCreator() { _classCallCheck(this, OverlayViewCreator); _get(Object.getPrototypeOf(OverlayViewCreator.prototype), "constructor", this).apply(this, arguments); } _createClass(OverlayViewCreator, [{ key: "getOverlayView", value: function getOverlayView() { return this.props.overlayView; } }, { key: "componentDidMount", value: function componentDidMount() { this.getOverlayView().setMap(this.props.mapHolderRef.getMap()); } }, { key: "componentDidUpdate", value: function componentDidUpdate(prevProps) { this.getOverlayView().setValues(this.props); this.getOverlayView()._redraw(this.props.mapPaneName !== prevProps.mapPaneName); } }, { key: "componentWillUnmount", value: function componentWillUnmount() { this.getOverlayView().setMap(null); } }, { key: "render", value: function render() { return _react2["default"].createElement("noscript", null); } }], [{ key: "_createOverlayView", value: function _createOverlayView(overlayViewProps) { var mapHolderRef = overlayViewProps.mapHolderRef; // https://developers.google.com/maps/documentation/javascript/3.exp/reference#OverlayView var overlayView = new google.maps.OverlayView(); overlayView.setValues((0, _utilsComposeOptions2["default"])(overlayViewProps, overlayViewControlledPropTypes)); overlayView.onAdd = function () { this._containerElement = document.createElement("div"); this._containerElement.style.position = "absolute"; }; overlayView.draw = function () { this._renderContent(); this._mountContainerToPane(); this._positionContainerElement(); }; overlayView.onRemove = function () { (0, _reactDom.unmountComponentAtNode)(this._containerElement); this._unmountContainerFromPane(); this._containerElement = null; }; overlayView._redraw = function (mapPaneNameChanged) { this._renderContent(); if (mapPaneNameChanged) { this._unmountContainerFromPane(); this._mountContainerToPane(); } this._positionContainerElement(); }; overlayView._renderContent = function () { (0, _reactDom.render)(_react.Children.only(this.get("children")), this._containerElement); }; overlayView._mountContainerToPane = function () { var mapPaneName = this.get("mapPaneName"); (0, _invariant2["default"])(!!mapPaneName, "OverlayView requires a mapPaneName/defaultMapPaneName in your props instead of %s", mapPaneName); this.getPanes()[mapPaneName].appendChild(this._containerElement); }; overlayView._unmountContainerFromPane = function () { this._containerElement.parentNode.removeChild(this._containerElement); }; overlayView._positionContainerElement = function () { var left = undefined, top = undefined; var position = this._getPixelPosition(); if (position) { var x = position.x; var y = position.y; var offset = this._getOffset(); if (offset) { x += offset.x; y += offset.y; } left = x + "px"; top = y + "px"; } this._containerElement.style.left = left; this._containerElement.style.top = top; }; overlayView._getPixelPosition = function () { var projection = this.getProjection(); var position = this.get("position"); (0, _invariant2["default"])(!!position, "OverlayView requires a position/defaultPosition in your props instead of %s", position); if (projection && position) { if (!(position instanceof google.maps.LatLng)) { position = new google.maps.LatLng(position.lat, position.lng); } return projection.fromLatLngToDivPixel(position); } }; overlayView._getOffset = function () { // Allows the component to control the visual position of the OverlayView // relative to the LatLng pixel position. var getPixelPositionOffset = this.get("getPixelPositionOffset"); if (getPixelPositionOffset) { return getPixelPositionOffset(this._containerElement.offsetWidth, this._containerElement.offsetHeight); } }; return overlayView; } }, { key: "propTypes", value: { mapHolderRef: _react.PropTypes.instanceOf(_GoogleMapHolder2["default"]).isRequired, overlayView: _react.PropTypes.object.isRequired }, enumerable: true }]); return OverlayViewCreator; })(_react.Component); exports["default"] = OverlayViewCreator; /***/ }, /* 41 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ 'use strict'; /** * Use invariant() to assert state which your program assumes to be true. * * Provide sprintf-style format (only %s is supported) and arguments * to provide information about what broke and what you were * expecting. * * The invariant message will be stripped in production, but the invariant * will remain to ensure logic does not differ in production. */ var invariant = function(condition, format, a, b, c, d, e, f) { if (false) { if (format === undefined) { throw new Error('invariant requires an error message argument'); } } if (!condition) { var error; if (format === undefined) { error = new Error( 'Minified exception occurred; use the non-minified dev environment ' + 'for the full error message and additional helpful warnings.' ); } else { var args = [a, b, c, d, e, f]; var argIndex = 0; error = new Error( format.replace(/%s/g, function() { return args[argIndex++]; }) ); error.name = 'Invariant Violation'; } error.framesToPop = 1; // we don't care about invariant's own frame throw error; } }; module.exports = invariant; /***/ }, /* 42 */ /***/ function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _react = __webpack_require__(1); var _react2 = _interopRequireDefault(_react); var _canUseDom = __webpack_require__(23); var _canUseDom2 = _interopRequireDefault(_canUseDom); var _creatorsPolygonCreator = __webpack_require__(43); var _creatorsPolygonCreator2 = _interopRequireDefault(_creatorsPolygonCreator); var Polygon = (function (_Component) { _inherits(Polygon, _Component); function Polygon() { _classCallCheck(this, Polygon); _get(Object.getPrototypeOf(Polygon.prototype), "constructor", this).apply(this, arguments); this.state = {}; } _createClass(Polygon, [{ key: "getDraggable", // Public APIs // // https://developers.google.com/maps/documentation/javascript/3.exp/reference#Polygon // // [].map.call($0.querySelectorAll("tr>td>code"), function(it){ return it.textContent; }).filter(function(it){ return it.match(/^get/) && !it.match(/^getMap/); }) value: function getDraggable() { return this.state.polygon.getDraggable(); } }, { key: "getEditable", value: function getEditable() { return this.state.polygon.getEditable(); } }, { key: "getPath", value: function getPath() { return this.state.polygon.getPath(); } }, { key: "getPaths", value: function getPaths() { return this.state.polygon.getPaths(); } }, { key: "getVisible", value: function getVisible() { return this.state.polygon.getVisible(); } // END - Public APIs // // https://developers.google.com/maps/documentation/javascript/3.exp/reference#Polygon }, { key: "componentWillMount", value: function componentWillMount() { if (!_canUseDom2["default"]) { return; } var polygon = _creatorsPolygonCreator2["default"]._createPolygon(this.props); this.setState({ polygon: polygon }); } }, { key: "render", value: function render() { if (this.state.polygon) { return _react2["default"].createElement( _creatorsPolygonCreator2["default"], _extends({ polygon: this.state.polygon }, this.props), this.props.children ); } else { return _react2["default"].createElement("noscript", null); } } }], [{ key: "propTypes", value: _extends({}, _creatorsPolygonCreator.polygonDefaultPropTypes, _creatorsPolygonCreator.polygonControlledPropTypes, _creatorsPolygonCreator.polygonEventPropTypes), enumerable: true }]); return Polygon; })(_react.Component); exports["default"] = Polygon; module.exports = exports["default"]; // Uncontrolled default[props] - used only in componentDidMount // Controlled [props] - used in componentDidMount/componentDidUpdate // Event [onEventName] /***/ }, /* 43 */ /***/ function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _react = __webpack_require__(1); var _react2 = _interopRequireDefault(_react); var _eventListsPolygonEventList = __webpack_require__(44); var _eventListsPolygonEventList2 = _interopRequireDefault(_eventListsPolygonEventList); var _utilsEventHandlerCreator = __webpack_require__(15); var _utilsEventHandlerCreator2 = _interopRequireDefault(_utilsEventHandlerCreator); var _utilsDefaultPropsCreator = __webpack_require__(16); var _utilsDefaultPropsCreator2 = _interopRequireDefault(_utilsDefaultPropsCreator); var _utilsComposeOptions = __webpack_require__(18); var _utilsComposeOptions2 = _interopRequireDefault(_utilsComposeOptions); var _utilsComponentLifecycleDecorator = __webpack_require__(20); var _utilsComponentLifecycleDecorator2 = _interopRequireDefault(_utilsComponentLifecycleDecorator); var _GoogleMapHolder = __webpack_require__(12); var _GoogleMapHolder2 = _interopRequireDefault(_GoogleMapHolder); var polygonControlledPropTypes = { // NOTICE!!!!!! // // Only expose those with getters & setters in the table as controlled props. // // [].map.call($0.querySelectorAll("tr>td>code"), function(it){ return it.textContent; }).filter(function(it){ return it.match(/^set/) && !it.match(/^setMap/); }) // // https://developers.google.com/maps/documentation/javascript/3.exp/reference#Polygon draggable: _react.PropTypes.bool, editable: _react.PropTypes.bool, options: _react.PropTypes.object, path: _react.PropTypes.any, paths: _react.PropTypes.any, visible: _react.PropTypes.bool }; exports.polygonControlledPropTypes = polygonControlledPropTypes; var polygonDefaultPropTypes = (0, _utilsDefaultPropsCreator2["default"])(polygonControlledPropTypes); exports.polygonDefaultPropTypes = polygonDefaultPropTypes; var polygonUpdaters = { draggable: function draggable(_draggable, component) { component.getPolygon().setDraggable(_draggable); }, editable: function editable(_editable, component) { component.getPolygon().setEditable(_editable); }, options: function options(_options, component) { component.getPolygon().setOptions(_options); }, path: function path(_path, component) { component.getPolygon().setPath(_path); }, paths: function paths(_paths, component) { component.getPolygon().setPaths(_paths); }, visible: function visible(_visible, component) { component.getPolygon().setVisible(_visible); } }; var _eventHandlerCreator = (0, _utilsEventHandlerCreator2["default"])(_eventListsPolygonEventList2["default"]); var eventPropTypes = _eventHandlerCreator.eventPropTypes; var registerEvents = _eventHandlerCreator.registerEvents; var polygonEventPropTypes = eventPropTypes; exports.polygonEventPropTypes = polygonEventPropTypes; var PolygonCreator = (function (_Component) { _inherits(PolygonCreator, _Component); function PolygonCreator() { _classCallCheck(this, _PolygonCreator); _get(Object.getPrototypeOf(_PolygonCreator.prototype), "constructor", this).apply(this, arguments); } _createClass(PolygonCreator, [{ key: "getPolygon", value: function getPolygon() { return this.props.polygon; } }, { key: "render", value: function render() { return _react2["default"].createElement("noscript", null); } }], [{ key: "_createPolygon", value: function _createPolygon(polygonProps) { var mapHolderRef = polygonProps.mapHolderRef; // https://developers.google.com/maps/documentation/javascript/3.exp/reference#Polygon var polygon = new google.maps.Polygon((0, _utilsComposeOptions2["default"])(polygonProps, polygonControlledPropTypes)); polygon.setMap(mapHolderRef.getMap()); return polygon; } }, { key: "propTypes", value: { mapHolderRef: _react.PropTypes.instanceOf(_GoogleMapHolder2["default"]).isRequired, polygon: _react.PropTypes.object.isRequired }, enumerable: true }]); var _PolygonCreator = PolygonCreator; PolygonCreator = (0, _utilsComponentLifecycleDecorator2["default"])({ registerEvents: registerEvents, instanceMethodName: "getPolygon", updaters: polygonUpdaters })(PolygonCreator) || PolygonCreator; return PolygonCreator; })(_react.Component); exports["default"] = PolygonCreator; /***/ }, /* 44 */ /***/ function(module, exports) { // https://developers.google.com/maps/documentation/javascript/3.exp/reference#Polygon // [].map.call($0.querySelectorAll("tr>td>code"), function(it){ return it.textContent; }) "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports["default"] = ["click", "dblclick", "drag", "dragend", "dragstart", "mousedown", "mousemove", "mouseout", "mouseover", "mouseup", "rightclick"]; module.exports = exports["default"]; /***/ }, /* 45 */ /***/ function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _react = __webpack_require__(1); var _react2 = _interopRequireDefault(_react); var _canUseDom = __webpack_require__(23); var _canUseDom2 = _interopRequireDefault(_canUseDom); var _creatorsPolylineCreator = __webpack_require__(46); var _creatorsPolylineCreator2 = _interopRequireDefault(_creatorsPolylineCreator); var Polyline = (function (_Component) { _inherits(Polyline, _Component); function Polyline() { _classCallCheck(this, Polyline); _get(Object.getPrototypeOf(Polyline.prototype), "constructor", this).apply(this, arguments); this.state = {}; } _createClass(Polyline, [{ key: "getDraggable", // Public APIs // // https://developers.google.com/maps/documentation/javascript/3.exp/reference#Polyline // // [].map.call($0.querySelectorAll("tr>td>code"), function(it){ return it.textContent; }).filter(function(it){ return it.match(/^get/) && !it.match(/^getMap/); }) value: function getDraggable() { return this.state.polyline.getDraggable(); } }, { key: "getEditable", value: function getEditable() { return this.state.polyline.getEditable(); } }, { key: "getPath", value: function getPath() { return this.state.polyline.getPath(); } }, { key: "getVisible", value: function getVisible() { return this.state.polyline.getVisible(); } // END - Public APIs // // https://developers.google.com/maps/documentation/javascript/3.exp/reference#Polyline }, { key: "componentWillMount", value: function componentWillMount() { if (!_canUseDom2["default"]) { return; } var polyline = _creatorsPolylineCreator2["default"]._createPolyline(this.props); this.setState({ polyline: polyline }); } }, { key: "render", value: function render() { if (this.state.polyline) { return _react2["default"].createElement( _creatorsPolylineCreator2["default"], _extends({ polyline: this.state.polyline }, this.props), this.props.children ); } else { return _react2["default"].createElement("noscript", null); } } }], [{ key: "propTypes", value: _extends({}, _creatorsPolylineCreator.polylineDefaultPropTypes, _creatorsPolylineCreator.polylineControlledPropTypes, _creatorsPolylineCreator.polylineEventPropTypes), enumerable: true }]); return Polyline; })(_react.Component); exports["default"] = Polyline; module.exports = exports["default"]; // Uncontrolled default[props] - used only in componentDidMount // Controlled [props] - used in componentDidMount/componentDidUpdate // Event [onEventName] /***/ }, /* 46 */ /***/ function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _react = __webpack_require__(1); var _react2 = _interopRequireDefault(_react); var _eventListsPolylineEventList = __webpack_require__(47); var _eventListsPolylineEventList2 = _interopRequireDefault(_eventListsPolylineEventList); var _utilsEventHandlerCreator = __webpack_require__(15); var _utilsEventHandlerCreator2 = _interopRequireDefault(_utilsEventHandlerCreator); var _utilsDefaultPropsCreator = __webpack_require__(16); var _utilsDefaultPropsCreator2 = _interopRequireDefault(_utilsDefaultPropsCreator); var _utilsComposeOptions = __webpack_require__(18); var _utilsComposeOptions2 = _interopRequireDefault(_utilsComposeOptions); var _utilsComponentLifecycleDecorator = __webpack_require__(20); var _utilsComponentLifecycleDecorator2 = _interopRequireDefault(_utilsComponentLifecycleDecorator); var _GoogleMapHolder = __webpack_require__(12); var _GoogleMapHolder2 = _interopRequireDefault(_GoogleMapHolder); var polylineControlledPropTypes = { // NOTICE!!!!!! // // Only expose those with getters & setters in the table as controlled props. // // [].map.call($0.querySelectorAll("tr>td>code"), function(it){ return it.textContent; }).filter(function(it){ return it.match(/^set/) && !it.match(/^setMap/); }) // // https://developers.google.com/maps/documentation/javascript/3.exp/reference#Polyline draggable: _react.PropTypes.bool, editable: _react.PropTypes.bool, options: _react.PropTypes.object, path: _react.PropTypes.any, visible: _react.PropTypes.bool }; exports.polylineControlledPropTypes = polylineControlledPropTypes; var polylineDefaultPropTypes = (0, _utilsDefaultPropsCreator2["default"])(polylineControlledPropTypes); exports.polylineDefaultPropTypes = polylineDefaultPropTypes; var polylineUpdaters = { draggable: function draggable(_draggable, component) { component.getPolyline().setDraggable(_draggable); }, editable: function editable(_editable, component) { component.getPolyline().setEditable(_editable); }, options: function options(_options, component) { component.getPolyline().setOptions(_options); }, path: function path(_path, component) { component.getPolyline().setPath(_path); }, visible: function visible(_visible, component) { component.getPolyline().setVisible(_visible); } }; var _eventHandlerCreator = (0, _utilsEventHandlerCreator2["default"])(_eventListsPolylineEventList2["default"]); var eventPropTypes = _eventHandlerCreator.eventPropTypes; var registerEvents = _eventHandlerCreator.registerEvents; var polylineEventPropTypes = eventPropTypes; exports.polylineEventPropTypes = polylineEventPropTypes; var PolylineCreator = (function (_Component) { _inherits(PolylineCreator, _Component); function PolylineCreator() { _classCallCheck(this, _PolylineCreator); _get(Object.getPrototypeOf(_PolylineCreator.prototype), "constructor", this).apply(this, arguments); } _createClass(PolylineCreator, [{ key: "getPolyline", value: function getPolyline() { return this.props.polyline; } }, { key: "render", value: function render() { return _react2["default"].createElement("noscript", null); } }], [{ key: "_createPolyline", value: function _createPolyline(polylineProps) { var mapHolderRef = polylineProps.mapHolderRef; // https://developers.google.com/maps/documentation/javascript/3.exp/reference#Polyline var polyline = new google.maps.Polyline((0, _utilsComposeOptions2["default"])(polylineProps, polylineControlledPropTypes)); polyline.setMap(mapHolderRef.getMap()); return polyline; } }, { key: "propTypes", value: { mapHolderRef: _react.PropTypes.instanceOf(_GoogleMapHolder2["default"]).isRequired, polyline: _react.PropTypes.object.isRequired }, enumerable: true }]); var _PolylineCreator = PolylineCreator; PolylineCreator = (0, _utilsComponentLifecycleDecorator2["default"])({ registerEvents: registerEvents, instanceMethodName: "getPolyline", updaters: polylineUpdaters })(PolylineCreator) || PolylineCreator; return PolylineCreator; })(_react.Component); exports["default"] = PolylineCreator; /***/ }, /* 47 */ /***/ function(module, exports) { // https://developers.google.com/maps/documentation/javascript/3.exp/reference#Polyline // [].map.call($0.querySelectorAll("tr>td>code"), function(it){ return it.textContent; }) "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports["default"] = ["click", "dblclick", "drag", "dragend", "dragstart", "mousedown", "mousemove", "mouseout", "mouseover", "mouseup", "rightclick"]; module.exports = exports["default"]; /***/ }, /* 48 */ /***/ function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _react = __webpack_require__(1); var _react2 = _interopRequireDefault(_react); var _canUseDom = __webpack_require__(23); var _canUseDom2 = _interopRequireDefault(_canUseDom); var _creatorsRectangleCreator = __webpack_require__(49); var _creatorsRectangleCreator2 = _interopRequireDefault(_creatorsRectangleCreator); /* * Original author: @alistairjcbrown * Original PR: https://github.com/tomchentw/react-google-maps/pull/80 */ var Rectangle = (function (_Component) { _inherits(Rectangle, _Component); function Rectangle() { _classCallCheck(this, Rectangle); _get(Object.getPrototypeOf(Rectangle.prototype), "constructor", this).apply(this, arguments); this.state = {}; } _createClass(Rectangle, [{ key: "getBounds", // Public APIs // // https://developers.google.com/maps/documentation/javascript/3.exp/reference#Rectangle // // [].map.call($0.querySelectorAll("tr>td>code"), function(it){ return it.textContent; }).filter(function(it){ return it.match(/^get/) && !it.match(/^getMap/); }) value: function getBounds() { return this.state.rectangle.getBounds(); } }, { key: "getDraggable", value: function getDraggable() { return this.state.rectangle.getDraggable(); } }, { key: "getEditable", value: function getEditable() { return this.state.rectangle.getEditable(); } }, { key: "getVisible", value: function getVisible() { return this.state.rectangle.getVisible(); } // END - Public APIs // // https://developers.google.com/maps/documentation/javascript/3.exp/reference#Rectangle }, { key: "componentWillMount", value: function componentWillMount() { if (!_canUseDom2["default"]) { return; } var rectangle = _creatorsRectangleCreator2["default"]._createRectangle(this.props); this.setState({ rectangle: rectangle }); } }, { key: "render", value: function render() { if (this.state.rectangle) { return _react2["default"].createElement( _creatorsRectangleCreator2["default"], _extends({ rectangle: this.state.rectangle }, this.props), this.props.children ); } else { return _react2["default"].createElement("noscript", null); } } }], [{ key: "propTypes", value: _extends({}, _creatorsRectangleCreator.rectangleDefaultPropTypes, _creatorsRectangleCreator.rectangleControlledPropTypes, _creatorsRectangleCreator.rectangleEventPropTypes), enumerable: true }]); return Rectangle; })(_react.Component); exports["default"] = Rectangle; module.exports = exports["default"]; // Uncontrolled default[props] - used only in componentDidMount // Controlled [props] - used in componentDidMount/componentDidUpdate // Event [onEventName] /***/ }, /* 49 */ /***/ function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _react = __webpack_require__(1); var _react2 = _interopRequireDefault(_react); var _eventListsRectangleEventList = __webpack_require__(50); var _eventListsRectangleEventList2 = _interopRequireDefault(_eventListsRectangleEventList); var _utilsEventHandlerCreator = __webpack_require__(15); var _utilsEventHandlerCreator2 = _interopRequireDefault(_utilsEventHandlerCreator); var _utilsDefaultPropsCreator = __webpack_require__(16); var _utilsDefaultPropsCreator2 = _interopRequireDefault(_utilsDefaultPropsCreator); var _utilsComposeOptions = __webpack_require__(18); var _utilsComposeOptions2 = _interopRequireDefault(_utilsComposeOptions); var _utilsComponentLifecycleDecorator = __webpack_require__(20); var _utilsComponentLifecycleDecorator2 = _interopRequireDefault(_utilsComponentLifecycleDecorator); var _GoogleMapHolder = __webpack_require__(12); var _GoogleMapHolder2 = _interopRequireDefault(_GoogleMapHolder); var rectangleControlledPropTypes = { // NOTICE!!!!!! // // Only expose those with getters & setters in the table as controlled props. // // [].map.call($0.querySelectorAll("tr>td>code"), function(it){ return it.textContent; }).filter(function(it){ return it.match(/^set/) && !it.match(/^setMap/); }) // // https://developers.google.com/maps/documentation/javascript/3.exp/reference#Rectangle bounds: _react.PropTypes.any, draggable: _react.PropTypes.bool, editable: _react.PropTypes.bool, options: _react.PropTypes.object, visible: _react.PropTypes.bool }; exports.rectangleControlledPropTypes = rectangleControlledPropTypes; var rectangleDefaultPropTypes = (0, _utilsDefaultPropsCreator2["default"])(rectangleControlledPropTypes); exports.rectangleDefaultPropTypes = rectangleDefaultPropTypes; var rectangleUpdaters = { bounds: function bounds(_bounds, component) { component.getRectangle().setBounds(_bounds); }, draggable: function draggable(_draggable, component) { component.getRectangle().setDraggable(_draggable); }, editable: function editable(_editable, component) { component.getRectangle().setEditable(_editable); }, options: function options(_options, component) { component.getRectangle().setOptions(_options); }, visible: function visible(_visible, component) { component.getRectangle().setVisible(_visible); } }; var _eventHandlerCreator = (0, _utilsEventHandlerCreator2["default"])(_eventListsRectangleEventList2["default"]); var eventPropTypes = _eventHandlerCreator.eventPropTypes; var registerEvents = _eventHandlerCreator.registerEvents; var rectangleEventPropTypes = eventPropTypes; exports.rectangleEventPropTypes = rectangleEventPropTypes; var RectangleCreator = (function (_Component) { _inherits(RectangleCreator, _Component); function RectangleCreator() { _classCallCheck(this, _RectangleCreator); _get(Object.getPrototypeOf(_RectangleCreator.prototype), "constructor", this).apply(this, arguments); } _createClass(RectangleCreator, [{ key: "getRectangle", value: function getRectangle() { return this.props.rectangle; } }, { key: "render", value: function render() { return _react2["default"].createElement("noscript", null); } }], [{ key: "_createRectangle", value: function _createRectangle(rectangleProps) { var mapHolderRef = rectangleProps.mapHolderRef; // https://developers.google.com/maps/documentation/javascript/3.exp/reference#Rectangle var rectangle = new google.maps.Rectangle((0, _utilsComposeOptions2["default"])(rectangleProps, rectangleControlledPropTypes)); rectangle.setMap(mapHolderRef.getMap()); return rectangle; } }, { key: "propTypes", value: { mapHolderRef: _react.PropTypes.instanceOf(_GoogleMapHolder2["default"]).isRequired, rectangle: _react.PropTypes.object.isRequired }, enumerable: true }]); var _RectangleCreator = RectangleCreator; RectangleCreator = (0, _utilsComponentLifecycleDecorator2["default"])({ registerEvents: registerEvents, instanceMethodName: "getRectangle", updaters: rectangleUpdaters })(RectangleCreator) || RectangleCreator; return RectangleCreator; })(_react.Component); exports["default"] = RectangleCreator; /***/ }, /* 50 */ /***/ function(module, exports) { // https://developers.google.com/maps/documentation/javascript/3.exp/reference#Rectangle // [].map.call($0.querySelectorAll("tr>td>code"), function(it){ return it.textContent; }) "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports["default"] = ["bounds_changed", "click", "dblclick", "drag", "dragend", "dragstart", "mousedown", "mousemove", "mouseout", "mouseover", "mouseup", "rightclick"]; module.exports = exports["default"]; /***/ }, /* 51 */ /***/ function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _react = __webpack_require__(1); var _react2 = _interopRequireDefault(_react); var _canUseDom = __webpack_require__(23); var _canUseDom2 = _interopRequireDefault(_canUseDom); var _creatorsSearchBoxCreator = __webpack_require__(52); var _creatorsSearchBoxCreator2 = _interopRequireDefault(_creatorsSearchBoxCreator); /* * Original author: @eyebraus * Original PR: https://github.com/tomchentw/react-google-maps/pull/110 */ var SearchBox = (function (_Component) { _inherits(SearchBox, _Component); function SearchBox() { _classCallCheck(this, SearchBox); _get(Object.getPrototypeOf(SearchBox.prototype), "constructor", this).apply(this, arguments); this.state = {}; } _createClass(SearchBox, [{ key: "getBounds", // Public APIs // // https://developers.google.com/maps/documentation/javascript/3.exp/reference#SearchBox // // [].map.call($0.querySelectorAll("tr>td>code"), function(it){ return it.textContent; }).filter(function(it){ return it.match(/^get/) && !it.match(/Map$/); }) value: function getBounds() { return this.state.searchBox.getBounds(); } }, { key: "getPlaces", value: function getPlaces() { return this.state.searchBox.getPlaces(); } // END - Public APIs // // https://developers.google.com/maps/documentation/javascript/3.exp/reference#SearchBox }, { key: "componentWillMount", value: function componentWillMount() { if (!_canUseDom2["default"]) { return; } var _props = this.props; var mapHolderRef = _props.mapHolderRef; var classes = _props.classes; var style = _props.style; var placeholder = _props.placeholder; var searchBoxProps = _objectWithoutProperties(_props, ["mapHolderRef", "classes", "style", "placeholder"]); // Cannot create input via component - Google Maps will mess with React's internal state by detaching/attaching. // Allow developers to style the "hidden element" via inputClasses. var domEl = document.createElement("input"); domEl.className = classes; domEl.type = "text"; domEl.placeholder = placeholder; for (var propKey in style) { if (style.hasOwnProperty(propKey)) { domEl.style[propKey] = style[propKey]; } } var searchBox = _creatorsSearchBoxCreator2["default"]._createSearchBox(domEl, searchBoxProps); this.setState({ inputElement: domEl, searchBox: searchBox }); } }, { key: "render", value: function render() { var _props2 = this.props; var mapHolderRef = _props2.mapHolderRef; var controlPosition = _props2.controlPosition; return this.state.searchBox ? _react2["default"].createElement( _creatorsSearchBoxCreator2["default"], _extends({ controlPosition: controlPosition, inputElement: this.state.inputElement, mapHolderRef: mapHolderRef, searchBox: this.state.searchBox }, this.props), this.props.children ) : _react2["default"].createElement("noscript", null); } }], [{ key: "propTypes", value: _extends({}, _creatorsSearchBoxCreator.searchBoxDefaultPropTypes, _creatorsSearchBoxCreator.searchBoxControlledPropTypes, _creatorsSearchBoxCreator.searchBoxEventPropTypes), enumerable: true }]); return SearchBox; })(_react.Component); exports["default"] = SearchBox; module.exports = exports["default"]; // Uncontrolled default[props] - used only in componentDidMount // Controlled [props] - used in componentDidMount/componentDidUpdate // Event [onEventName] /***/ }, /* 52 */ /***/ function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _react = __webpack_require__(1); var _react2 = _interopRequireDefault(_react); var _eventListsSearchBoxEventList = __webpack_require__(53); var _eventListsSearchBoxEventList2 = _interopRequireDefault(_eventListsSearchBoxEventList); var _utilsEventHandlerCreator = __webpack_require__(15); var _utilsEventHandlerCreator2 = _interopRequireDefault(_utilsEventHandlerCreator); var _utilsDefaultPropsCreator = __webpack_require__(16); var _utilsDefaultPropsCreator2 = _interopRequireDefault(_utilsDefaultPropsCreator); var _utilsComposeOptions = __webpack_require__(18); var _utilsComposeOptions2 = _interopRequireDefault(_utilsComposeOptions); var _utilsComponentLifecycleDecorator = __webpack_require__(20); var _utilsComponentLifecycleDecorator2 = _interopRequireDefault(_utilsComponentLifecycleDecorator); var _GoogleMapHolder = __webpack_require__(12); var _GoogleMapHolder2 = _interopRequireDefault(_GoogleMapHolder); var searchBoxControlledPropTypes = { // NOTICE!!!!!! // // Only expose those with getters & setters in the table as controlled props. // bounds: _react.PropTypes.any }; exports.searchBoxControlledPropTypes = searchBoxControlledPropTypes; var searchBoxDefaultPropTypes = (0, _utilsDefaultPropsCreator2["default"])(searchBoxControlledPropTypes); exports.searchBoxDefaultPropTypes = searchBoxDefaultPropTypes; var searchBoxUpdaters = { bounds: function bounds(_bounds, component) { component.getSearchBox().setBounds(_bounds); } }; var _eventHandlerCreator = (0, _utilsEventHandlerCreator2["default"])(_eventListsSearchBoxEventList2["default"]); var eventPropTypes = _eventHandlerCreator.eventPropTypes; var registerEvents = _eventHandlerCreator.registerEvents; var searchBoxEventPropTypes = eventPropTypes; exports.searchBoxEventPropTypes = searchBoxEventPropTypes; var SearchBoxCreator = (function (_Component) { _inherits(SearchBoxCreator, _Component); function SearchBoxCreator() { _classCallCheck(this, _SearchBoxCreator); _get(Object.getPrototypeOf(_SearchBoxCreator.prototype), "constructor", this).apply(this, arguments); } _createClass(SearchBoxCreator, [{ key: "componentDidMount", value: function componentDidMount() { this._mountComponentToMap(this.props.controlPosition); } }, { key: "componentDidUpdate", value: function componentDidUpdate(prevProps) { if (this.props.controlPosition !== prevProps.controlPosition) { this._unmountComponentFromMap(prevProps.controlPosition); this._mountComponentToMap(this.props.controlPosition); } } }, { key: "componentWillUnmount", value: function componentWillUnmount() { this._unmountComponentFromMap(this.props.controlPosition); } }, { key: "_mountComponentToMap", value: function _mountComponentToMap(controlPosition) { var _props = this.props; var mapHolderRef = _props.mapHolderRef; var inputElement = _props.inputElement; mapHolderRef.getMap().controls[controlPosition].push(inputElement); } }, { key: "_unmountComponentFromMap", value: function _unmountComponentFromMap(controlPosition) { var _props2 = this.props; var mapHolderRef = _props2.mapHolderRef; var inputElement = _props2.inputElement; var index = mapHolderRef.getMap().controls[controlPosition].getArray().indexOf(inputElement); mapHolderRef.getMap().controls[controlPosition].removeAt(index); } }, { key: "getSearchBox", value: function getSearchBox() { return this.props.searchBox; } }, { key: "render", value: function render() { return _react2["default"].createElement("noscript", null); } }], [{ key: "_createSearchBox", value: function _createSearchBox(inputElement, searchBoxProps) { var searchBox = new google.maps.places.SearchBox(inputElement, (0, _utilsComposeOptions2["default"])(searchBoxProps, searchBoxControlledPropTypes)); return searchBox; } }, { key: "propTypes", value: { mapHolderRef: _react.PropTypes.instanceOf(_GoogleMapHolder2["default"]).isRequired, searchBox: _react.PropTypes.object.isRequired }, enumerable: true }]); var _SearchBoxCreator = SearchBoxCreator; SearchBoxCreator = (0, _utilsComponentLifecycleDecorator2["default"])({ registerEvents: registerEvents, instanceMethodName: "getSearchBox", updaters: searchBoxUpdaters })(SearchBoxCreator) || SearchBoxCreator; return SearchBoxCreator; })(_react.Component); exports["default"] = SearchBoxCreator; /***/ }, /* 53 */ /***/ function(module, exports) { // https://developers.google.com/maps/documentation/javascript/3.exp/reference#SearchBox // [].map.call($0.querySelectorAll("tr>td>code"), function(it){ return it.textContent; }) "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports["default"] = ["places_changed"]; module.exports = exports["default"]; /***/ }, /* 54 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); var _get = function get(_x5, _x6, _x7) { var _again = true; _function: while (_again) { var object = _x5, property = _x6, receiver = _x7; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x5 = parent; _x6 = property; _x7 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _react = __webpack_require__(1); var _react2 = _interopRequireDefault(_react); var _canUseDom = __webpack_require__(23); var _canUseDom2 = _interopRequireDefault(_canUseDom); var _addonsCreatorsMarkerClustererCreator = __webpack_require__(55); var _addonsCreatorsMarkerClustererCreator2 = _interopRequireDefault(_addonsCreatorsMarkerClustererCreator); var MarkerClusterer = (function (_Component) { _inherits(MarkerClusterer, _Component); function MarkerClusterer() { _classCallCheck(this, MarkerClusterer); _get(Object.getPrototypeOf(MarkerClusterer.prototype), 'constructor', this).apply(this, arguments); this.state = {}; } _createClass(MarkerClusterer, [{ key: 'getAvaerageCenter', // Public APIs // http://google-maps-utility-library-v3.googlecode.com/svn/trunk/markerclustererplus/docs/reference.html#events value: function getAvaerageCenter() { return this.state.markerClusterer.getAvaerageCenter(); } }, { key: 'getBatchSizeIE', value: function getBatchSizeIE() { return this.state.markerClusterer.getBatchSizeIE(); } }, { key: 'getCalculator', value: function getCalculator() { return this.state.markerClusterer.getCalculator(); } }, { key: 'getClusterClass', value: function getClusterClass() { return this.state.markerClusterer.getClusterClass(); } }, { key: 'getClusters', value: function getClusters() { return this.state.markerClusterer.getClusters(); } }, { key: 'getEnableRetinaIcons', value: function getEnableRetinaIcons() { return this.state.markerClusterer.getEnableRetinaIcons(); } }, { key: 'getGridSize', value: function getGridSize() { return this.state.markerClusterer.getGridSize(); } }, { key: 'getIgnoreHidden', value: function getIgnoreHidden() { return this.state.markerClusterer.getIgnoreHidden(); } }, { key: 'getImageExtension', value: function getImageExtension() { return this.state.markerClusterer.getImageExtension(); } }, { key: 'getImagePath', value: function getImagePath() { return this.state.markerClusterer.getImagePath(); } }, { key: 'getImageSize', value: function getImageSize() { return this.state.markerClusterer.getImageSize(); } }, { key: 'getMarkers', value: function getMarkers() { return this.state.markerClusterer.getMarkers(); } }, { key: 'getMaxZoom', value: function getMaxZoom() { return this.state.markerClusterer.getMaxZoom(); } }, { key: 'getMinimumClusterSize', value: function getMinimumClusterSize() { return this.state.markerClusterer.getMinimumClusterSize(); } }, { key: 'getStyles', value: function getStyles() { return this.state.markerClusterer.getStyles(); } }, { key: 'getTitle', value: function getTitle() { return this.state.markerClusterer.getTitle(); } }, { key: 'getTotalClusters', value: function getTotalClusters() { return this.state.markerClusterer.getTotalClusters(); } }, { key: 'getZoomOnClick', value: function getZoomOnClick() { return this.state.markerClusterer.getZoomOnClick(); } // Public APIs - Use this carefully }, { key: 'addMarker', value: function addMarker(marker) { var nodraw = arguments.length <= 1 || arguments[1] === undefined ? false : arguments[1]; return this.state.markerClusterer.addMarker(marker, nodraw); } }, { key: 'addMarkers', value: function addMarkers(markers) { var nodraw = arguments.length <= 1 || arguments[1] === undefined ? false : arguments[1]; return this.state.markerClusterer.addMarkers(markers, nodraw); } }, { key: 'removeMarker', value: function removeMarker(marker) { var nodraw = arguments.length <= 1 || arguments[1] === undefined ? false : arguments[1]; return this.state.markerClusterer.removeMarker(marker, nodraw); } }, { key: 'removeMarkers', value: function removeMarkers(markers) { var nodraw = arguments.length <= 1 || arguments[1] === undefined ? false : arguments[1]; return this.state.markerClusterer.removeMarkers(markers, nodraw); } }, { key: 'clearMarkers', value: function clearMarkers() { return this.state.markerClusterer.clearMarkers(); } }, { key: 'fitMapToMarkers', value: function fitMapToMarkers() { return this.state.markerClusterer.fitMapToMarkers(); } }, { key: 'repaint', value: function repaint() { return this.state.markerClusterer.repaint(); } }, { key: 'componentWillMount', value: function componentWillMount() { if (!_canUseDom2['default']) { return; } var _props = this.props; var mapHolderRef = _props.mapHolderRef; var markerClustererProps = _objectWithoutProperties(_props, ['mapHolderRef']); var markerClusterer = _addonsCreatorsMarkerClustererCreator2['default']._createMarkerClusterer(mapHolderRef, markerClustererProps); this.setState({ markerClusterer: markerClusterer }); } }, { key: 'render', value: function render() { if (this.state.markerClusterer) { return _react2['default'].createElement( _addonsCreatorsMarkerClustererCreator2['default'], _extends({ markerClusterer: this.state.markerClusterer }, this.props), this.props.children ); } else { return _react2['default'].createElement('noscript', null); } } }], [{ key: 'propTypes', value: _extends({}, _addonsCreatorsMarkerClustererCreator.markerClusterDefaultPropTypes, _addonsCreatorsMarkerClustererCreator.markerClusterControlledPropTypes, _addonsCreatorsMarkerClustererCreator.markerClusterEventPropTypes), enumerable: true }]); return MarkerClusterer; })(_react.Component); exports['default'] = MarkerClusterer; module.exports = exports['default']; /***/ }, /* 55 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _react = __webpack_require__(1); var _react2 = _interopRequireDefault(_react); var _invariant = __webpack_require__(41); var _invariant2 = _interopRequireDefault(_invariant); var _addonsEventListsMarkerClustererEventList = __webpack_require__(56); var _addonsEventListsMarkerClustererEventList2 = _interopRequireDefault(_addonsEventListsMarkerClustererEventList); var _utilsEventHandlerCreator = __webpack_require__(15); var _utilsEventHandlerCreator2 = _interopRequireDefault(_utilsEventHandlerCreator); var _utilsDefaultPropsCreator = __webpack_require__(16); var _utilsDefaultPropsCreator2 = _interopRequireDefault(_utilsDefaultPropsCreator); var _utilsComposeOptions = __webpack_require__(18); var _utilsComposeOptions2 = _interopRequireDefault(_utilsComposeOptions); var _utilsComponentLifecycleDecorator = __webpack_require__(20); var _utilsComponentLifecycleDecorator2 = _interopRequireDefault(_utilsComponentLifecycleDecorator); var _creatorsGoogleMapHolder = __webpack_require__(12); var _creatorsGoogleMapHolder2 = _interopRequireDefault(_creatorsGoogleMapHolder); var markerClustererControlledPropTypes = { // http://google-maps-utility-library-v3.googlecode.com/svn/trunk/markerclustererplus/docs/reference.html averageCenter: _react.PropTypes.bool, batchSizeIE: _react.PropTypes.number, calculator: _react.PropTypes.func, clusterClass: _react.PropTypes.string, enableRetinaIcons: _react.PropTypes.bool, gridSize: _react.PropTypes.number, ignoreHidden: _react.PropTypes.bool, imageExtension: _react.PropTypes.string, imagePath: _react.PropTypes.string, imageSizes: _react.PropTypes.array, maxZoom: _react.PropTypes.number, minimumClusterSize: _react.PropTypes.number, styles: _react.PropTypes.array, title: _react.PropTypes.string, zoomOnClick: _react.PropTypes.bool }; exports.markerClustererControlledPropTypes = markerClustererControlledPropTypes; var markerClustererDefaultPropTypes = (0, _utilsDefaultPropsCreator2['default'])(markerClustererControlledPropTypes); exports.markerClustererDefaultPropTypes = markerClustererDefaultPropTypes; var markerClustererUpdaters = { averageCenter: function averageCenter(_averageCenter, component) { component.getMarkerClusterer().setAverageCenter(_averageCenter); }, batchSizeIE: function batchSizeIE(_batchSizeIE, component) { component.getMarkerClusterer().setBatchSizeIE(_batchSizeIE); }, calculator: function calculator(_calculator, component) { component.getMarkerClusterer().setCalculator(_calculator); }, enableRetinaIcons: function enableRetinaIcons(_enableRetinaIcons, component) { component.getMarkerClusterer().setEnableRetinaIcons(_enableRetinaIcons); }, gridSize: function gridSize(_gridSize, component) { component.getMarkerClusterer().setGridSize(_gridSize); }, ignoreHidden: function ignoreHidden(_ignoreHidden, component) { component.getMarkerClusterer().setIgnoreHidden(_ignoreHidden); }, imageExtension: function imageExtension(_imageExtension, component) { component.getMarkerClusterer().setImageExtension(_imageExtension); }, imagePath: function imagePath(_imagePath, component) { component.getMarkerClusterer().setImagePath(_imagePath); }, imageSizes: function imageSizes(_imageSizes, component) { component.getMarkerClusterer().setImageSizes(_imageSizes); }, maxZoom: function maxZoom(_maxZoom, component) { component.getMarkerClusterer().setMaxZoom(_maxZoom); }, minimumClusterSize: function minimumClusterSize(_minimumClusterSize, component) { component.getMarkerClusterer().setMinimumClusterSize(_minimumClusterSize); }, styles: function styles(_styles, component) { component.getMarkerClusterer().setStyles(_styles); }, title: function title(_title, component) { component.getMarkerClusterer().setTitle(_title); }, zoomOnClick: function zoomOnClick(_zoomOnClick, component) { component.getMarkerClusterer().setZoomOnClick(_zoomOnClick); } }; var _eventHandlerCreator = (0, _utilsEventHandlerCreator2['default'])(_addonsEventListsMarkerClustererEventList2['default']); var eventPropTypes = _eventHandlerCreator.eventPropTypes; var registerEvents = _eventHandlerCreator.registerEvents; var markerClustererEventPropTypes = eventPropTypes; exports.markerClustererEventPropTypes = markerClustererEventPropTypes; var MarkerClustererCreator = (function (_Component) { _inherits(MarkerClustererCreator, _Component); function MarkerClustererCreator() { _classCallCheck(this, _MarkerClustererCreator); _get(Object.getPrototypeOf(_MarkerClustererCreator.prototype), 'constructor', this).apply(this, arguments); } _createClass(MarkerClustererCreator, [{ key: 'getMarkerClusterer', value: function getMarkerClusterer() { return this.props.markerClusterer; } }, { key: 'componentDidUpdate', value: function componentDidUpdate(prevProps) { this.props.markerClusterer.repaint(); } }, { key: 'componentWillUnmount', value: function componentWillUnmount() { this.props.markerClusterer.setMap(null); } }, { key: 'getAnchor', value: function getAnchor() { return this.props.markerClusterer; } }, { key: 'getAnchorType', value: function getAnchorType() { return 'MarkerClusterer'; } }, { key: 'render', value: function render() { var _this = this; var _props = this.props; var mapHolderRef = _props.mapHolderRef; var children = _props.children; if (0 < _react.Children.count(children)) { return _react2['default'].createElement( 'div', null, _react.Children.map(children, function (childElement) { if (_react2['default'].isValidElement(childElement)) { return _react2['default'].cloneElement(childElement, { mapHolderRef: mapHolderRef, anchorHolderRef: _this }); } else { return childElement; } }) ); } else { return _react2['default'].createElement('noscript', null); } } }], [{ key: '_createMarkerClusterer', value: function _createMarkerClusterer(mapHolderRef, markerClustererProps) { var GoogleMarkerClusterer = __webpack_require__(57); // http://google-maps-utility-library-v3.googlecode.com/svn/trunk/markerclustererplus/docs/reference.html#events var markerClusterer = new GoogleMarkerClusterer(mapHolderRef.getMap(), [], (0, _utilsComposeOptions2['default'])(markerClustererProps, markerClustererControlledPropTypes)); return markerClusterer; } }, { key: 'PropTypes', value: { mapHolderRef: _react.PropTypes.instanceOf(_creatorsGoogleMapHolder2['default']).isRequired, markerClusterer: _react.PropTypes.object.isRequired }, enumerable: true }]); var _MarkerClustererCreator = MarkerClustererCreator; MarkerClustererCreator = (0, _utilsComponentLifecycleDecorator2['default'])({ registerEvents: registerEvents, instanceMethodName: 'getMarkerClusterer', updaters: markerClustererUpdaters })(MarkerClustererCreator) || MarkerClustererCreator; return MarkerClustererCreator; })(_react.Component); exports['default'] = MarkerClustererCreator; /***/ }, /* 56 */ /***/ function(module, exports) { // http://google-maps-utility-library-v3.googlecode.com/svn/trunk/markerclustererplus/docs/reference.html "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports["default"] = ["click", "clusteringbegin", "clusteringend", "mouseout", "mouseover"]; module.exports = exports["default"]; /***/ }, /* 57 */ /***/ function(module, exports) { /** * @name MarkerClustererPlus for Google Maps V3 * @version 2.1.2 [May 28, 2014] * @author Gary Little * @fileoverview * The library creates and manages per-zoom-level clusters for large amounts of markers. * <p> * This is an enhanced V3 implementation of the * <a href="http://gmaps-utility-library-dev.googlecode.com/svn/tags/markerclusterer/" * >V2 MarkerClusterer</a> by Xiaoxi Wu. It is based on the * <a href="http://google-maps-utility-library-v3.googlecode.com/svn/tags/markerclusterer/" * >V3 MarkerClusterer</a> port by Luke Mahe. MarkerClustererPlus was created by Gary Little. * <p> * v2.0 release: MarkerClustererPlus v2.0 is backward compatible with MarkerClusterer v1.0. It * adds support for the <code>ignoreHidden</code>, <code>title</code>, <code>batchSizeIE</code>, * and <code>calculator</code> properties as well as support for four more events. It also allows * greater control over the styling of the text that appears on the cluster marker. The * documentation has been significantly improved and the overall code has been simplified and * polished. Very large numbers of markers can now be managed without causing Javascript timeout * errors on Internet Explorer. Note that the name of the <code>clusterclick</code> event has been * deprecated. The new name is <code>click</code>, so please change your application code now. */ /** * 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. */ /** * @name ClusterIconStyle * @class This class represents the object for values in the <code>styles</code> array passed * to the {@link MarkerClusterer} constructor. The element in this array that is used to * style the cluster icon is determined by calling the <code>calculator</code> function. * * @property {string} url The URL of the cluster icon image file. Required. * @property {number} height The display height (in pixels) of the cluster icon. Required. * @property {number} width The display width (in pixels) of the cluster icon. Required. * @property {Array} [anchorText] The position (in pixels) from the center of the cluster icon to * where the text label is to be centered and drawn. The format is <code>[yoffset, xoffset]</code> * where <code>yoffset</code> increases as you go down from center and <code>xoffset</code> * increases to the right of center. The default is <code>[0, 0]</code>. * @property {Array} [anchorIcon] The anchor position (in pixels) of the cluster icon. This is the * spot on the cluster icon that is to be aligned with the cluster position. The format is * <code>[yoffset, xoffset]</code> where <code>yoffset</code> increases as you go down and * <code>xoffset</code> increases to the right of the top-left corner of the icon. The default * anchor position is the center of the cluster icon. * @property {string} [textColor="black"] The color of the label text shown on the * cluster icon. * @property {number} [textSize=11] The size (in pixels) of the label text shown on the * cluster icon. * @property {string} [textDecoration="none"] The value of the CSS <code>text-decoration</code> * property for the label text shown on the cluster icon. * @property {string} [fontWeight="bold"] The value of the CSS <code>font-weight</code> * property for the label text shown on the cluster icon. * @property {string} [fontStyle="normal"] The value of the CSS <code>font-style</code> * property for the label text shown on the cluster icon. * @property {string} [fontFamily="Arial,sans-serif"] The value of the CSS <code>font-family</code> * property for the label text shown on the cluster icon. * @property {string} [backgroundPosition="0 0"] The position of the cluster icon image * within the image defined by <code>url</code>. The format is <code>"xpos ypos"</code> * (the same format as for the CSS <code>background-position</code> property). You must set * this property appropriately when the image defined by <code>url</code> represents a sprite * containing multiple images. Note that the position <i>must</i> be specified in px units. */ /** * @name ClusterIconInfo * @class This class is an object containing general information about a cluster icon. This is * the object that a <code>calculator</code> function returns. * * @property {string} text The text of the label to be shown on the cluster icon. * @property {number} index The index plus 1 of the element in the <code>styles</code> * array to be used to style the cluster icon. * @property {string} title The tooltip to display when the mouse moves over the cluster icon. * If this value is <code>undefined</code> or <code>""</code>, <code>title</code> is set to the * value of the <code>title</code> property passed to the MarkerClusterer. */ /** * A cluster icon. * * @constructor * @extends google.maps.OverlayView * @param {Cluster} cluster The cluster with which the icon is to be associated. * @param {Array} [styles] An array of {@link ClusterIconStyle} defining the cluster icons * to use for various cluster sizes. * @private */ function ClusterIcon(cluster, styles) { cluster.getMarkerClusterer().extend(ClusterIcon, google.maps.OverlayView); this.cluster_ = cluster; this.className_ = cluster.getMarkerClusterer().getClusterClass(); this.styles_ = styles; this.center_ = null; this.div_ = null; this.sums_ = null; this.visible_ = false; this.setMap(cluster.getMap()); // Note: this causes onAdd to be called } /** * Adds the icon to the DOM. */ ClusterIcon.prototype.onAdd = function () { var cClusterIcon = this; var cMouseDownInCluster; var cDraggingMapByCluster; this.div_ = document.createElement("div"); this.div_.className = this.className_; if (this.visible_) { this.show(); } this.getPanes().overlayMouseTarget.appendChild(this.div_); // Fix for Issue 157 this.boundsChangedListener_ = google.maps.event.addListener(this.getMap(), "bounds_changed", function () { cDraggingMapByCluster = cMouseDownInCluster; }); google.maps.event.addDomListener(this.div_, "mousedown", function () { cMouseDownInCluster = true; cDraggingMapByCluster = false; }); google.maps.event.addDomListener(this.div_, "click", function (e) { cMouseDownInCluster = false; if (!cDraggingMapByCluster) { var theBounds; var mz; var mc = cClusterIcon.cluster_.getMarkerClusterer(); /** * This event is fired when a cluster marker is clicked. * @name MarkerClusterer#click * @param {Cluster} c The cluster that was clicked. * @event */ google.maps.event.trigger(mc, "click", cClusterIcon.cluster_); google.maps.event.trigger(mc, "clusterclick", cClusterIcon.cluster_); // deprecated name // The default click handler follows. Disable it by setting // the zoomOnClick property to false. if (mc.getZoomOnClick()) { // Zoom into the cluster. mz = mc.getMaxZoom(); theBounds = cClusterIcon.cluster_.getBounds(); mc.getMap().fitBounds(theBounds); // There is a fix for Issue 170 here: setTimeout(function () { mc.getMap().fitBounds(theBounds); // Don't zoom beyond the max zoom level if (mz !== null && (mc.getMap().getZoom() > mz)) { mc.getMap().setZoom(mz + 1); } }, 100); } // Prevent event propagation to the map: e.cancelBubble = true; if (e.stopPropagation) { e.stopPropagation(); } } }); google.maps.event.addDomListener(this.div_, "mouseover", function () { var mc = cClusterIcon.cluster_.getMarkerClusterer(); /** * This event is fired when the mouse moves over a cluster marker. * @name MarkerClusterer#mouseover * @param {Cluster} c The cluster that the mouse moved over. * @event */ google.maps.event.trigger(mc, "mouseover", cClusterIcon.cluster_); }); google.maps.event.addDomListener(this.div_, "mouseout", function () { var mc = cClusterIcon.cluster_.getMarkerClusterer(); /** * This event is fired when the mouse moves out of a cluster marker. * @name MarkerClusterer#mouseout * @param {Cluster} c The cluster that the mouse moved out of. * @event */ google.maps.event.trigger(mc, "mouseout", cClusterIcon.cluster_); }); }; /** * Removes the icon from the DOM. */ ClusterIcon.prototype.onRemove = function () { if (this.div_ && this.div_.parentNode) { this.hide(); google.maps.event.removeListener(this.boundsChangedListener_); google.maps.event.clearInstanceListeners(this.div_); this.div_.parentNode.removeChild(this.div_); this.div_ = null; } }; /** * Draws the icon. */ ClusterIcon.prototype.draw = function () { if (this.visible_) { var pos = this.getPosFromLatLng_(this.center_); this.div_.style.top = pos.y + "px"; this.div_.style.left = pos.x + "px"; } }; /** * Hides the icon. */ ClusterIcon.prototype.hide = function () { if (this.div_) { this.div_.style.display = "none"; } this.visible_ = false; }; /** * Positions and shows the icon. */ ClusterIcon.prototype.show = function () { if (this.div_) { var img = ""; // NOTE: values must be specified in px units var bp = this.backgroundPosition_.split(" "); var spriteH = parseInt(bp[0].replace(/^\s+|\s+$/g, ""), 10); var spriteV = parseInt(bp[1].replace(/^\s+|\s+$/g, ""), 10); var pos = this.getPosFromLatLng_(this.center_); this.div_.style.cssText = this.createCss(pos); img = "<img src='" + this.url_ + "' style='position: absolute; top: " + spriteV + "px; left: " + spriteH + "px; "; if (!this.cluster_.getMarkerClusterer().enableRetinaIcons_) { img += "clip: rect(" + (-1 * spriteV) + "px, " + ((-1 * spriteH) + this.width_) + "px, " + ((-1 * spriteV) + this.height_) + "px, " + (-1 * spriteH) + "px);"; } img += "'>"; this.div_.innerHTML = img + "<div style='" + "position: absolute;" + "top: " + this.anchorText_[0] + "px;" + "left: " + this.anchorText_[1] + "px;" + "color: " + this.textColor_ + ";" + "font-size: " + this.textSize_ + "px;" + "font-family: " + this.fontFamily_ + ";" + "font-weight: " + this.fontWeight_ + ";" + "font-style: " + this.fontStyle_ + ";" + "text-decoration: " + this.textDecoration_ + ";" + "text-align: center;" + "width: " + this.width_ + "px;" + "line-height:" + this.height_ + "px;" + "'>" + this.sums_.text + "</div>"; if (typeof this.sums_.title === "undefined" || this.sums_.title === "") { this.div_.title = this.cluster_.getMarkerClusterer().getTitle(); } else { this.div_.title = this.sums_.title; } this.div_.style.display = ""; } this.visible_ = true; }; /** * Sets the icon styles to the appropriate element in the styles array. * * @param {ClusterIconInfo} sums The icon label text and styles index. */ ClusterIcon.prototype.useStyle = function (sums) { this.sums_ = sums; var index = Math.max(0, sums.index - 1); index = Math.min(this.styles_.length - 1, index); var style = this.styles_[index]; this.url_ = style.url; this.height_ = style.height; this.width_ = style.width; this.anchorText_ = style.anchorText || [0, 0]; this.anchorIcon_ = style.anchorIcon || [parseInt(this.height_ / 2, 10), parseInt(this.width_ / 2, 10)]; this.textColor_ = style.textColor || "black"; this.textSize_ = style.textSize || 11; this.textDecoration_ = style.textDecoration || "none"; this.fontWeight_ = style.fontWeight || "bold"; this.fontStyle_ = style.fontStyle || "normal"; this.fontFamily_ = style.fontFamily || "Arial,sans-serif"; this.backgroundPosition_ = style.backgroundPosition || "0 0"; }; /** * Sets the position at which to center the icon. * * @param {google.maps.LatLng} center The latlng to set as the center. */ ClusterIcon.prototype.setCenter = function (center) { this.center_ = center; }; /** * Creates the cssText style parameter based on the position of the icon. * * @param {google.maps.Point} pos The position of the icon. * @return {string} The CSS style text. */ ClusterIcon.prototype.createCss = function (pos) { var style = []; style.push("cursor: pointer;"); style.push("position: absolute; top: " + pos.y + "px; left: " + pos.x + "px;"); style.push("width: " + this.width_ + "px; height: " + this.height_ + "px;"); return style.join(""); }; /** * Returns the position at which to place the DIV depending on the latlng. * * @param {google.maps.LatLng} latlng The position in latlng. * @return {google.maps.Point} The position in pixels. */ ClusterIcon.prototype.getPosFromLatLng_ = function (latlng) { var pos = this.getProjection().fromLatLngToDivPixel(latlng); pos.x -= this.anchorIcon_[1]; pos.y -= this.anchorIcon_[0]; pos.x = parseInt(pos.x, 10); pos.y = parseInt(pos.y, 10); return pos; }; /** * Creates a single cluster that manages a group of proximate markers. * Used internally, do not call this constructor directly. * @constructor * @param {MarkerClusterer} mc The <code>MarkerClusterer</code> object with which this * cluster is associated. */ function Cluster(mc) { this.markerClusterer_ = mc; this.map_ = mc.getMap(); this.gridSize_ = mc.getGridSize(); this.minClusterSize_ = mc.getMinimumClusterSize(); this.averageCenter_ = mc.getAverageCenter(); this.markers_ = []; this.center_ = null; this.bounds_ = null; this.clusterIcon_ = new ClusterIcon(this, mc.getStyles()); } /** * Returns the number of markers managed by the cluster. You can call this from * a <code>click</code>, <code>mouseover</code>, or <code>mouseout</code> event handler * for the <code>MarkerClusterer</code> object. * * @return {number} The number of markers in the cluster. */ Cluster.prototype.getSize = function () { return this.markers_.length; }; /** * Returns the array of markers managed by the cluster. You can call this from * a <code>click</code>, <code>mouseover</code>, or <code>mouseout</code> event handler * for the <code>MarkerClusterer</code> object. * * @return {Array} The array of markers in the cluster. */ Cluster.prototype.getMarkers = function () { return this.markers_; }; /** * Returns the center of the cluster. You can call this from * a <code>click</code>, <code>mouseover</code>, or <code>mouseout</code> event handler * for the <code>MarkerClusterer</code> object. * * @return {google.maps.LatLng} The center of the cluster. */ Cluster.prototype.getCenter = function () { return this.center_; }; /** * Returns the map with which the cluster is associated. * * @return {google.maps.Map} The map. * @ignore */ Cluster.prototype.getMap = function () { return this.map_; }; /** * Returns the <code>MarkerClusterer</code> object with which the cluster is associated. * * @return {MarkerClusterer} The associated marker clusterer. * @ignore */ Cluster.prototype.getMarkerClusterer = function () { return this.markerClusterer_; }; /** * Returns the bounds of the cluster. * * @return {google.maps.LatLngBounds} the cluster bounds. * @ignore */ Cluster.prototype.getBounds = function () { var i; var bounds = new google.maps.LatLngBounds(this.center_, this.center_); var markers = this.getMarkers(); for (i = 0; i < markers.length; i++) { bounds.extend(markers[i].getPosition()); } return bounds; }; /** * Removes the cluster from the map. * * @ignore */ Cluster.prototype.remove = function () { this.clusterIcon_.setMap(null); this.markers_ = []; delete this.markers_; }; /** * Adds a marker to the cluster. * * @param {google.maps.Marker} marker The marker to be added. * @return {boolean} True if the marker was added. * @ignore */ Cluster.prototype.addMarker = function (marker) { var i; var mCount; var mz; if (this.isMarkerAlreadyAdded_(marker)) { return false; } if (!this.center_) { this.center_ = marker.getPosition(); this.calculateBounds_(); } else { if (this.averageCenter_) { var l = this.markers_.length + 1; var lat = (this.center_.lat() * (l - 1) + marker.getPosition().lat()) / l; var lng = (this.center_.lng() * (l - 1) + marker.getPosition().lng()) / l; this.center_ = new google.maps.LatLng(lat, lng); this.calculateBounds_(); } } marker.isAdded = true; this.markers_.push(marker); mCount = this.markers_.length; mz = this.markerClusterer_.getMaxZoom(); if (mz !== null && this.map_.getZoom() > mz) { // Zoomed in past max zoom, so show the marker. if (marker.getMap() !== this.map_) { marker.setMap(this.map_); } } else if (mCount < this.minClusterSize_) { // Min cluster size not reached so show the marker. if (marker.getMap() !== this.map_) { marker.setMap(this.map_); } } else if (mCount === this.minClusterSize_) { // Hide the markers that were showing. for (i = 0; i < mCount; i++) { this.markers_[i].setMap(null); } } else { marker.setMap(null); } this.updateIcon_(); return true; }; /** * Determines if a marker lies within the cluster's bounds. * * @param {google.maps.Marker} marker The marker to check. * @return {boolean} True if the marker lies in the bounds. * @ignore */ Cluster.prototype.isMarkerInClusterBounds = function (marker) { return this.bounds_.contains(marker.getPosition()); }; /** * Calculates the extended bounds of the cluster with the grid. */ Cluster.prototype.calculateBounds_ = function () { var bounds = new google.maps.LatLngBounds(this.center_, this.center_); this.bounds_ = this.markerClusterer_.getExtendedBounds(bounds); }; /** * Updates the cluster icon. */ Cluster.prototype.updateIcon_ = function () { var mCount = this.markers_.length; var mz = this.markerClusterer_.getMaxZoom(); if (mz !== null && this.map_.getZoom() > mz) { this.clusterIcon_.hide(); return; } if (mCount < this.minClusterSize_) { // Min cluster size not yet reached. this.clusterIcon_.hide(); return; } var numStyles = this.markerClusterer_.getStyles().length; var sums = this.markerClusterer_.getCalculator()(this.markers_, numStyles); this.clusterIcon_.setCenter(this.center_); this.clusterIcon_.useStyle(sums); this.clusterIcon_.show(); }; /** * Determines if a marker has already been added to the cluster. * * @param {google.maps.Marker} marker The marker to check. * @return {boolean} True if the marker has already been added. */ Cluster.prototype.isMarkerAlreadyAdded_ = function (marker) { var i; if (this.markers_.indexOf) { return this.markers_.indexOf(marker) !== -1; } else { for (i = 0; i < this.markers_.length; i++) { if (marker === this.markers_[i]) { return true; } } } return false; }; /** * @name MarkerClustererOptions * @class This class represents the optional parameter passed to * the {@link MarkerClusterer} constructor. * @property {number} [gridSize=60] The grid size of a cluster in pixels. The grid is a square. * @property {number} [maxZoom=null] The maximum zoom level at which clustering is enabled or * <code>null</code> if clustering is to be enabled at all zoom levels. * @property {boolean} [zoomOnClick=true] Whether to zoom the map when a cluster marker is * clicked. You may want to set this to <code>false</code> if you have installed a handler * for the <code>click</code> event and it deals with zooming on its own. * @property {boolean} [averageCenter=false] Whether the position of a cluster marker should be * the average position of all markers in the cluster. If set to <code>false</code>, the * cluster marker is positioned at the location of the first marker added to the cluster. * @property {number} [minimumClusterSize=2] The minimum number of markers needed in a cluster * before the markers are hidden and a cluster marker appears. * @property {boolean} [ignoreHidden=false] Whether to ignore hidden markers in clusters. You * may want to set this to <code>true</code> to ensure that hidden markers are not included * in the marker count that appears on a cluster marker (this count is the value of the * <code>text</code> property of the result returned by the default <code>calculator</code>). * If set to <code>true</code> and you change the visibility of a marker being clustered, be * sure to also call <code>MarkerClusterer.repaint()</code>. * @property {string} [title=""] The tooltip to display when the mouse moves over a cluster * marker. (Alternatively, you can use a custom <code>calculator</code> function to specify a * different tooltip for each cluster marker.) * @property {function} [calculator=MarkerClusterer.CALCULATOR] The function used to determine * the text to be displayed on a cluster marker and the index indicating which style to use * for the cluster marker. The input parameters for the function are (1) the array of markers * represented by a cluster marker and (2) the number of cluster icon styles. It returns a * {@link ClusterIconInfo} object. The default <code>calculator</code> returns a * <code>text</code> property which is the number of markers in the cluster and an * <code>index</code> property which is one higher than the lowest integer such that * <code>10^i</code> exceeds the number of markers in the cluster, or the size of the styles * array, whichever is less. The <code>styles</code> array element used has an index of * <code>index</code> minus 1. For example, the default <code>calculator</code> returns a * <code>text</code> value of <code>"125"</code> and an <code>index</code> of <code>3</code> * for a cluster icon representing 125 markers so the element used in the <code>styles</code> * array is <code>2</code>. A <code>calculator</code> may also return a <code>title</code> * property that contains the text of the tooltip to be used for the cluster marker. If * <code>title</code> is not defined, the tooltip is set to the value of the <code>title</code> * property for the MarkerClusterer. * @property {string} [clusterClass="cluster"] The name of the CSS class defining general styles * for the cluster markers. Use this class to define CSS styles that are not set up by the code * that processes the <code>styles</code> array. * @property {Array} [styles] An array of {@link ClusterIconStyle} elements defining the styles * of the cluster markers to be used. The element to be used to style a given cluster marker * is determined by the function defined by the <code>calculator</code> property. * The default is an array of {@link ClusterIconStyle} elements whose properties are derived * from the values for <code>imagePath</code>, <code>imageExtension</code>, and * <code>imageSizes</code>. * @property {boolean} [enableRetinaIcons=false] Whether to allow the use of cluster icons that * have sizes that are some multiple (typically double) of their actual display size. Icons such * as these look better when viewed on high-resolution monitors such as Apple's Retina displays. * Note: if this property is <code>true</code>, sprites cannot be used as cluster icons. * @property {number} [batchSize=MarkerClusterer.BATCH_SIZE] Set this property to the * number of markers to be processed in a single batch when using a browser other than * Internet Explorer (for Internet Explorer, use the batchSizeIE property instead). * @property {number} [batchSizeIE=MarkerClusterer.BATCH_SIZE_IE] When Internet Explorer is * being used, markers are processed in several batches with a small delay inserted between * each batch in an attempt to avoid Javascript timeout errors. Set this property to the * number of markers to be processed in a single batch; select as high a number as you can * without causing a timeout error in the browser. This number might need to be as low as 100 * if 15,000 markers are being managed, for example. * @property {string} [imagePath=MarkerClusterer.IMAGE_PATH] * The full URL of the root name of the group of image files to use for cluster icons. * The complete file name is of the form <code>imagePath</code>n.<code>imageExtension</code> * where n is the image file number (1, 2, etc.). * @property {string} [imageExtension=MarkerClusterer.IMAGE_EXTENSION] * The extension name for the cluster icon image files (e.g., <code>"png"</code> or * <code>"jpg"</code>). * @property {Array} [imageSizes=MarkerClusterer.IMAGE_SIZES] * An array of numbers containing the widths of the group of * <code>imagePath</code>n.<code>imageExtension</code> image files. * (The images are assumed to be square.) */ /** * Creates a MarkerClusterer object with the options specified in {@link MarkerClustererOptions}. * @constructor * @extends google.maps.OverlayView * @param {google.maps.Map} map The Google map to attach to. * @param {Array.<google.maps.Marker>} [opt_markers] The markers to be added to the cluster. * @param {MarkerClustererOptions} [opt_options] The optional parameters. */ function MarkerClusterer(map, opt_markers, opt_options) { // MarkerClusterer implements google.maps.OverlayView interface. We use the // extend function to extend MarkerClusterer with google.maps.OverlayView // because it might not always be available when the code is defined so we // look for it at the last possible moment. If it doesn't exist now then // there is no point going ahead :) this.extend(MarkerClusterer, google.maps.OverlayView); opt_markers = opt_markers || []; opt_options = opt_options || {}; this.markers_ = []; this.clusters_ = []; this.listeners_ = []; this.activeMap_ = null; this.ready_ = false; this.gridSize_ = opt_options.gridSize || 60; this.minClusterSize_ = opt_options.minimumClusterSize || 2; this.maxZoom_ = opt_options.maxZoom || null; this.styles_ = opt_options.styles || []; this.title_ = opt_options.title || ""; this.zoomOnClick_ = true; if (opt_options.zoomOnClick !== undefined) { this.zoomOnClick_ = opt_options.zoomOnClick; } this.averageCenter_ = false; if (opt_options.averageCenter !== undefined) { this.averageCenter_ = opt_options.averageCenter; } this.ignoreHidden_ = false; if (opt_options.ignoreHidden !== undefined) { this.ignoreHidden_ = opt_options.ignoreHidden; } this.enableRetinaIcons_ = false; if (opt_options.enableRetinaIcons !== undefined) { this.enableRetinaIcons_ = opt_options.enableRetinaIcons; } this.imagePath_ = opt_options.imagePath || MarkerClusterer.IMAGE_PATH; this.imageExtension_ = opt_options.imageExtension || MarkerClusterer.IMAGE_EXTENSION; this.imageSizes_ = opt_options.imageSizes || MarkerClusterer.IMAGE_SIZES; this.calculator_ = opt_options.calculator || MarkerClusterer.CALCULATOR; this.batchSize_ = opt_options.batchSize || MarkerClusterer.BATCH_SIZE; this.batchSizeIE_ = opt_options.batchSizeIE || MarkerClusterer.BATCH_SIZE_IE; this.clusterClass_ = opt_options.clusterClass || "cluster"; if (navigator.userAgent.toLowerCase().indexOf("msie") !== -1) { // Try to avoid IE timeout when processing a huge number of markers: this.batchSize_ = this.batchSizeIE_; } this.setupStyles_(); this.addMarkers(opt_markers, true); this.setMap(map); // Note: this causes onAdd to be called } /** * Implementation of the onAdd interface method. * @ignore */ MarkerClusterer.prototype.onAdd = function () { var cMarkerClusterer = this; this.activeMap_ = this.getMap(); this.ready_ = true; this.repaint(); // Add the map event listeners this.listeners_ = [ google.maps.event.addListener(this.getMap(), "zoom_changed", function () { cMarkerClusterer.resetViewport_(false); // Workaround for this Google bug: when map is at level 0 and "-" of // zoom slider is clicked, a "zoom_changed" event is fired even though // the map doesn't zoom out any further. In this situation, no "idle" // event is triggered so the cluster markers that have been removed // do not get redrawn. Same goes for a zoom in at maxZoom. if (this.getZoom() === (this.get("minZoom") || 0) || this.getZoom() === this.get("maxZoom")) { google.maps.event.trigger(this, "idle"); } }), google.maps.event.addListener(this.getMap(), "idle", function () { cMarkerClusterer.redraw_(); }) ]; }; /** * Implementation of the onRemove interface method. * Removes map event listeners and all cluster icons from the DOM. * All managed markers are also put back on the map. * @ignore */ MarkerClusterer.prototype.onRemove = function () { var i; // Put all the managed markers back on the map: for (i = 0; i < this.markers_.length; i++) { if (this.markers_[i].getMap() !== this.activeMap_) { this.markers_[i].setMap(this.activeMap_); } } // Remove all clusters: for (i = 0; i < this.clusters_.length; i++) { this.clusters_[i].remove(); } this.clusters_ = []; // Remove map event listeners: for (i = 0; i < this.listeners_.length; i++) { google.maps.event.removeListener(this.listeners_[i]); } this.listeners_ = []; this.activeMap_ = null; this.ready_ = false; }; /** * Implementation of the draw interface method. * @ignore */ MarkerClusterer.prototype.draw = function () {}; /** * Sets up the styles object. */ MarkerClusterer.prototype.setupStyles_ = function () { var i, size; if (this.styles_.length > 0) { return; } for (i = 0; i < this.imageSizes_.length; i++) { size = this.imageSizes_[i]; this.styles_.push({ url: this.imagePath_ + (i + 1) + "." + this.imageExtension_, height: size, width: size }); } }; /** * Fits the map to the bounds of the markers managed by the clusterer. */ MarkerClusterer.prototype.fitMapToMarkers = function () { var i; var markers = this.getMarkers(); var bounds = new google.maps.LatLngBounds(); for (i = 0; i < markers.length; i++) { bounds.extend(markers[i].getPosition()); } this.getMap().fitBounds(bounds); }; /** * Returns the value of the <code>gridSize</code> property. * * @return {number} The grid size. */ MarkerClusterer.prototype.getGridSize = function () { return this.gridSize_; }; /** * Sets the value of the <code>gridSize</code> property. * * @param {number} gridSize The grid size. */ MarkerClusterer.prototype.setGridSize = function (gridSize) { this.gridSize_ = gridSize; }; /** * Returns the value of the <code>minimumClusterSize</code> property. * * @return {number} The minimum cluster size. */ MarkerClusterer.prototype.getMinimumClusterSize = function () { return this.minClusterSize_; }; /** * Sets the value of the <code>minimumClusterSize</code> property. * * @param {number} minimumClusterSize The minimum cluster size. */ MarkerClusterer.prototype.setMinimumClusterSize = function (minimumClusterSize) { this.minClusterSize_ = minimumClusterSize; }; /** * Returns the value of the <code>maxZoom</code> property. * * @return {number} The maximum zoom level. */ MarkerClusterer.prototype.getMaxZoom = function () { return this.maxZoom_; }; /** * Sets the value of the <code>maxZoom</code> property. * * @param {number} maxZoom The maximum zoom level. */ MarkerClusterer.prototype.setMaxZoom = function (maxZoom) { this.maxZoom_ = maxZoom; }; /** * Returns the value of the <code>styles</code> property. * * @return {Array} The array of styles defining the cluster markers to be used. */ MarkerClusterer.prototype.getStyles = function () { return this.styles_; }; /** * Sets the value of the <code>styles</code> property. * * @param {Array.<ClusterIconStyle>} styles The array of styles to use. */ MarkerClusterer.prototype.setStyles = function (styles) { this.styles_ = styles; }; /** * Returns the value of the <code>title</code> property. * * @return {string} The content of the title text. */ MarkerClusterer.prototype.getTitle = function () { return this.title_; }; /** * Sets the value of the <code>title</code> property. * * @param {string} title The value of the title property. */ MarkerClusterer.prototype.setTitle = function (title) { this.title_ = title; }; /** * Returns the value of the <code>zoomOnClick</code> property. * * @return {boolean} True if zoomOnClick property is set. */ MarkerClusterer.prototype.getZoomOnClick = function () { return this.zoomOnClick_; }; /** * Sets the value of the <code>zoomOnClick</code> property. * * @param {boolean} zoomOnClick The value of the zoomOnClick property. */ MarkerClusterer.prototype.setZoomOnClick = function (zoomOnClick) { this.zoomOnClick_ = zoomOnClick; }; /** * Returns the value of the <code>averageCenter</code> property. * * @return {boolean} True if averageCenter property is set. */ MarkerClusterer.prototype.getAverageCenter = function () { return this.averageCenter_; }; /** * Sets the value of the <code>averageCenter</code> property. * * @param {boolean} averageCenter The value of the averageCenter property. */ MarkerClusterer.prototype.setAverageCenter = function (averageCenter) { this.averageCenter_ = averageCenter; }; /** * Returns the value of the <code>ignoreHidden</code> property. * * @return {boolean} True if ignoreHidden property is set. */ MarkerClusterer.prototype.getIgnoreHidden = function () { return this.ignoreHidden_; }; /** * Sets the value of the <code>ignoreHidden</code> property. * * @param {boolean} ignoreHidden The value of the ignoreHidden property. */ MarkerClusterer.prototype.setIgnoreHidden = function (ignoreHidden) { this.ignoreHidden_ = ignoreHidden; }; /** * Returns the value of the <code>enableRetinaIcons</code> property. * * @return {boolean} True if enableRetinaIcons property is set. */ MarkerClusterer.prototype.getEnableRetinaIcons = function () { return this.enableRetinaIcons_; }; /** * Sets the value of the <code>enableRetinaIcons</code> property. * * @param {boolean} enableRetinaIcons The value of the enableRetinaIcons property. */ MarkerClusterer.prototype.setEnableRetinaIcons = function (enableRetinaIcons) { this.enableRetinaIcons_ = enableRetinaIcons; }; /** * Returns the value of the <code>imageExtension</code> property. * * @return {string} The value of the imageExtension property. */ MarkerClusterer.prototype.getImageExtension = function () { return this.imageExtension_; }; /** * Sets the value of the <code>imageExtension</code> property. * * @param {string} imageExtension The value of the imageExtension property. */ MarkerClusterer.prototype.setImageExtension = function (imageExtension) { this.imageExtension_ = imageExtension; }; /** * Returns the value of the <code>imagePath</code> property. * * @return {string} The value of the imagePath property. */ MarkerClusterer.prototype.getImagePath = function () { return this.imagePath_; }; /** * Sets the value of the <code>imagePath</code> property. * * @param {string} imagePath The value of the imagePath property. */ MarkerClusterer.prototype.setImagePath = function (imagePath) { this.imagePath_ = imagePath; }; /** * Returns the value of the <code>imageSizes</code> property. * * @return {Array} The value of the imageSizes property. */ MarkerClusterer.prototype.getImageSizes = function () { return this.imageSizes_; }; /** * Sets the value of the <code>imageSizes</code> property. * * @param {Array} imageSizes The value of the imageSizes property. */ MarkerClusterer.prototype.setImageSizes = function (imageSizes) { this.imageSizes_ = imageSizes; }; /** * Returns the value of the <code>calculator</code> property. * * @return {function} the value of the calculator property. */ MarkerClusterer.prototype.getCalculator = function () { return this.calculator_; }; /** * Sets the value of the <code>calculator</code> property. * * @param {function(Array.<google.maps.Marker>, number)} calculator The value * of the calculator property. */ MarkerClusterer.prototype.setCalculator = function (calculator) { this.calculator_ = calculator; }; /** * Returns the value of the <code>batchSizeIE</code> property. * * @return {number} the value of the batchSizeIE property. */ MarkerClusterer.prototype.getBatchSizeIE = function () { return this.batchSizeIE_; }; /** * Sets the value of the <code>batchSizeIE</code> property. * * @param {number} batchSizeIE The value of the batchSizeIE property. */ MarkerClusterer.prototype.setBatchSizeIE = function (batchSizeIE) { this.batchSizeIE_ = batchSizeIE; }; /** * Returns the value of the <code>clusterClass</code> property. * * @return {string} the value of the clusterClass property. */ MarkerClusterer.prototype.getClusterClass = function () { return this.clusterClass_; }; /** * Sets the value of the <code>clusterClass</code> property. * * @param {string} clusterClass The value of the clusterClass property. */ MarkerClusterer.prototype.setClusterClass = function (clusterClass) { this.clusterClass_ = clusterClass; }; /** * Returns the array of markers managed by the clusterer. * * @return {Array} The array of markers managed by the clusterer. */ MarkerClusterer.prototype.getMarkers = function () { return this.markers_; }; /** * Returns the number of markers managed by the clusterer. * * @return {number} The number of markers. */ MarkerClusterer.prototype.getTotalMarkers = function () { return this.markers_.length; }; /** * Returns the current array of clusters formed by the clusterer. * * @return {Array} The array of clusters formed by the clusterer. */ MarkerClusterer.prototype.getClusters = function () { return this.clusters_; }; /** * Returns the number of clusters formed by the clusterer. * * @return {number} The number of clusters formed by the clusterer. */ MarkerClusterer.prototype.getTotalClusters = function () { return this.clusters_.length; }; /** * Adds a marker to the clusterer. The clusters are redrawn unless * <code>opt_nodraw</code> is set to <code>true</code>. * * @param {google.maps.Marker} marker The marker to add. * @param {boolean} [opt_nodraw] Set to <code>true</code> to prevent redrawing. */ MarkerClusterer.prototype.addMarker = function (marker, opt_nodraw) { this.pushMarkerTo_(marker); if (!opt_nodraw) { this.redraw_(); } }; /** * Adds an array of markers to the clusterer. The clusters are redrawn unless * <code>opt_nodraw</code> is set to <code>true</code>. * * @param {Array.<google.maps.Marker>} markers The markers to add. * @param {boolean} [opt_nodraw] Set to <code>true</code> to prevent redrawing. */ MarkerClusterer.prototype.addMarkers = function (markers, opt_nodraw) { var key; for (key in markers) { if (markers.hasOwnProperty(key)) { this.pushMarkerTo_(markers[key]); } } if (!opt_nodraw) { this.redraw_(); } }; /** * Pushes a marker to the clusterer. * * @param {google.maps.Marker} marker The marker to add. */ MarkerClusterer.prototype.pushMarkerTo_ = function (marker) { // If the marker is draggable add a listener so we can update the clusters on the dragend: if (marker.getDraggable()) { var cMarkerClusterer = this; google.maps.event.addListener(marker, "dragend", function () { if (cMarkerClusterer.ready_) { this.isAdded = false; cMarkerClusterer.repaint(); } }); } marker.isAdded = false; this.markers_.push(marker); }; /** * Removes a marker from the cluster. The clusters are redrawn unless * <code>opt_nodraw</code> is set to <code>true</code>. Returns <code>true</code> if the * marker was removed from the clusterer. * * @param {google.maps.Marker} marker The marker to remove. * @param {boolean} [opt_nodraw] Set to <code>true</code> to prevent redrawing. * @return {boolean} True if the marker was removed from the clusterer. */ MarkerClusterer.prototype.removeMarker = function (marker, opt_nodraw) { var removed = this.removeMarker_(marker); if (!opt_nodraw && removed) { this.repaint(); } return removed; }; /** * Removes an array of markers from the cluster. The clusters are redrawn unless * <code>opt_nodraw</code> is set to <code>true</code>. Returns <code>true</code> if markers * were removed from the clusterer. * * @param {Array.<google.maps.Marker>} markers The markers to remove. * @param {boolean} [opt_nodraw] Set to <code>true</code> to prevent redrawing. * @return {boolean} True if markers were removed from the clusterer. */ MarkerClusterer.prototype.removeMarkers = function (markers, opt_nodraw) { var i, r; var removed = false; for (i = 0; i < markers.length; i++) { r = this.removeMarker_(markers[i]); removed = removed || r; } if (!opt_nodraw && removed) { this.repaint(); } return removed; }; /** * Removes a marker and returns true if removed, false if not. * * @param {google.maps.Marker} marker The marker to remove * @return {boolean} Whether the marker was removed or not */ MarkerClusterer.prototype.removeMarker_ = function (marker) { var i; var index = -1; if (this.markers_.indexOf) { index = this.markers_.indexOf(marker); } else { for (i = 0; i < this.markers_.length; i++) { if (marker === this.markers_[i]) { index = i; break; } } } if (index === -1) { // Marker is not in our list of markers, so do nothing: return false; } marker.setMap(null); this.markers_.splice(index, 1); // Remove the marker from the list of managed markers return true; }; /** * Removes all clusters and markers from the map and also removes all markers * managed by the clusterer. */ MarkerClusterer.prototype.clearMarkers = function () { this.resetViewport_(true); this.markers_ = []; }; /** * Recalculates and redraws all the marker clusters from scratch. * Call this after changing any properties. */ MarkerClusterer.prototype.repaint = function () { var oldClusters = this.clusters_.slice(); this.clusters_ = []; this.resetViewport_(false); this.redraw_(); // Remove the old clusters. // Do it in a timeout to prevent blinking effect. setTimeout(function () { var i; for (i = 0; i < oldClusters.length; i++) { oldClusters[i].remove(); } }, 0); }; /** * Returns the current bounds extended by the grid size. * * @param {google.maps.LatLngBounds} bounds The bounds to extend. * @return {google.maps.LatLngBounds} The extended bounds. * @ignore */ MarkerClusterer.prototype.getExtendedBounds = function (bounds) { var projection = this.getProjection(); // Turn the bounds into latlng. var tr = new google.maps.LatLng(bounds.getNorthEast().lat(), bounds.getNorthEast().lng()); var bl = new google.maps.LatLng(bounds.getSouthWest().lat(), bounds.getSouthWest().lng()); // Convert the points to pixels and the extend out by the grid size. var trPix = projection.fromLatLngToDivPixel(tr); trPix.x += this.gridSize_; trPix.y -= this.gridSize_; var blPix = projection.fromLatLngToDivPixel(bl); blPix.x -= this.gridSize_; blPix.y += this.gridSize_; // Convert the pixel points back to LatLng var ne = projection.fromDivPixelToLatLng(trPix); var sw = projection.fromDivPixelToLatLng(blPix); // Extend the bounds to contain the new bounds. bounds.extend(ne); bounds.extend(sw); return bounds; }; /** * Redraws all the clusters. */ MarkerClusterer.prototype.redraw_ = function () { this.createClusters_(0); }; /** * Removes all clusters from the map. The markers are also removed from the map * if <code>opt_hide</code> is set to <code>true</code>. * * @param {boolean} [opt_hide] Set to <code>true</code> to also remove the markers * from the map. */ MarkerClusterer.prototype.resetViewport_ = function (opt_hide) { var i, marker; // Remove all the clusters for (i = 0; i < this.clusters_.length; i++) { this.clusters_[i].remove(); } this.clusters_ = []; // Reset the markers to not be added and to be removed from the map. for (i = 0; i < this.markers_.length; i++) { marker = this.markers_[i]; marker.isAdded = false; if (opt_hide) { marker.setMap(null); } } }; /** * Calculates the distance between two latlng locations in km. * * @param {google.maps.LatLng} p1 The first lat lng point. * @param {google.maps.LatLng} p2 The second lat lng point. * @return {number} The distance between the two points in km. * @see http://www.movable-type.co.uk/scripts/latlong.html */ MarkerClusterer.prototype.distanceBetweenPoints_ = function (p1, p2) { var R = 6371; // Radius of the Earth in km var dLat = (p2.lat() - p1.lat()) * Math.PI / 180; var dLon = (p2.lng() - p1.lng()) * Math.PI / 180; var a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.cos(p1.lat() * Math.PI / 180) * Math.cos(p2.lat() * Math.PI / 180) * Math.sin(dLon / 2) * Math.sin(dLon / 2); var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a)); var d = R * c; return d; }; /** * Determines if a marker is contained in a bounds. * * @param {google.maps.Marker} marker The marker to check. * @param {google.maps.LatLngBounds} bounds The bounds to check against. * @return {boolean} True if the marker is in the bounds. */ MarkerClusterer.prototype.isMarkerInBounds_ = function (marker, bounds) { return bounds.contains(marker.getPosition()); }; /** * Adds a marker to a cluster, or creates a new cluster. * * @param {google.maps.Marker} marker The marker to add. */ MarkerClusterer.prototype.addToClosestCluster_ = function (marker) { var i, d, cluster, center; var distance = 40000; // Some large number var clusterToAddTo = null; for (i = 0; i < this.clusters_.length; i++) { cluster = this.clusters_[i]; center = cluster.getCenter(); if (center) { d = this.distanceBetweenPoints_(center, marker.getPosition()); if (d < distance) { distance = d; clusterToAddTo = cluster; } } } if (clusterToAddTo && clusterToAddTo.isMarkerInClusterBounds(marker)) { clusterToAddTo.addMarker(marker); } else { cluster = new Cluster(this); cluster.addMarker(marker); this.clusters_.push(cluster); } }; /** * Creates the clusters. This is done in batches to avoid timeout errors * in some browsers when there is a huge number of markers. * * @param {number} iFirst The index of the first marker in the batch of * markers to be added to clusters. */ MarkerClusterer.prototype.createClusters_ = function (iFirst) { var i, marker; var mapBounds; var cMarkerClusterer = this; if (!this.ready_) { return; } // Cancel previous batch processing if we're working on the first batch: if (iFirst === 0) { /** * This event is fired when the <code>MarkerClusterer</code> begins * clustering markers. * @name MarkerClusterer#clusteringbegin * @param {MarkerClusterer} mc The MarkerClusterer whose markers are being clustered. * @event */ google.maps.event.trigger(this, "clusteringbegin", this); if (typeof this.timerRefStatic !== "undefined") { clearTimeout(this.timerRefStatic); delete this.timerRefStatic; } } // Get our current map view bounds. // Create a new bounds object so we don't affect the map. // // See Comments 9 & 11 on Issue 3651 relating to this workaround for a Google Maps bug: if (this.getMap().getZoom() > 3) { mapBounds = new google.maps.LatLngBounds(this.getMap().getBounds().getSouthWest(), this.getMap().getBounds().getNorthEast()); } else { mapBounds = new google.maps.LatLngBounds(new google.maps.LatLng(85.02070771743472, -178.48388434375), new google.maps.LatLng(-85.08136444384544, 178.00048865625)); } var bounds = this.getExtendedBounds(mapBounds); var iLast = Math.min(iFirst + this.batchSize_, this.markers_.length); for (i = iFirst; i < iLast; i++) { marker = this.markers_[i]; if (!marker.isAdded && this.isMarkerInBounds_(marker, bounds)) { if (!this.ignoreHidden_ || (this.ignoreHidden_ && marker.getVisible())) { this.addToClosestCluster_(marker); } } } if (iLast < this.markers_.length) { this.timerRefStatic = setTimeout(function () { cMarkerClusterer.createClusters_(iLast); }, 0); } else { delete this.timerRefStatic; /** * This event is fired when the <code>MarkerClusterer</code> stops * clustering markers. * @name MarkerClusterer#clusteringend * @param {MarkerClusterer} mc The MarkerClusterer whose markers are being clustered. * @event */ google.maps.event.trigger(this, "clusteringend", this); } }; /** * Extends an object's prototype by another's. * * @param {Object} obj1 The object to be extended. * @param {Object} obj2 The object to extend with. * @return {Object} The new extended object. * @ignore */ MarkerClusterer.prototype.extend = function (obj1, obj2) { return (function (object) { var property; for (property in object.prototype) { this.prototype[property] = object.prototype[property]; } return this; }).apply(obj1, [obj2]); }; /** * The default function for determining the label text and style * for a cluster icon. * * @param {Array.<google.maps.Marker>} markers The array of markers represented by the cluster. * @param {number} numStyles The number of marker styles available. * @return {ClusterIconInfo} The information resource for the cluster. * @constant * @ignore */ MarkerClusterer.CALCULATOR = function (markers, numStyles) { var index = 0; var title = ""; var count = markers.length.toString(); var dv = count; while (dv !== 0) { dv = parseInt(dv / 10, 10); index++; } index = Math.min(index, numStyles); return { text: count, index: index, title: title }; }; /** * The number of markers to process in one batch. * * @type {number} * @constant */ MarkerClusterer.BATCH_SIZE = 2000; /** * The number of markers to process in one batch (IE only). * * @type {number} * @constant */ MarkerClusterer.BATCH_SIZE_IE = 500; /** * The default root name for the marker cluster images. * * @type {string} * @constant */ MarkerClusterer.IMAGE_PATH = "http://google-maps-utility-library-v3.googlecode.com/svn/trunk/markerclustererplus/images/m"; /** * The default extension name for the marker cluster images. * * @type {string} * @constant */ MarkerClusterer.IMAGE_EXTENSION = "png"; /** * The default array of sizes for the marker cluster images. * * @type {Array.<number>} * @constant */ MarkerClusterer.IMAGE_SIZES = [53, 56, 66, 78, 90]; module.exports = MarkerClusterer /***/ }, /* 58 */ /***/ function(module, exports) { module.exports = __WEBPACK_EXTERNAL_MODULE_58__; /***/ } /******/ ]) }); ;
// XXX Hack to prevent hextorstr function used by JWS send a string instead of // a Word Array. On this way, no string decoding needs to take place and Crypto // takes care of everything. // Note that it should not affect the other algorithms as hextorstr is exclusively // used on Hmac family (that invokes CryptoJS library). window.hextorstr = function (c) { return window.CryptoJS.enc.Hex.parse(c); }; //this is used to parse base64 function url_base64_decode(str) { var output = str.replace(/-/g, '+').replace(/_/g, '/'); switch (output.length % 4) { case 0: break; case 2: output += '=='; break; case 3: output += '='; break; default: throw 'Illegal base64url string!'; } var result = window.atob(output); //polifyll https://github.com/davidchambers/Base64.js try{ return decodeURIComponent(escape(result)); } catch (err) { return result; } } window.decode = function (base64json) { var json = null, error = null; try { json = url_base64_decode(base64json); json = JSON.stringify(JSON.parse(json), undefined, 2); } catch (e) { error = e; } return {result: json, error: error}; }; window.sign = function (algorithm, header, payload, key, isSecretBase64Encoded) { var value = '', error = null, headerAsJSON, payloadAsJSON; try { headerAsJSON = JSON.stringify(JSON.parse(header)); } catch (e) { error = {result: null, error: {cause: e, who: ['header']}}; } try { payloadAsJSON = JSON.stringify(JSON.parse(payload)); } catch (e) { if (error) { error.error.who.push('payload'); } else { error = {result: null, error: {cause: e, who: ['payload']}}; } } if (error) { return error; } if(algorithm === 'HS256'){ if (isSecretBase64Encoded) { try { key = window.b64utob64(key); key = window.CryptoJS.enc.Base64.parse(key).toString(); } catch (e) { return {result: '', error: e}; } } else { key = window.CryptoJS.enc.Latin1.parse(key).toString(); } } try { value = KJUR.jws.JWS.sign(algorithm, headerAsJSON, payloadAsJSON, key); } catch (e) { error = e; } return {result: value, error: error}; }; window.isValidBase64String = function (s) { try { s = window.b64utob64(s); window.CryptoJS.enc.Base64.parse(s).toString(); return true; } catch (e) { return false; } }; window.verify = function (algorithm, value, key, isSecretBase64Encoded) { var result = '', error = null; if (algorithm === 'HS256'){ if (isSecretBase64Encoded) { try { key = window.b64utob64(key); key = window.CryptoJS.enc.Base64.parse(key).toString(); } catch (e) { return {result: '', error: e}; } } else { key = window.CryptoJS.enc.Latin1.parse(key).toString(); } } try { result = KJUR.jws.JWS.verify(value, key); } catch (e) { error = e; } return {result: result, error: error}; };
/* Copyright (c) 2003-2013, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ CKEDITOR.plugins.setLang( 'stylescombo', 'ja', { label: 'スタイル', panelTitle: 'スタイル', panelTitle1: 'ブロックスタイル', panelTitle2: 'インラインスタイル', panelTitle3: 'オブジェクトスタイル' });
import React, { cloneElement } from 'react'; import classNames from 'classnames'; import ValidComponentChildren from './utils/ValidComponentChildren'; import createChainedFunction from './utils/createChainedFunction'; import BootstrapMixin from './BootstrapMixin'; import SafeAnchor from './SafeAnchor'; const SubNav = React.createClass({ mixins: [BootstrapMixin], propTypes: { onSelect: React.PropTypes.func, active: React.PropTypes.bool, activeHref: React.PropTypes.string, activeKey: React.PropTypes.any, disabled: React.PropTypes.bool, eventKey: React.PropTypes.any, href: React.PropTypes.string, title: React.PropTypes.string, text: React.PropTypes.node, target: React.PropTypes.string }, getDefaultProps() { return { bsClass: 'nav' }; }, handleClick(e) { if (this.props.onSelect) { e.preventDefault(); if (!this.props.disabled) { this.props.onSelect(this.props.eventKey, this.props.href, this.props.target); } } }, isActive() { return this.isChildActive(this); }, isChildActive(child) { if (child.props.active) { return true; } if (this.props.activeKey != null && this.props.activeKey === child.props.eventKey) { return true; } if (this.props.activeHref != null && this.props.activeHref === child.props.href) { return true; } if (child.props.children) { let isActive = false; ValidComponentChildren.forEach( child.props.children, function (grandchild) { if (this.isChildActive(grandchild)) { isActive = true; } }, this ); return isActive; } return false; }, getChildActiveProp(child) { if (child.props.active) { return true; } if (this.props.activeKey != null) { if (child.props.eventKey === this.props.activeKey) { return true; } } if (this.props.activeHref != null) { if (child.props.href === this.props.activeHref) { return true; } } return child.props.active; }, render() { let classes = { 'active': this.isActive(), 'disabled': this.props.disabled }; return ( <li {...this.props} className={classNames(this.props.className, classes)}> <SafeAnchor href={this.props.href} title={this.props.title} target={this.props.target} onClick={this.handleClick}> {this.props.text} </SafeAnchor> <ul className="nav"> {ValidComponentChildren.map(this.props.children, this.renderNavItem)} </ul> </li> ); }, renderNavItem(child, index) { return cloneElement( child, { active: this.getChildActiveProp(child), onSelect: createChainedFunction(child.props.onSelect, this.props.onSelect), key: child.key ? child.key : index } ); } }); export default SubNav;
/* http://keith-wood.name/calendars.html Arabic localisation for calendars datepicker for jQuery. Mahmoud Khaled -- mahmoud.khaled@badrit.com NOTE: monthNames are the new months names */ (function($) { 'use strict'; $.calendarsPicker.regionalOptions['ar-EG'] = { renderer: $.calendarsPicker.defaultRenderer, prevText: '&#x3c;السابق', prevStatus: 'عرض الشهر السابق', prevJumpText: '&#x3c;&#x3c;', prevJumpStatus: '', nextText: 'التالي&#x3e;', nextStatus: 'عرض الشهر القادم', nextJumpText: '&#x3e;&#x3e;', nextJumpStatus: '', currentText: 'اليوم', currentStatus: 'عرض الشهر الحالي', todayText: 'اليوم', todayStatus: 'عرض الشهر الحالي', clearText: 'مسح', clearStatus: 'امسح التاريخ الحالي', closeText: 'إغلاق', closeStatus: 'إغلاق بدون حفظ', yearStatus: 'عرض سنة آخرى', monthStatus: 'عرض شهر آخر', weekText: 'أسبوع', weekStatus: 'أسبوع السنة', dayStatus: 'اختر D, M d', defaultStatus: 'اختر يوم', isRTL: true }; $.calendarsPicker.setDefaults($.calendarsPicker.regionalOptions['ar-EG']); })(jQuery);
/** * @fileoverview Common utilities. */ "use strict"; //------------------------------------------------------------------------------ // Constants //------------------------------------------------------------------------------ var PLUGIN_NAME_PREFIX = "eslint-plugin-", NAMESPACE_REGEX = /^@.*\//i; //------------------------------------------------------------------------------ // Public Interface //------------------------------------------------------------------------------ /** * Merges two config objects. This will not only add missing keys, but will also modify values to match. * @param {Object} target config object * @param {Object} src config object. Overrides in this config object will take priority over base. * @param {boolean} [combine] Whether to combine arrays or not * @returns {Object} merged config object. */ exports.mergeConfigs = function deepmerge(target, src, combine) { /* The MIT License (MIT) Copyright (c) 2012 Nicholas Fisher 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. */ // This code is taken from deepmerge repo (https://github.com/KyleAMathews/deepmerge) and modified to meet our needs. var array = Array.isArray(src) || Array.isArray(target); var dst = array && [] || {}; combine = !!combine; if (array) { target = target || []; dst = dst.concat(target); if (typeof src !== "object" && !Array.isArray(src)) { src = [src]; } Object.keys(src).forEach(function(e, i) { e = src[i]; if (typeof dst[i] === "undefined") { dst[i] = e; } else if (typeof e === "object") { dst[i] = deepmerge(target[i], e); } else { if (!combine) { dst[i] = e; } else { if (dst.indexOf(e) === -1) { dst.push(e); } } } }); } else { if (target && typeof target === "object") { Object.keys(target).forEach(function(key) { dst[key] = target[key]; }); } Object.keys(src).forEach(function(key) { if (Array.isArray(src[key]) || Array.isArray(target[key])) { dst[key] = deepmerge(target[key], src[key], key === "plugins"); } else if (typeof src[key] !== "object" || !src[key]) { dst[key] = src[key]; } else { if (!target[key]) { dst[key] = src[key]; } else { dst[key] = deepmerge(target[key], src[key]); } } }); } return dst; }; /** * Removes the prefix `eslint-plugin-` from a plugin name. * @param {string} pluginName The name of the plugin which may have the prefix. * @returns {string} The name of the plugin without prefix. */ exports.removePluginPrefix = function removePluginPrefix(pluginName) { return pluginName.indexOf(PLUGIN_NAME_PREFIX) === 0 ? pluginName.substring(PLUGIN_NAME_PREFIX.length) : pluginName; }; /** * @param {string} pluginName The name of the plugin which may have the prefix. * @returns {string} The name of the plugins namepace if it has one. */ exports.getNamespace = function getNamespace(pluginName) { return pluginName.match(NAMESPACE_REGEX) ? pluginName.match(NAMESPACE_REGEX)[0] : ""; }; /** * Removes the namespace from a plugin name. * @param {string} pluginName The name of the plugin which may have the prefix. * @returns {string} The name of the plugin without the namespace. */ exports.removeNameSpace = function removeNameSpace(pluginName) { return pluginName.replace(NAMESPACE_REGEX, ""); }; exports.PLUGIN_NAME_PREFIX = PLUGIN_NAME_PREFIX;
var MockServer = require('mockserver'); module.exports = { setUp: function (callback) { this.client = require('../../nightwatch.js').init(); callback(); }, testCommand : function(test) { var client = this.client; MockServer.addMock({ url : "/wd/hub/session/1352110219202/moveto", method:'POST', postdata: '{"element":"0"}', response : JSON.stringify({ sessionId: "1352110219202", status: 0 }) }); client.moveTo('css selector', '#weblogin', null, null, function callback(result) { test.equals(result.status, 0) }).moveToElement('#weblogin', null, null, function callback(result) { test.equals(result.status, 0) test.done(); }); }, tearDown : function(callback) { this.client = null; // clean up callback(); } }
/* * CKFinder * ======== * http://cksource.com/ckfinder * Copyright (C) 2007-2013, 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 Romanian * language. */ /** * Contains the dictionary of language entries. * @namespace */ CKFinder.lang['ro'] = { appTitle : 'CKFinder', // Common messages and labels. common : { // Put the voice-only part of the label in the span. unavailable : '%1<span class="cke_accessibility">, indisponibil</span>', confirmCancel : 'Unele opțiuni au fost schimbate. Ești sigur că vrei să închizi fereastra de dialog?', ok : 'OK', cancel : 'Anulează', confirmationTitle : 'Confirmă', messageTitle : 'Informații', inputTitle : 'Întreabă', undo : 'Starea anterioară', redo : 'Starea ulterioară(redo)', skip : 'Sări', skipAll : 'Sări peste toate', makeDecision : 'Ce acțiune trebuie luată?', rememberDecision: 'Reține acțiunea pe viitor' }, // Language direction, 'ltr' or 'rtl'. dir : 'ltr', HelpLang : 'en', LangCode : 'ro', // 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 : 'dd/mm/yyyy HH:MM', DateAmPm : ['AM', 'PM'], // Folders FoldersTitle : 'Dosare', FolderLoading : 'Încărcare...', FolderNew : 'Te rugăm să introduci numele dosarului nou: ', FolderRename : 'Te rugăm să introduci numele nou al dosarului: ', FolderDelete : 'Ești sigur că vrei să ștergi dosarul "%1"?', FolderRenaming : ' (Redenumire...)', FolderDeleting : ' (Ștergere...)', DestinationFolder : 'Destination Folder', // MISSING // Files FileRename : 'Te rugăm să introduci numele nou al fișierului: ', FileRenameExt : 'Ești sigur că vrei să schimbi extensia fișierului? Fișierul poate deveni inutilizabil.', FileRenaming : 'Redenumire...', FileDelete : 'Ești sigur că vrei să ștergi fișierul "%1"?', FilesDelete : 'Are you sure you want to delete %1 files?', // MISSING FilesLoading : 'Încărcare...', FilesEmpty : 'Dosarul este gol.', DestinationFile : 'Destination File', // MISSING SkippedFiles : 'List of skipped files:', // MISSING // Basket BasketFolder : 'Coș', BasketClear : 'Golește coș', BasketRemove : 'Elimină din coș', BasketOpenFolder : 'Deschide dosarul părinte', BasketTruncateConfirm : 'Sigur dorești să elimini toate fișierele din coș?', BasketRemoveConfirm : 'Sigur dorești să elimini fișierul "%1" din coș?', BasketRemoveConfirmMultiple : 'Do you really want to remove %1 files from the basket?', // MISSING BasketEmpty : 'Niciun fișier în coș, trage și așează cu mouse-ul.', BasketCopyFilesHere : 'Copiază fișiere din coș', BasketMoveFilesHere : 'Mută fișiere din coș', // Global messages OperationCompletedSuccess : 'Operation completed successfully.', // MISSING OperationCompletedErrors : 'Operation completed with errors.', // MISSING FileError : '%s: %e', // MISSING // Move and Copy files MovedFilesNumber : 'Number of files moved: %s.', // MISSING CopiedFilesNumber : 'Number of files copied: %s.', // MISSING MoveFailedList : 'The following files could not be moved:<br />%s', // MISSING CopyFailedList : 'The following files could not be copied:<br />%s', // MISSING // Toolbar Buttons (some used elsewhere) Upload : 'Încarcă', UploadTip : 'Încarcă un fișier nou', Refresh : 'Reîmprospătare', Settings : 'Setări', Help : 'Ajutor', HelpTip : 'Ajutor', // Context Menus Select : 'Selectează', SelectThumbnail : 'Selectează Thumbnail', View : 'Vizualizează', Download : 'Descarcă', NewSubFolder : 'Subdosar nou', Rename : 'Redenumește', Delete : 'Șterge', DeleteFiles : 'Delete Files', // MISSING CopyDragDrop : 'Copiază aici', MoveDragDrop : 'Mută aici', // Dialogs RenameDlgTitle : 'Redenumește', NewNameDlgTitle : 'Nume nou', FileExistsDlgTitle : 'Fișierul există deja', SysErrorDlgTitle : 'Eroare de sistem', FileOverwrite : 'Suprascriere', FileAutorename : 'Auto-redenumire', ManuallyRename : 'Manually rename', // MISSING // Generic OkBtn : 'OK', CancelBtn : 'Anulează', CloseBtn : 'Închide', // Upload Panel UploadTitle : 'Încarcă un fișier nou', UploadSelectLbl : 'Selectează un fișier de încărcat', UploadProgressLbl : '(Încărcare în progres, te rog așteaptă...)', UploadBtn : 'Încarcă fișierul selectat', UploadBtnCancel : 'Anulează', UploadNoFileMsg : 'Te rugăm să selectezi un fișier din computer.', UploadNoFolder : 'Te rugăm să selectezi un dosar înainte de a încărca.', UploadNoPerms : 'Încărcare fișier nepermisă.', UploadUnknError : 'Eroare la trimiterea fișierului.', UploadExtIncorrect : 'Extensie fișier nepermisă în acest dosar.', // Flash Uploads UploadLabel : 'Fișiere de încărcat', UploadTotalFiles : 'Total fișiere:', UploadTotalSize : 'Total mărime:', UploadSend : 'Încarcă', UploadAddFiles : 'Adaugă fișiere', UploadClearFiles : 'Renunță la toate', UploadCancel : 'Anulează încărcare', UploadRemove : 'Elimină', UploadRemoveTip : 'Elimină !f', UploadUploaded : 'Încarcă !n%', UploadProcessing : 'Prelucrare...', // Settings Panel SetTitle : 'Setări', SetView : 'Vizualizează:', SetViewThumb : 'Thumbnails', SetViewList : 'Listă', SetDisplay : 'Afișează:', SetDisplayName : 'Nume fișier', SetDisplayDate : 'Dată', SetDisplaySize : 'Mărime fișier', SetSort : 'Sortare:', SetSortName : 'după nume fișier', SetSortDate : 'după dată', SetSortSize : 'după mărime', SetSortExtension : 'după extensie', // Status Bar FilesCountEmpty : '<Dosar Gol>', FilesCountOne : '1 fișier', FilesCountMany : '%1 fișiere', // Size and Speed Kb : '%1 KB', Mb : '%1 MB', Gb : '%1 GB', SizePerSecond : '%1/s', // Connector Error Messages. ErrorUnknown : 'Nu a fost posibilă finalizarea cererii. (Eroare %1)', Errors : { 10 : 'Comandă invalidă.', 11 : 'Tipul de resursă nu a fost specificat în cerere.', 12 : 'Tipul de resursă cerut nu este valid.', 102 : 'Nume fișier sau nume dosar invalid.', 103 : 'Nu a fost posibiliă finalizarea cererii din cauza restricțiilor de autorizare.', 104 : 'Nu a fost posibiliă finalizarea cererii din cauza restricțiilor de permisiune la sistemul de fișiere.', 105 : 'Extensie fișier invalidă.', 109 : 'Cerere invalidă.', 110 : 'Eroare necunoscută.', 111 : 'It was not possible to complete the request due to resulting file size.', // MISSING 115 : 'Există deja un fișier sau un dosar cu același nume.', 116 : 'Dosar negăsit. Te rog împrospătează și încearcă din nou.', 117 : 'Fișier negăsit. Te rog împrospătează lista de fișiere și încearcă din nou.', 118 : 'Calea sursei și a țintei sunt egale.', 201 : 'Un fișier cu același nume este deja disponibil. Fișierul încărcat a fost redenumit cu "%1".', 202 : 'Fișier invalid.', 203 : 'Fișier invalid. Mărimea fișierului este prea mare.', 204 : 'Fișierul încărcat este corupt.', 205 : 'Niciun dosar temporar nu este disponibil pentru încărcarea pe server.', 206 : 'Încărcare anulată din motive de securitate. Fișierul conține date asemănătoare cu HTML.', 207 : 'Fișierul încărcat a fost redenumit cu "%1".', 300 : 'Mutare fișier(e) eșuată.', 301 : 'Copiere fișier(e) eșuată.', 500 : 'Browser-ul de fișiere este dezactivat din motive de securitate. Te rog contactează administratorul de sistem și verifică configurarea de fișiere CKFinder.', 501 : 'Funcționalitatea de creat thumbnails este dezactivată.' }, // Other Error Messages. ErrorMsg : { FileEmpty : 'Numele fișierului nu poate fi gol.', FileExists : 'Fișierul %s există deja.', FolderEmpty : 'Numele dosarului nu poate fi gol.', FolderExists : 'Folder %s already exists.', // MISSING FolderNameExists : 'Folder already exists.', // MISSING FileInvChar : 'Numele fișierului nu poate conține niciunul din următoarele caractere: \n\\ / : * ? " < > |', FolderInvChar : 'Numele dosarului nu poate conține niciunul din următoarele caractere: \n\\ / : * ? " < > |', PopupBlockView : 'Nu a fost posibilă deschiderea fișierului într-o fereastră nouă. Te rugăm să configurezi browser-ul și să dezactivezi toate popup-urile blocate pentru acest site.', XmlError : 'Nu a fost posibilă încărcarea în mod corespunzător a răspunsului XML de pe serverul web.', XmlEmpty : 'Nu a fost posibilă încărcarea răspunsului XML de pe serverul web. Serverul a returnat un răspuns gol.', XmlRawResponse : 'Răspuns brut de la server: %s' }, // Imageresize plugin Imageresize : { dialogTitle : 'Redimensionează %s', sizeTooBig : 'Nu se pot seta înălțimea sau lățimea unei imagini la o valoare mai mare decât dimesiunea originală (%size).', resizeSuccess : 'Imagine redimensionată cu succes.', thumbnailNew : 'Crează un thumbnail nou', thumbnailSmall : 'Mic (%s)', thumbnailMedium : 'Mediu (%s)', thumbnailLarge : 'Mare (%s)', newSize : 'Setează o dimensiune nouă', width : 'Lățime', height : 'Înălțime', invalidHeight : 'Înălțime invalidă.', invalidWidth : 'Lățime invalidă.', invalidName : 'Nume fișier invalid.', newImage : 'Creează o imagine nouă', noExtensionChange : 'Extensia fișierului nu poate fi schimbată.', imageSmall : 'Imaginea sursă este prea mică.', contextMenuName : 'Redimensionează', lockRatio : 'Blochează raport', resetSize : 'Resetează dimensiunea' }, // Fileeditor plugin Fileeditor : { save : 'Salvează', fileOpenError : 'Fișierul nu a putut fi deschis.', fileSaveSuccess : 'Fișier salvat cu succes.', contextMenuName : 'Editează', loadingFile : 'Încărcare fișier, te rog așteaptă...' }, Maximize : { maximize : 'Maximizare', minimize : 'Minimizare' }, Gallery : { current : 'Imaginea {current} din {total}' }, Zip : { extractHereLabel : 'Extract here', // MISSING extractToLabel : 'Extract to...', // MISSING downloadZipLabel : 'Download as zip', // MISSING compressZipLabel : 'Compress to zip', // MISSING removeAndExtract : 'Remove existing and extract', // MISSING extractAndOverwrite : 'Extract overwriting existing files', // MISSING extractSuccess : 'File extracted successfully.' // MISSING }, Search : { searchPlaceholder : 'Căutare' } };
var assert = require('assert'); var math = require('../../../index'); var Matrix = math.type.Matrix; var DenseMatrix = math.type.DenseMatrix; var SparseMatrix = math.type.SparseMatrix; var Complex = math.type.Complex; var Range = math.type.Range; var index = math.index; describe('DenseMatrix', function() { describe('constructor', function() { it('should create empty matrix if called with no argument', function() { var m = new DenseMatrix(); assert.deepEqual(m._size, [0]); assert.deepEqual(m._data, []); }); it('should create a DenseMatrix from an array', function () { var m = new DenseMatrix( [ [1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12] ]); assert.deepEqual(m._size, [4, 3]); assert.deepEqual( m._data, [ [1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12] ]); }); it('should create a DenseMatrix from an array, number datatype', function () { var m = new DenseMatrix( [ [1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12] ], 'number'); assert.deepEqual(m._size, [4, 3]); assert.deepEqual( m._data, [ [1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12] ]); assert(m._datatype === 'number'); }); it('should create a DenseMatrix an array containing matrices', function () { var m = new DenseMatrix([new DenseMatrix([1,2]), new DenseMatrix([3, 4])]); assert.deepEqual(m, new DenseMatrix([[1,2],[3, 4]])); }); it('should create a DenseMatrix from another DenseMatrix', function () { var m1 = new DenseMatrix( [ [1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12] ]); var m2 = new DenseMatrix(m1); assert.deepEqual(m1._size, m2._size); assert.deepEqual(m1._data, m2._data); }); it('should create a DenseMatrix from another DenseMatrix, number datatype', function () { var m1 = new DenseMatrix( [ [1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12] ], 'number'); var m2 = new DenseMatrix(m1); assert.deepEqual(m1._size, m2._size); assert.deepEqual(m1._data, m2._data); assert.deepEqual(m1._datatype, m2._datatype); }); it('should create a DenseMatrix from a SparseMatrix', function () { var m1 = new SparseMatrix( [ [1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12] ]); var m2 = new DenseMatrix(m1); assert.deepEqual(m1.size(), m2.size()); assert.deepEqual(m1.toArray(), m2.toArray()); }); it('should create a DenseMatrix from a SparseMatrix, number datatype', function () { var m1 = new SparseMatrix( [ [1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12] ], 'number'); var m2 = new DenseMatrix(m1); assert.deepEqual(m1.size(), m2.size()); assert.deepEqual(m1.toArray(), m2.toArray()); assert.deepEqual(m1._datatype, m2._datatype); }); it('should create a DenseMatrix using method create', function () { var a = new DenseMatrix ([1,2,3]); var b = a.create([4,5,6]); assert.equal(b.isDenseMatrix, true); assert.deepEqual(b, new DenseMatrix([4,5,6])); var c = a.create([7,8,9], 'number'); assert.deepEqual(c, new DenseMatrix([7,8,9], 'number')); }); it('should have a property isMatrix', function () { var a = new DenseMatrix(); assert.strictEqual(a.isMatrix, true); }); it('should have a property isDenseMatrix', function () { var a = new DenseMatrix(); assert.strictEqual(a.isDenseMatrix, true); }); it('should have a property type', function () { var a = new DenseMatrix(); assert.strictEqual(a.type, 'DenseMatrix'); }); it('should throw an error when the dimensions of the input array are invalid', function () { assert.throws(function () { new DenseMatrix( [ [1, 2], [4, 5, 6] ]); }, /DimensionError: Dimension mismatch \(3 != 2\)/); }); it('should throw an error when called without new keyword', function () { assert.throws(function () { DenseMatrix(); }, /Constructor must be called with the new operator/); }); it('should throw an error when called with invalid datatype', function () { assert.throws(function () { new DenseMatrix([], 1); }); }); }); describe('size', function() { it('should return the expected size', function() { assert.deepEqual(new DenseMatrix().size(), [0]); assert.deepEqual(new DenseMatrix([[23]]).size(), [1,1]); assert.deepEqual(new DenseMatrix([[1,2,3],[4,5,6]]).size(), [2,3]); assert.deepEqual(new DenseMatrix([1,2,3]).size(), [3]); assert.deepEqual(new DenseMatrix([[1],[2],[3]]).size(), [3,1]); assert.deepEqual(new DenseMatrix([[[1],[2],[3]]]).size(), [1,3,1]); assert.deepEqual(new DenseMatrix([[[3]]]).size(), [1,1,1]); assert.deepEqual(new DenseMatrix([[]]).size(), [1,0]); }); it('should return a clone of the size', function() { var m = new DenseMatrix([[1,2,3], [4,5,6]]); var s = m.size(); assert.deepEqual(s, [2, 3]); // change s, should not change the size of m s[2] = 4; assert.deepEqual(s, [2, 3, 4]); assert.deepEqual(m.size(), [2, 3]); }); }); describe('toString', function() { it('should return string representation of matrix', function() { assert.equal(new DenseMatrix([[1,2],[3,4]]).toString(), '[[1, 2], [3, 4]]'); assert.equal(new DenseMatrix([[1,2],[3,1/3]]).toString(), '[[1, 2], [3, 0.3333333333333333]]'); }); }); describe('toJSON', function () { it('should serialize Matrix', function() { assert.deepEqual( new DenseMatrix([[1,2],[3,4]]).toJSON(), { mathjs: 'DenseMatrix', data: [[1, 2], [3, 4]], size: [2, 2], datatype: undefined }); }); it('should serialize Matrix, number datatype', function() { assert.deepEqual( new DenseMatrix([[1,2],[3,4]], 'number').toJSON(), { mathjs: 'DenseMatrix', data: [[1, 2], [3, 4]], size: [2, 2], datatype: 'number' }); }); }); describe('fromJSON', function () { it('should deserialize Matrix', function() { var json = { mathjs: 'DenseMatrix', data: [[1, 2], [3, 4]], size: [2, 2] }; var m = DenseMatrix.fromJSON(json); assert.ok(m instanceof Matrix); assert.deepEqual(m._size, [2, 2]); assert.strictEqual(m._data[0][0], 1); assert.strictEqual(m._data[0][1], 2); assert.strictEqual(m._data[1][0], 3); assert.strictEqual(m._data[1][1], 4); }); it('should deserialize Matrix, number datatype', function() { var json = { mathjs: 'DenseMatrix', data: [[1, 2], [3, 4]], size: [2, 2], datatype: 'number' }; var m = DenseMatrix.fromJSON(json); assert.ok(m instanceof Matrix); assert.deepEqual(m._size, [2, 2]); assert.strictEqual(m._data[0][0], 1); assert.strictEqual(m._data[0][1], 2); assert.strictEqual(m._data[1][0], 3); assert.strictEqual(m._data[1][1], 4); assert.strictEqual(m._datatype, 'number'); }); }); describe('format', function () { it('should format matrix', function() { assert.equal(new DenseMatrix([[1,2],[3,1/3]]).format(), '[[1, 2], [3, 0.3333333333333333]]'); assert.equal(new DenseMatrix([[1,2],[3,1/3]]).format(3), '[[1, 2], [3, 0.333]]'); assert.equal(new DenseMatrix([[1,2],[3,1/3]]).format(4), '[[1, 2], [3, 0.3333]]'); }); }); describe('resize', function() { it('should resize the matrix correctly', function() { var m = new DenseMatrix([[1,2,3],[4,5,6]]); m.resize([2,4]); assert.deepEqual(m.valueOf(), [[1,2,3,0], [4,5,6,0]]); m.resize([1,2]); assert.deepEqual(m.valueOf(), [[1,2]]); m.resize([1,2,2], 8); assert.deepEqual(m.valueOf(), [[[1,8],[2,8]]]); m.resize([2,3], 9); assert.deepEqual(m.valueOf(), [[1,2, 9], [9,9,9]]); m = new DenseMatrix(); m.resize([3,3,3], 6); assert.deepEqual(m.valueOf(), [ [[6,6,6],[6,6,6],[6,6,6]], [[6,6,6],[6,6,6],[6,6,6]], [[6,6,6],[6,6,6],[6,6,6]] ]); m.resize([2,2]); assert.deepEqual(m.valueOf(), [[6,6],[6,6]]); m.resize([0]); assert.deepEqual(m.valueOf(), []); }); it('should resize the matrix with uninitialized default value', function() { var m = new DenseMatrix([]); m.resize([3], math.uninitialized); assert.deepEqual(m.valueOf(), arr(uninit, uninit, uninit)); }); it('should return a different matrix when copy=true', function() { var m1 = new DenseMatrix( [ [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0] ]); var m2 = m1.resize([2, 2], 0, true); assert(m1 !== m2); // original matrix cannot be modified assert.deepEqual(m1._size, [4, 4]); assert.deepEqual( m1._data, [ [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0] ]); // new matrix should have correct size assert.deepEqual(m2._size, [2, 2]); assert.deepEqual( m2._data, [ [0, 0], [0, 0] ]); }); }); describe('reshape', function () { it('should reshape the matrix properly', function () { var m = new DenseMatrix([[1,2,3],[4,5,6]]); m.reshape([3,2]); assert.deepEqual(m.valueOf(), [[1,2], [3,4], [5,6]]); m.reshape([6,1]); assert.deepEqual(m.valueOf(), [[1],[2],[3],[4],[5],[6]]); }); it('should return a copy only when specified', function () { var m1 = new DenseMatrix([[1, 2], [3, 4]]); var m2 = m1.reshape([4]); var m3 = m2.reshape([1, 4], true); assert.strictEqual(m2, m1); assert.deepEqual(m2.valueOf(), [1, 2, 3, 4]); assert.deepEqual(m2.valueOf(), m1.valueOf()); assert.notStrictEqual(m3, m2); assert.deepEqual(m3.valueOf(), [[1, 2, 3, 4]]); assert.notDeepEqual(m3.valueOf(), m2.valueOf()); }); it('should update the size of the reshaped matrix', function () { var m1 = new DenseMatrix([[1, 2], [3, 4]]); var m2 = m1.reshape([4], true); assert.deepEqual(m1.size(), [2, 2]); m1.reshape([1, 1, 4]); assert.deepEqual(m1.size(), [1, 1, 4]); assert.deepEqual(m2.size(), [4]); }); }); describe('get', function () { var m = new DenseMatrix([[0, 1], [2, 3]]); it('should get a value from the matrix', function() { assert.equal(m.get([1,0]), 2); assert.equal(m.get([0,1]), 1); }); it('should throw an error when getting a value out of range', function() { assert.throws(function () { m.get([3,0]); }); assert.throws(function () { m.get([1,5]); }); assert.throws(function () { m.get([1]); }); assert.throws(function () { m.get([]); }); }); it('should throw an error in case of dimension mismatch', function() { assert.throws(function () { m.get([0,2,0,2,0,2]); }, /Dimension mismatch/); }); it('should throw an error when getting a value given a invalid index', function() { assert.throws(function () { m.get([1.2, 2]); }); assert.throws(function () { m.get([1,-2]); }); assert.throws(function () { m.get(1,1); }); assert.throws(function () { m.get(math.index(1,1)); }); assert.throws(function () { m.get([[1,1]]); }); }); }); describe('set', function () { it('should set a value in a matrix', function() { var m = new DenseMatrix([[0, 0], [0, 0]]); m.set([1,0], 5); assert.deepEqual(m, new DenseMatrix([ [0, 0], [5, 0] ])); m.set([0, 2], 4); assert.deepEqual(m, new DenseMatrix([ [0, 0, 4], [5, 0, 0] ])); m.set([0,0,1], 3); assert.deepEqual(m, new DenseMatrix([ [[0,3], [0,0], [4,0]], [[5,0], [0,0], [0,0]] ])); }); it('should set a value in a matrix with defaultValue for new elements', function() { var m = new DenseMatrix(); var defaultValue = 0; m.set([2], 4, defaultValue); assert.deepEqual(m, new DenseMatrix([0, 0, 4])); }); it('should throw an error when setting a value given a invalid index', function() { var m = new DenseMatrix([[0, 0], [0, 0]]); assert.throws(function() { m.set([2.5,0], 5); }); assert.throws(function() { m.set([1], 5); }); assert.throws(function() { m.set([-1, 1], 5); }); assert.throws(function() { m.set(math.index(new Range(0,0)), 5); }); }); }); describe('get subset', function() { it('should get the right subset of the matrix', function() { var m; // get 1-dimensional m = new DenseMatrix(math.range(0,10)); assert.deepEqual(m.size(), [10]); assert.deepEqual(m.subset(index(new Range(2, 5))).valueOf(), [2,3,4]); // get 2-dimensional m = new DenseMatrix([[1,2,3],[4,5,6],[7,8,9]]); assert.deepEqual(m.size(), [3,3]); assert.deepEqual(m.subset(index(1,1)), 5); assert.deepEqual(m.subset(index(new Range(0,2),new Range(0,2))).valueOf(), [[1,2],[4,5]]); assert.deepEqual(m.subset(index(1, new Range(1,3))).valueOf(), [[5,6]]); assert.deepEqual(m.subset(index(0, new Range(1,3))).valueOf(), [[2,3]]); assert.deepEqual(m.subset(index(new Range(1,3), 1)).valueOf(), [[5],[8]]); assert.deepEqual(m.subset(index(new Range(1,3), 2)).valueOf(), [[6],[9]]); assert.deepEqual(m.subset(index([0,1,2], [1])).valueOf(), [[2],[5],[8]]); // get n-dimensional m = new DenseMatrix([[[1,2],[3,4]], [[5,6],[7,8]]]); assert.deepEqual(m.size(), [2,2,2]); assert.deepEqual(m.subset(index(new Range(0,2),new Range(0,2),new Range(0,2))).valueOf(), m.valueOf()); assert.deepEqual(m.subset(index(0,0,0)), 1); assert.deepEqual(m.subset(index(1,1,1)).valueOf(), 8); assert.deepEqual(m.subset(index(1,1,new Range(0,2))).valueOf(), [[[7,8]]]); assert.deepEqual(m.subset(index(1,new Range(0,2),1)).valueOf(), [[[6],[8]]]); assert.deepEqual(m.subset(index(new Range(0,2),1,1)).valueOf(), [[[4]],[[8]]]); }); it('should squeeze the output when index contains a scalar', function() { var m = new DenseMatrix(math.range(0,10)); assert.deepEqual(m.subset(index(1)), 1); assert.deepEqual(m.subset(index(new Range(1,2))), new DenseMatrix([1])); m = new DenseMatrix([[1,2], [3,4]]); assert.deepEqual(m.subset(index(1,1)), 4); assert.deepEqual(m.subset(index(new Range(1,2), 1)), new DenseMatrix([[4]])); assert.deepEqual(m.subset(index(1, new Range(1,2))), new DenseMatrix([[4]])); assert.deepEqual(m.subset(index(new Range(1,2), new Range(1,2))), new DenseMatrix([[4]])); }); it('should throw an error if the given subset is invalid', function() { var m = new DenseMatrix(); assert.throws(function () { m.subset([-1]); }); m = new DenseMatrix([[1,2,3],[4,5,6]]); assert.throws(function () { m.subset([1,2,3]); }); assert.throws(function () { m.subset([3,0]); }); assert.throws(function () { m.subset([1]); }); }); it('should throw an error in case of wrong number of arguments', function() { var m = new DenseMatrix(); assert.throws(function () { m.subset();}, /Wrong number of arguments/); assert.throws(function () { m.subset(1,2,3,4); }, /Wrong number of arguments/); }); it('should throw an error in case of dimension mismatch', function() { var m = new DenseMatrix([[1,2,3],[4,5,6]]); assert.throws(function () { m.subset(index(new Range(0,2))); }, /Dimension mismatch/); }); }); describe('set subset', function() { it('should set the given subset', function() { // set 1-dimensional var m = new DenseMatrix(math.range(0,7)); m.subset(index(new Range(2,4)), [20,30]); assert.deepEqual(m, new DenseMatrix([0,1,20,30,4,5,6])); m.subset(index(4), 40); assert.deepEqual(m, new DenseMatrix([0,1,20,30,40,5,6])); // set 2-dimensional m = new DenseMatrix(); m.resize([3,3]); assert.deepEqual(m, new DenseMatrix([ [0, 0, 0], [0, 0, 0], [0, 0, 0] ])); m.subset(index(new Range(1,3), new Range(1,3)), [[1,2],[3,4]]); assert.deepEqual(m, new DenseMatrix([ [0, 0, 0], [0, 1, 2], [0, 3, 4]])); m.subset(index(0, new Range(0,3)), [5,6,7]); assert.deepEqual(m, new DenseMatrix([[5,6,7],[0,1,2],[0,3,4]])); m.subset(index(new Range(0,3), 0), [8,9,10]); // unsqueezes the submatrix assert.deepEqual(m, new DenseMatrix([[8,6,7],[9,1,2],[10,3,4]])); }); it('should set the given subset with defaultValue for new elements', function() { // multiple values var m = new DenseMatrix(); var defaultValue = 0; m.subset(index(new Range(3,5)), [3, 4], defaultValue); assert.deepEqual(m, new DenseMatrix([0, 0, 0, 3, 4])); defaultValue = 1; m.subset(index(new Range(3,5),1), [5, 6], defaultValue); assert.deepEqual(m, new DenseMatrix([ [0, 1], [0, 1], [0, 1], [3, 5], [4, 6] ])); defaultValue = 2; m.subset(index(new Range(3,5),2), [7, 8], defaultValue); assert.deepEqual(m, new DenseMatrix([ [0, 1, 2], [0, 1, 2], [0, 1, 2], [3, 5, 7], [4, 6, 8] ])); // a single value var i = new DenseMatrix(); defaultValue = 0; i.subset(math.index(2, 1), 6, defaultValue); assert.deepEqual(i, new DenseMatrix([[0, 0], [0, 0], [0, 6]])); }); it('should unsqueeze the replacement subset if needed', function() { var m = new DenseMatrix([[0,0],[0,0]]); // 2x2 m.subset(index(0, new Range(0,2)), [1,1]); // 2 assert.deepEqual(m, new DenseMatrix([[1,1],[0,0]])); m.subset(index(new Range(0,2), 0), [2,2]); // 2 assert.deepEqual(m, new DenseMatrix([[2,1],[2,0]])); m = new DenseMatrix([[[0],[0],[0]]]); // 1x3x1 m.subset(index(0, new Range(0,3), 0), [1,2,3]); // 3 assert.deepEqual(m, new DenseMatrix([[[1],[2],[3]]])); m = new DenseMatrix([[[0,0,0]]]); // 1x1x3 m.subset(index(0, 0, new Range(0,3)), [1,2,3]); // 3 assert.deepEqual(m, new DenseMatrix([[[1,2,3]]])); m = new DenseMatrix([[[0]],[[0]],[[0]]]); // 3x1x1 m.subset(index(new Range(0,3), 0, 0), [1,2,3]); // 3 assert.deepEqual(m, new DenseMatrix([[[1]],[[2]],[[3]]])); m = new DenseMatrix([[[0,0,0]]]); // 1x1x3 m.subset(index(0, 0, new Range(0,3)), [[1,2,3]]); // 1x3 assert.deepEqual(m, new DenseMatrix([[[1,2,3]]])); m = new DenseMatrix([[[0]],[[0]],[[0]]]); // 3x1x1 m.subset(index(new Range(0,3), 0, 0), [[1],[2],[3]]); // 3x1 assert.deepEqual(m, new DenseMatrix([[[1]],[[2]],[[3]]])); }); it('should leave the subset unchanged when unsqueezing it', function() { var m = new DenseMatrix([[0, 0], [0, 0]]); // 2 dimensional var r = new DenseMatrix([1,2]); // 1 dimensional m.subset(index(0, new Range(0,2)), r); assert.deepEqual(m, new DenseMatrix([[1, 2], [0, 0]])); assert.deepEqual(r, new DenseMatrix([1,2])); }); it('should resize the matrix if the replacement subset is different size than selected subset', function() { // set 2-dimensional with resize var m = new DenseMatrix([[123]]); m.subset(index(new Range(1,3), new Range(1,3)), [[1,2],[3,4]]); assert.deepEqual(m, new DenseMatrix([[123,0,0],[0,1,2],[0,3,4]])); // set resize dimensions m = new DenseMatrix([123]); assert.deepEqual(m.size(), [1]); m.subset(index(new Range(1,3), new Range(1,3)), [[1,2],[3,4]]); assert.deepEqual(m, new DenseMatrix([[123,0,0],[0,1,2],[0,3,4]])); m.subset(index(new Range(0,2), new Range(0,2)), [[55,55],[55,55]]); assert.deepEqual(m, new DenseMatrix([[55,55,0],[55,55,2],[0,3,4]])); m = new DenseMatrix(); m.subset(index(new Range(1,3), new Range(1,3), new Range(1,3)), [[[1,2],[3,4]],[[5,6],[7,8]]]); var res = new DenseMatrix([ [ [0, 0, 0], [0, 0, 0], [0, 0, 0] ], [ [0, 0, 0], [0, 1, 2], [0, 3, 4] ], [ [0, 0, 0], [0, 5, 6], [0, 7, 8] ] ]); assert.deepEqual(m, res); }); it ('should throw an error in case of wrong type of index', function () { assert.throws(function () { new DenseMatrix().subset('no index', 2); }, /Invalid index/); }); it ('should throw an error in case of wrong size of submatrix', function () { assert.throws(function () { new DenseMatrix().subset(index(0), [2,3]); }, /Scalar expected/); }); it('should throw an error in case of dimension mismatch', function() { var m = new DenseMatrix([[1,2,3],[4,5,6]]); assert.throws(function () { m.subset(index(new Range(0,2)), [100,100]); }, /Dimension mismatch/); assert.throws(function () { m.subset(index(new Range(0,2), new Range(0,2)), [100,100]); }, /Dimension mismatch/); }); }); describe('map', function() { it('should apply the given function to all elements in the matrix', function() { var m = new DenseMatrix([ [[1,2],[3,4]], [[5,6],[7,8]], [[9,10],[11,12]], [[13,14],[15,16]] ]); var m2 = m.map(function (value) { return value * 2; }); assert.deepEqual( m2.valueOf(), [ [[2,4],[6,8]], [[10,12],[14,16]], [[18,20],[22,24]], [[26,28],[30,32]] ]); m = new DenseMatrix([1]); m2 = m.map(function (value) { return value * 2; }); assert.deepEqual(m2.valueOf(), [2]); m = new DenseMatrix([1,2,3]); m2 = m.map(function (value) { return value * 2; }); assert.deepEqual(m2.valueOf(), [2,4,6]); }); it('should work on empty matrices', function() { var m = new DenseMatrix([]); var m2 = m.map(function (value) { return value * 2; }); assert.deepEqual(m2.toArray(), []); }); it('should invoke callback with parameters value, index, obj', function() { var m = new DenseMatrix([[1,2,3], [4,5,6]]); var m2 = m.map( function (value, index, obj) { return math.clone([value, index, obj === m]); } ); assert.deepEqual( m2.toArray(), [ [ [1, [0, 0], true ], [2, [0, 1], true ], [3, [0, 2], true ] ], [ [4, [1, 0], true ], [5, [1, 1], true ], [6, [1, 2], true ] ] ]); }); }); describe('forEach', function() { it('should run on all elements of the matrix, last dimension first', function() { var m, output; m = new DenseMatrix([ [[1,2],[3,4]], [[5,6],[7,8]], [[9,10],[11,12]], [[13,14],[15,16]] ]); output = []; m.forEach(function (value) { output.push(value); }); assert.deepEqual(output, [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]); m = new DenseMatrix([1]); output = []; m.forEach(function (value) { output.push(value); }); assert.deepEqual(output, [1]); m = new DenseMatrix([1,2,3]); output = []; m.forEach(function (value) { output.push(value); }); assert.deepEqual(output, [1,2,3]); }); it('should work on empty matrices', function() { var m = new DenseMatrix([]); var output = []; m.forEach(function (value) { output.push(value); }); assert.deepEqual(output, []); }); it('should invoke callback with parameters value, index, obj', function() { var m = new DenseMatrix([[1,2,3], [4,5,6]]); var output = []; m.forEach( function (value, index, obj) { output.push(math.clone([value, index, obj === m])); } ); assert.deepEqual(output, [ [1, [0, 0], true ], [2, [0, 1], true ], [3, [0, 2], true ], [4, [1, 0], true ], [5, [1, 1], true ], [6, [1, 2], true ] ]); }); }); describe('clone', function() { it('should clone the matrix properly', function() { var m1 = new DenseMatrix( [ [1,2,3], [4,5,6] ]); var m2 = m1.clone(); assert.deepEqual(m1._data, m2._data); }); }); describe('toArray', function () { it('should return array', function () { var m = new DenseMatrix({ data: [ [1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12] ], size: [4, 3] }); var a = m.toArray(); assert.deepEqual( a, [ [1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12] ]); }); it('should return array, complex numbers', function () { var m = new DenseMatrix({ data: [new Complex(1, 1), new Complex(4, 4), new Complex(5, 5), new Complex(2, 2), new Complex(3, 3), new Complex(6, 6)], size: [1, 6] }); var a = m.toArray(); assert.deepEqual(a, [new Complex(1, 1), new Complex(4, 4), new Complex(5, 5), new Complex(2, 2), new Complex(3, 3), new Complex(6, 6)]); }); }); describe('diagonal', function () { it('should create matrix (n x n)', function () { var m = DenseMatrix.diagonal([3, 3], 1); assert.deepEqual(m._size, [3, 3]); assert.deepEqual( m.toArray(), [ [1, 0, 0], [0, 1, 0], [0, 0, 1] ]); }); it('should create matrix (n x n), k > 0', function () { var m = DenseMatrix.diagonal([3, 3], 1, 1); assert.deepEqual(m._size, [3, 3]); assert.deepEqual( m.toArray(), [ [0, 1, 0], [0, 0, 1], [0, 0, 0] ]); }); it('should create matrix (n x n), k < 0', function () { var m = DenseMatrix.diagonal([3, 3], 1, -1); assert.deepEqual(m._size, [3, 3]); assert.deepEqual( m.toArray(), [ [0, 0, 0], [1, 0, 0], [0, 1, 0] ]); }); it('should create matrix (n x n), vector value', function () { var m = DenseMatrix.diagonal([3, 3], [1, 2, 3]); assert.deepEqual(m._size, [3, 3]); assert.deepEqual( m.toArray(), [ [1, 0, 0], [0, 2, 0], [0, 0, 3] ]); }); it('should create matrix (n x n), vector value, k > 0', function () { var m = DenseMatrix.diagonal([3, 3], [1, 2], 1); assert.deepEqual(m._size, [3, 3]); assert.deepEqual( m.toArray(), [ [0, 1, 0], [0, 0, 2], [0, 0, 0] ]); }); it('should create matrix (n x n), vector value, k < 0', function () { var m = DenseMatrix.diagonal([3, 3], [1, 2], -1); assert.deepEqual(m._size, [3, 3]); assert.deepEqual( m.toArray(), [ [0, 0, 0], [1, 0, 0], [0, 2, 0] ]); }); it('should create matrix (n x n), matrix vector value', function () { var m = DenseMatrix.diagonal([3, 3], math.matrix([1, 2, 3])); assert.deepEqual(m._size, [3, 3]); assert.deepEqual( m.toArray(), [ [1, 0, 0], [0, 2, 0], [0, 0, 3] ]); }); it('should create matrix (n x n), matrix vector value, k > 0', function () { var m = DenseMatrix.diagonal([3, 3], math.matrix([1, 2]), 1); assert.deepEqual(m._size, [3, 3]); assert.deepEqual( m.toArray(), [ [0, 1, 0], [0, 0, 2], [0, 0, 0] ]); }); it('should create matrix (n x n), matrix vector value, k < 0', function () { var m = DenseMatrix.diagonal([3, 3], math.matrix([1, 2]), -1); assert.deepEqual(m._size, [3, 3]); assert.deepEqual( m.toArray(), [ [0, 0, 0], [1, 0, 0], [0, 2, 0] ]); }); it('should create matrix (m x n), m > n', function () { var m = DenseMatrix.diagonal([4, 3], 1); assert.deepEqual(m._size, [4, 3]); assert.deepEqual( m.toArray(), [ [1, 0, 0], [0, 1, 0], [0, 0, 1], [0, 0, 0] ]); }); it('should create matrix (m x n), m > n, k > 0', function () { var m = DenseMatrix.diagonal([4, 3], 1, 1); assert.deepEqual(m._size, [4, 3]); assert.deepEqual( m.toArray(), [ [0, 1, 0], [0, 0, 1], [0, 0, 0], [0, 0, 0] ]); }); it('should create matrix (m x n), m > n, k < 0', function () { var m = DenseMatrix.diagonal([4, 3], 1, -1); assert.deepEqual(m._size, [4, 3]); assert.deepEqual( m.toArray(), [ [0, 0, 0], [1, 0, 0], [0, 1, 0], [0, 0, 1], ]); }); it('should create matrix (m x n), m > n, vector value', function () { var m = DenseMatrix.diagonal([4, 3], [1, 2, 3]); assert.deepEqual(m._size, [4, 3]); assert.deepEqual( m.toArray(), [ [1, 0, 0], [0, 2, 0], [0, 0, 3], [0, 0, 0] ]); }); it('should create matrix (m x n), m > n, vector value, k > 0', function () { var m = DenseMatrix.diagonal([4, 3], [1, 2], 1); assert.deepEqual(m._size, [4, 3]); assert.deepEqual( m.toArray(), [ [0, 1, 0], [0, 0, 2], [0, 0, 0], [0, 0, 0] ]); }); it('should create matrix (m x n), m > n, vector value, k < 0', function () { var m = DenseMatrix.diagonal([4, 3], [1, 2, 3], -1); assert.deepEqual(m._size, [4, 3]); assert.deepEqual( m.toArray(), [ [0, 0, 0], [1, 0, 0], [0, 2, 0], [0, 0, 3] ]); }); it('should create matrix (m x n), m < n', function () { var m = DenseMatrix.diagonal([3, 4], 1); assert.deepEqual(m._size, [3, 4]); assert.deepEqual( m.toArray(), [ [1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0] ]); }); it('should create matrix (m x n), m < n, k > 0', function () { var m = DenseMatrix.diagonal([3, 4], 1, 1); assert.deepEqual(m._size, [3, 4]); assert.deepEqual( m.toArray(), [ [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1] ]); }); it('should create matrix (m x n), m < n, k < 0', function () { var m = DenseMatrix.diagonal([3, 4], 1, -1); assert.deepEqual(m._size, [3, 4]); assert.deepEqual( m.toArray(), [ [0, 0, 0, 0], [1, 0, 0, 0], [0, 1, 0, 0] ]); }); it('should create matrix (m x n), m < n, vector value', function () { var m = DenseMatrix.diagonal([3, 4], [1, 2, 3]); assert.deepEqual(m._size, [3, 4]); assert.deepEqual( m.toArray(), [ [1, 0, 0, 0], [0, 2, 0, 0], [0, 0, 3, 0] ]); }); it('should create matrix (m x n), m < n, vector value, k > 0', function () { var m = DenseMatrix.diagonal([3, 4], [1, 2, 3], 1); assert.deepEqual(m._size, [3, 4]); assert.deepEqual( m.toArray(), [ [0, 1, 0, 0], [0, 0, 2, 0], [0, 0, 0, 3] ]); }); it('should create matrix (m x n), m < n, vector value, k < 0', function () { var m = DenseMatrix.diagonal([3, 4], [1, 2], -1); assert.deepEqual(m._size, [3, 4]); assert.deepEqual( m.toArray(), [ [0, 0, 0, 0], [1, 0, 0, 0], [0, 2, 0, 0] ]); }); it('should get matrix diagonal (n x n)', function () { var m = new DenseMatrix( [ [1, 0, 0], [0, 1, 0], [0, 0, 1] ]); assert.deepEqual(m.diagonal(), new DenseMatrix([1, 1, 1])); }); it('should get matrix diagonal (n x n), k > 0', function () { var m = new DenseMatrix( [ [1, 2, 0], [0, 1, 3], [0, 0, 1] ]); assert.deepEqual(m.diagonal(1), new DenseMatrix([2, 3])); }); it('should get matrix diagonal (n x n), k < 0', function () { var m = new DenseMatrix( [ [1, 0, 0], [2, 1, 0], [0, 3, 1] ]); assert.deepEqual(m.diagonal(-1), new DenseMatrix([2, 3])); }); it('should get matrix diagonal (m x n), m > n', function () { var m = new DenseMatrix( [ [1, 0, 0], [0, 1, 0], [0, 0, 1], [0, 0, 0] ]); assert.deepEqual(m.diagonal(), new DenseMatrix([1, 1, 1])); }); it('should get matrix diagonal (m x n), m > n, k > 0', function () { var m = new DenseMatrix( [ [1, 2, 0], [0, 1, 3], [0, 0, 1], [0, 0, 0] ]); assert.deepEqual(m.diagonal(1), new DenseMatrix([2, 3])); }); it('should get matrix diagonal (m x n), m > n, k < 0', function () { var m = new DenseMatrix( [ [1, 0, 0], [2, 1, 0], [0, 3, 1], [0, 0, 4] ]); assert.deepEqual(m.diagonal(-1), new DenseMatrix([2, 3, 4])); }); it('should get matrix diagonal (m x n), m < n', function () { var m = new DenseMatrix( [ [1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0] ]); assert.deepEqual(m.diagonal(), new DenseMatrix([1, 1, 1])); }); it('should get matrix diagonal (m x n), m < n, k > 0', function () { var m = new DenseMatrix( [ [1, 2, 0, 0], [0, 1, 3, 0], [0, 0, 1, 4] ]); assert.deepEqual(m.diagonal(1), new DenseMatrix([2, 3, 4])); }); it('should get matrix diagonal (m x n), m < n, k < 0', function () { var m = new DenseMatrix( [ [1, 0, 0, 0], [2, 1, 0, 0], [4, 3, 1, 0] ]); assert.deepEqual(m.diagonal(-1), new DenseMatrix([2, 3])); assert.deepEqual(m.diagonal(-2), new DenseMatrix([4])); }); }); describe('swapRows', function () { it('should swap rows with values', function () { var m = new DenseMatrix( [ [1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12] ]); m.swapRows(1, 2); assert.deepEqual( m.valueOf(), [ [1, 2, 3], [7, 8, 9], [4, 5, 6], [10, 11, 12] ]); }); it('should swap row with value and no values', function () { var m = new DenseMatrix( [ [1, 2, 3], [4, 5, 6], [0, 0, 0], [10, 11, 12] ]); m.swapRows(1, 2); assert.deepEqual( m.valueOf(), [ [1, 2, 3], [0, 0, 0], [4, 5, 6], [10, 11, 12] ]); }); it('should swap row with no value and values', function () { var m = new DenseMatrix( [ [1, 2, 3], [4, 5, 6], [0, 0, 0], [10, 11, 12] ]); m.swapRows(2, 1); assert.deepEqual( m.valueOf(), [ [1, 2, 3], [0, 0, 0], [4, 5, 6], [10, 11, 12] ]); }); it('should swap rows with missing values', function () { var m = new DenseMatrix( [ [1, 2, 3], [0, 5, 0], [7, 0, 9], [10, 11, 12] ]); m.swapRows(2, 1); assert.deepEqual( m.valueOf(), [ [1, 2, 3], [7, 0, 9], [0, 5, 0], [10, 11, 12] ]); }); it('should swap last row with another row', function () { var m = new DenseMatrix( [ [1, 2, 3], [0, 5, 0], [7, 0, 9], [10, 11, 12] ]); m.swapRows(3, 1); assert.deepEqual( m.valueOf(), [ [1, 2, 3], [10, 11, 12], [7, 0, 9], [0, 5, 0] ]); }); it('should swap first row with another row', function () { var m = new DenseMatrix( [ [0, 2, 0], [0, 5, 0], [7, 0, 9], [10, 0, 0] ]); m.swapRows(0, 2); assert.deepEqual( m.valueOf(), [ [7, 0, 9], [0, 5, 0], [0, 2, 0], [10, 0, 0] ]); }); }); /** * Helper function to create an Array containing uninitialized values * Example: arr(uninit, uninit, 2); // [ , , 2 ] */ var uninit = {}; function arr() { var array = []; array.length = arguments.length; for (var i = 0; i < arguments.length; i++) { var value = arguments[i]; if (value !== uninit) { array[i] = value; } } return array; } });
'use strict'; var assert = require('assert'); var mocha = require('mocha'); var describe = mocha.describe; var it = mocha.it; var testutil = require('../testutil.js'); var loca = require('../../src/tables/loca.js'); describe('tables/loca.js', function() { it('can parse the short version', function() { var data = testutil.unhex('DEAD BEEF 0010 0100 80CE'); assert.deepEqual([32, 512, 2 * 0x80ce], loca.parse(data, 4, 2, true)); }); it('can parse the long version', function() { var data = testutil.unhex('DEADBEEF 00000010 00000100 ABCD5678'); assert.deepEqual([0x10, 0x100, 0xabcd5678], loca.parse(data, 4, 2, false)); }); });
/** * ag-grid - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components * @version v13.0.0 * @link http://www.ag-grid.com/ * @license MIT */ "use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; var __param = (this && this.__param) || function (paramIndex, decorator) { return function (target, key) { decorator(target, key, paramIndex); } }; Object.defineProperty(exports, "__esModule", { value: true }); var utils_1 = require("../utils"); var columnGroup_1 = require("../entities/columnGroup"); var column_1 = require("../entities/column"); var gridOptionsWrapper_1 = require("../gridOptionsWrapper"); var expressionService_1 = require("../valueService/expressionService"); var balancedColumnTreeBuilder_1 = require("./balancedColumnTreeBuilder"); var displayedGroupCreator_1 = require("./displayedGroupCreator"); var autoWidthCalculator_1 = require("../rendering/autoWidthCalculator"); var eventService_1 = require("../eventService"); var columnUtils_1 = require("./columnUtils"); var logger_1 = require("../logger"); var events_1 = require("../events"); var originalColumnGroup_1 = require("../entities/originalColumnGroup"); var groupInstanceIdCreator_1 = require("./groupInstanceIdCreator"); var context_1 = require("../context/context"); var gridPanel_1 = require("../gridPanel/gridPanel"); var columnAnimationService_1 = require("../rendering/columnAnimationService"); var autoGroupColService_1 = require("./autoGroupColService"); var valueCache_1 = require("../valueService/valueCache"); var gridApi_1 = require("../gridApi"); var ColumnApi = (function () { function ColumnApi() { } ColumnApi.prototype.sizeColumnsToFit = function (gridWidth) { this._columnController.sizeColumnsToFit(gridWidth); }; ColumnApi.prototype.setColumnGroupOpened = function (group, newValue, instanceId) { this._columnController.setColumnGroupOpened(group, newValue, instanceId); }; ColumnApi.prototype.getColumnGroup = function (name, instanceId) { return this._columnController.getColumnGroup(name, instanceId); }; ColumnApi.prototype.getDisplayNameForColumn = function (column, location) { return this._columnController.getDisplayNameForColumn(column, location); }; ColumnApi.prototype.getDisplayNameForColumnGroup = function (columnGroup, location) { return this._columnController.getDisplayNameForColumnGroup(columnGroup, location); }; ColumnApi.prototype.getColumn = function (key) { return this._columnController.getPrimaryColumn(key); }; ColumnApi.prototype.setColumnState = function (columnState) { return this._columnController.setColumnState(columnState); }; ColumnApi.prototype.getColumnState = function () { return this._columnController.getColumnState(); }; ColumnApi.prototype.resetColumnState = function () { this._columnController.resetColumnState(); }; ColumnApi.prototype.isPinning = function () { return this._columnController.isPinningLeft() || this._columnController.isPinningRight(); }; ColumnApi.prototype.isPinningLeft = function () { return this._columnController.isPinningLeft(); }; ColumnApi.prototype.isPinningRight = function () { return this._columnController.isPinningRight(); }; ColumnApi.prototype.getDisplayedColAfter = function (col) { return this._columnController.getDisplayedColAfter(col); }; ColumnApi.prototype.getDisplayedColBefore = function (col) { return this._columnController.getDisplayedColBefore(col); }; ColumnApi.prototype.setColumnVisible = function (key, visible) { this._columnController.setColumnVisible(key, visible); }; ColumnApi.prototype.setColumnsVisible = function (keys, visible) { this._columnController.setColumnsVisible(keys, visible); }; ColumnApi.prototype.setColumnPinned = function (key, pinned) { this._columnController.setColumnPinned(key, pinned); }; ColumnApi.prototype.setColumnsPinned = function (keys, pinned) { this._columnController.setColumnsPinned(keys, pinned); }; ColumnApi.prototype.getAllColumns = function () { return this._columnController.getAllPrimaryColumns(); }; ColumnApi.prototype.getAllGridColumns = function () { return this._columnController.getAllGridColumns(); }; ColumnApi.prototype.getDisplayedLeftColumns = function () { return this._columnController.getDisplayedLeftColumns(); }; ColumnApi.prototype.getDisplayedCenterColumns = function () { return this._columnController.getDisplayedCenterColumns(); }; ColumnApi.prototype.getDisplayedRightColumns = function () { return this._columnController.getDisplayedRightColumns(); }; ColumnApi.prototype.getAllDisplayedColumns = function () { return this._columnController.getAllDisplayedColumns(); }; ColumnApi.prototype.getAllDisplayedVirtualColumns = function () { return this._columnController.getAllDisplayedVirtualColumns(); }; ColumnApi.prototype.moveColumn = function (key, toIndex) { if (typeof key === 'number') { // moveColumn used to take indexes, so this is advising user who hasn't moved to new method name console.log('ag-Grid: you are using moveColumn(fromIndex, toIndex) - moveColumn takes a column key and a destination index, not two indexes, to move with indexes use moveColumnByIndex(from,to) instead'); this._columnController.moveColumnByIndex(key, toIndex); } else { this._columnController.moveColumn(key, toIndex); } }; ColumnApi.prototype.moveColumnByIndex = function (fromIndex, toIndex) { this._columnController.moveColumnByIndex(fromIndex, toIndex); }; ColumnApi.prototype.moveColumns = function (columnsToMoveKeys, toIndex) { this._columnController.moveColumns(columnsToMoveKeys, toIndex); }; ColumnApi.prototype.moveRowGroupColumn = function (fromIndex, toIndex) { this._columnController.moveRowGroupColumn(fromIndex, toIndex); }; ColumnApi.prototype.setColumnAggFunc = function (column, aggFunc) { this._columnController.setColumnAggFunc(column, aggFunc); }; ColumnApi.prototype.setColumnWidth = function (key, newWidth, finished) { if (finished === void 0) { finished = true; } this._columnController.setColumnWidth(key, newWidth, finished); }; ColumnApi.prototype.setPivotMode = function (pivotMode) { this._columnController.setPivotMode(pivotMode); }; ColumnApi.prototype.isPivotMode = function () { return this._columnController.isPivotMode(); }; ColumnApi.prototype.getSecondaryPivotColumn = function (pivotKeys, valueColKey) { return this._columnController.getSecondaryPivotColumn(pivotKeys, valueColKey); }; ColumnApi.prototype.setValueColumns = function (colKeys) { this._columnController.setValueColumns(colKeys); }; ColumnApi.prototype.getValueColumns = function () { return this._columnController.getValueColumns(); }; ColumnApi.prototype.removeValueColumn = function (colKey) { this._columnController.removeValueColumn(colKey); }; ColumnApi.prototype.removeValueColumns = function (colKeys) { this._columnController.removeValueColumns(colKeys); }; ColumnApi.prototype.addValueColumn = function (colKey) { this._columnController.addValueColumn(colKey); }; ColumnApi.prototype.addValueColumns = function (colKeys) { this._columnController.addValueColumns(colKeys); }; ColumnApi.prototype.setRowGroupColumns = function (colKeys) { this._columnController.setRowGroupColumns(colKeys); }; ColumnApi.prototype.removeRowGroupColumn = function (colKey) { this._columnController.removeRowGroupColumn(colKey); }; ColumnApi.prototype.removeRowGroupColumns = function (colKeys) { this._columnController.removeRowGroupColumns(colKeys); }; ColumnApi.prototype.addRowGroupColumn = function (colKey) { this._columnController.addRowGroupColumn(colKey); }; ColumnApi.prototype.addRowGroupColumns = function (colKeys) { this._columnController.addRowGroupColumns(colKeys); }; ColumnApi.prototype.getRowGroupColumns = function () { return this._columnController.getRowGroupColumns(); }; ColumnApi.prototype.setPivotColumns = function (colKeys) { this._columnController.setPivotColumns(colKeys); }; ColumnApi.prototype.removePivotColumn = function (colKey) { this._columnController.removePivotColumn(colKey); }; ColumnApi.prototype.removePivotColumns = function (colKeys) { this._columnController.removePivotColumns(colKeys); }; ColumnApi.prototype.addPivotColumn = function (colKey) { this._columnController.addPivotColumn(colKey); }; ColumnApi.prototype.addPivotColumns = function (colKeys) { this._columnController.addPivotColumns(colKeys); }; ColumnApi.prototype.getPivotColumns = function () { return this._columnController.getPivotColumns(); }; ColumnApi.prototype.getLeftDisplayedColumnGroups = function () { return this._columnController.getLeftDisplayedColumnGroups(); }; ColumnApi.prototype.getCenterDisplayedColumnGroups = function () { return this._columnController.getCenterDisplayedColumnGroups(); }; ColumnApi.prototype.getRightDisplayedColumnGroups = function () { return this._columnController.getRightDisplayedColumnGroups(); }; ColumnApi.prototype.getAllDisplayedColumnGroups = function () { return this._columnController.getAllDisplayedColumnGroups(); }; ColumnApi.prototype.autoSizeColumn = function (key) { return this._columnController.autoSizeColumn(key); }; ColumnApi.prototype.autoSizeColumns = function (keys) { return this._columnController.autoSizeColumns(keys); }; ColumnApi.prototype.autoSizeAllColumns = function () { this._columnController.autoSizeAllColumns(); }; ColumnApi.prototype.setSecondaryColumns = function (colDefs) { this._columnController.setSecondaryColumns(colDefs); }; // below goes through deprecated items, prints message to user, then calls the new version of the same method ColumnApi.prototype.columnGroupOpened = function (group, newValue) { console.error('ag-Grid: columnGroupOpened no longer exists, use setColumnGroupOpened'); this.setColumnGroupOpened(group, newValue); }; ColumnApi.prototype.hideColumns = function (colIds, hide) { console.error('ag-Grid: hideColumns is deprecated, use setColumnsVisible'); this._columnController.setColumnsVisible(colIds, !hide); }; ColumnApi.prototype.hideColumn = function (colId, hide) { console.error('ag-Grid: hideColumn is deprecated, use setColumnVisible'); this._columnController.setColumnVisible(colId, !hide); }; ColumnApi.prototype.setState = function (columnState) { console.error('ag-Grid: setState is deprecated, use setColumnState'); return this.setColumnState(columnState); }; ColumnApi.prototype.getState = function () { console.error('ag-Grid: getState is deprecated, use getColumnState'); return this.getColumnState(); }; ColumnApi.prototype.resetState = function () { console.error('ag-Grid: resetState is deprecated, use resetColumnState'); this.resetColumnState(); }; ColumnApi.prototype.getAggregationColumns = function () { console.error('ag-Grid: getAggregationColumns is deprecated, use getValueColumns'); return this._columnController.getValueColumns(); }; ColumnApi.prototype.removeAggregationColumn = function (colKey) { console.error('ag-Grid: removeAggregationColumn is deprecated, use removeValueColumn'); this._columnController.removeValueColumn(colKey); }; ColumnApi.prototype.removeAggregationColumns = function (colKeys) { console.error('ag-Grid: removeAggregationColumns is deprecated, use removeValueColumns'); this._columnController.removeValueColumns(colKeys); }; ColumnApi.prototype.addAggregationColumn = function (colKey) { console.error('ag-Grid: addAggregationColumn is deprecated, use addValueColumn'); this._columnController.addValueColumn(colKey); }; ColumnApi.prototype.addAggregationColumns = function (colKeys) { console.error('ag-Grid: addAggregationColumns is deprecated, use addValueColumns'); this._columnController.addValueColumns(colKeys); }; ColumnApi.prototype.setColumnAggFunction = function (column, aggFunc) { console.error('ag-Grid: setColumnAggFunction is deprecated, use setColumnAggFunc'); this._columnController.setColumnAggFunc(column, aggFunc); }; ColumnApi.prototype.getDisplayNameForCol = function (column) { console.error('ag-Grid: getDisplayNameForCol is deprecated, use getDisplayNameForColumn'); return this.getDisplayNameForColumn(column, null); }; __decorate([ context_1.Autowired('columnController'), __metadata("design:type", ColumnController) ], ColumnApi.prototype, "_columnController", void 0); ColumnApi = __decorate([ context_1.Bean('columnApi') ], ColumnApi); return ColumnApi; }()); exports.ColumnApi = ColumnApi; var ColumnController = (function () { function ColumnController() { // header row count, based on user provided columns this.primaryHeaderRowCount = 0; this.secondaryHeaderRowCount = 0; this.secondaryColumnsPresent = false; // header row count, either above, or based on pivoting if we are pivoting this.gridHeaderRowCount = 0; // these are the lists used by the rowRenderer to render nodes. almost the leaf nodes of the above // displayed trees, however it also takes into account if the groups are open or not. this.displayedLeftColumns = []; this.displayedRightColumns = []; this.displayedCenterColumns = []; // all three lists above combined this.allDisplayedColumns = []; // same as above, except trimmed down to only columns within the viewport this.allDisplayedVirtualColumns = []; this.allDisplayedCenterVirtualColumns = []; this.rowGroupColumns = []; this.valueColumns = []; this.pivotColumns = []; this.ready = false; this.autoGroupsNeedBuilding = false; this.pivotMode = false; this.bodyWidth = 0; this.leftWidth = 0; this.rightWidth = 0; this.bodyWidthDirty = true; } ColumnController.prototype.init = function () { this.pivotMode = this.gridOptionsWrapper.isPivotMode(); }; ColumnController.prototype.setVirtualViewportLeftAndRight = function () { if (this.gridOptionsWrapper.isEnableRtl()) { this.viewportLeft = this.bodyWidth - this.scrollPosition - this.scrollWidth; this.viewportRight = this.bodyWidth - this.scrollPosition; } else { this.viewportLeft = this.scrollPosition; this.viewportRight = this.scrollWidth + this.scrollPosition; } }; // used by clipboard service, to know what columns to paste into ColumnController.prototype.getDisplayedColumnsStartingAt = function (column) { var currentColumn = column; var result = []; while (utils_1.Utils.exists(currentColumn)) { result.push(currentColumn); currentColumn = this.getDisplayedColAfter(currentColumn); } return result; }; // checks what columns are currently displayed due to column virtualisation. fires an event // if the list of columns has changed. // + setColumnWidth(), setVirtualViewportPosition(), setColumnDefs(), sizeColumnsToFit() ColumnController.prototype.checkDisplayedVirtualColumns = function () { // check displayCenterColumnTree exists first, as it won't exist when grid is initialising if (utils_1.Utils.exists(this.displayedCenterColumns)) { var hashBefore = this.allDisplayedVirtualColumns.map(function (column) { return column.getId(); }).join('#'); this.updateVirtualSets(); var hashAfter = this.allDisplayedVirtualColumns.map(function (column) { return column.getId(); }).join('#'); if (hashBefore !== hashAfter) { var event_1 = { type: events_1.Events.EVENT_VIRTUAL_COLUMNS_CHANGED, api: this.gridApi, columnApi: this.columnApi }; this.eventService.dispatchEvent(event_1); } } }; ColumnController.prototype.setVirtualViewportPosition = function (scrollWidth, scrollPosition) { if (scrollWidth !== this.scrollWidth || scrollPosition !== this.scrollPosition || this.bodyWidthDirty) { this.scrollWidth = scrollWidth; this.scrollPosition = scrollPosition; // we need to call setVirtualViewportLeftAndRight() at least once after the body width changes, // as the viewport can stay the same, but in RTL, if body width changes, we need to work out the // virtual columns again this.bodyWidthDirty = true; this.setVirtualViewportLeftAndRight(); if (this.ready) { this.checkDisplayedVirtualColumns(); } } }; ColumnController.prototype.isPivotMode = function () { return this.pivotMode; }; ColumnController.prototype.setPivotMode = function (pivotMode) { if (pivotMode === this.pivotMode) { return; } this.pivotMode = pivotMode; this.updateDisplayedColumns(); var event = { type: events_1.Events.EVENT_COLUMN_PIVOT_MODE_CHANGED, api: this.gridApi, columnApi: this.columnApi }; this.eventService.dispatchEvent(event); }; ColumnController.prototype.getSecondaryPivotColumn = function (pivotKeys, valueColKey) { if (!this.secondaryColumnsPresent) { return null; } var valueColumnToFind = this.getPrimaryColumn(valueColKey); var foundColumn = null; this.secondaryColumns.forEach(function (column) { var thisPivotKeys = column.getColDef().pivotKeys; var pivotValueColumn = column.getColDef().pivotValueColumn; var pivotKeyMatches = utils_1.Utils.compareArrays(thisPivotKeys, pivotKeys); var pivotValueMatches = pivotValueColumn === valueColumnToFind; if (pivotKeyMatches && pivotValueMatches) { foundColumn = column; } }); return foundColumn; }; ColumnController.prototype.setBeans = function (loggerFactory) { this.logger = loggerFactory.create('ColumnController'); }; ColumnController.prototype.setFirstRightAndLastLeftPinned = function () { var lastLeft; var firstRight; if (this.gridOptionsWrapper.isEnableRtl()) { lastLeft = this.displayedLeftColumns ? this.displayedLeftColumns[0] : null; firstRight = this.displayedRightColumns ? this.displayedRightColumns[this.displayedRightColumns.length - 1] : null; } else { lastLeft = this.displayedLeftColumns ? this.displayedLeftColumns[this.displayedLeftColumns.length - 1] : null; firstRight = this.displayedRightColumns ? this.displayedRightColumns[0] : null; } this.gridColumns.forEach(function (column) { column.setLastLeftPinned(column === lastLeft); column.setFirstRightPinned(column === firstRight); }); }; ColumnController.prototype.autoSizeColumns = function (keys) { // because of column virtualisation, we can only do this function on columns that are // actually rendered, as non-rendered columns (outside the viewport and not rendered // due to column virtualisation) are not present. this can result in all rendered columns // getting narrowed, which in turn introduces more rendered columns on the RHS which // did not get autosized in the original run, leaving the visible grid with columns on // the LHS sized, but RHS no. so we keep looping through teh visible columns until // no more cols are available (rendered) to be resized var _this = this; // keep track of which cols we have resized in here var columnsAutosized = []; // initialise with anything except 0 so that while loop executs at least once var changesThisTimeAround = -1; while (changesThisTimeAround !== 0) { changesThisTimeAround = 0; this.actionOnGridColumns(keys, function (column) { // if already autosized, skip it if (columnsAutosized.indexOf(column) >= 0) { return; } // get how wide this col should be var preferredWidth = _this.autoWidthCalculator.getPreferredWidthForColumn(column); // preferredWidth = -1 if this col is not on the screen if (preferredWidth > 0) { var newWidth = _this.normaliseColumnWidth(column, preferredWidth); column.setActualWidth(newWidth); columnsAutosized.push(column); changesThisTimeAround++; } return true; }); } if (columnsAutosized.length > 0) { var event_2 = { type: events_1.Events.EVENT_COLUMN_RESIZED, columns: columnsAutosized, column: columnsAutosized.length === 1 ? columnsAutosized[0] : null, finished: true, api: this.gridApi, columnApi: this.columnApi }; this.eventService.dispatchEvent(event_2); } }; ColumnController.prototype.autoSizeColumn = function (key) { this.autoSizeColumns([key]); }; ColumnController.prototype.autoSizeAllColumns = function () { var allDisplayedColumns = this.getAllDisplayedColumns(); this.autoSizeColumns(allDisplayedColumns); }; ColumnController.prototype.getColumnsFromTree = function (rootColumns) { var result = []; recursiveFindColumns(rootColumns); return result; function recursiveFindColumns(childColumns) { for (var i = 0; i < childColumns.length; i++) { var child = childColumns[i]; if (child instanceof column_1.Column) { result.push(child); } else if (child instanceof originalColumnGroup_1.OriginalColumnGroup) { recursiveFindColumns(child.getChildren()); } } } }; ColumnController.prototype.getAllDisplayedColumnGroups = function () { if (this.displayedLeftColumnTree && this.displayedRightColumnTree && this.displayedCentreColumnTree) { return this.displayedLeftColumnTree .concat(this.displayedCentreColumnTree) .concat(this.displayedRightColumnTree); } else { return null; } }; // + columnSelectPanel ColumnController.prototype.getPrimaryColumnTree = function () { return this.primaryBalancedTree; }; // + gridPanel -> for resizing the body and setting top margin ColumnController.prototype.getHeaderRowCount = function () { return this.gridHeaderRowCount; }; // + headerRenderer -> setting pinned body width ColumnController.prototype.getLeftDisplayedColumnGroups = function () { return this.displayedLeftColumnTree; }; // + headerRenderer -> setting pinned body width ColumnController.prototype.getRightDisplayedColumnGroups = function () { return this.displayedRightColumnTree; }; // + headerRenderer -> setting pinned body width ColumnController.prototype.getCenterDisplayedColumnGroups = function () { return this.displayedCentreColumnTree; }; ColumnController.prototype.getDisplayedColumnGroups = function (type) { switch (type) { case column_1.Column.PINNED_LEFT: return this.getLeftDisplayedColumnGroups(); case column_1.Column.PINNED_RIGHT: return this.getRightDisplayedColumnGroups(); default: return this.getCenterDisplayedColumnGroups(); } }; // gridPanel -> ensureColumnVisible ColumnController.prototype.isColumnDisplayed = function (column) { return this.getAllDisplayedColumns().indexOf(column) >= 0; }; // + csvCreator ColumnController.prototype.getAllDisplayedColumns = function () { return this.allDisplayedColumns; }; ColumnController.prototype.getAllDisplayedVirtualColumns = function () { return this.allDisplayedVirtualColumns; }; ColumnController.prototype.getDisplayedLeftColumnsForRow = function (rowNode) { if (!this.colSpanActive) { return this.displayedLeftColumns; } else { return this.getDisplayedColumnsForRow(rowNode, this.displayedLeftColumns); } }; ColumnController.prototype.getDisplayedRightColumnsForRow = function (rowNode) { if (!this.colSpanActive) { return this.displayedRightColumns; } else { return this.getDisplayedColumnsForRow(rowNode, this.displayedRightColumns); } }; ColumnController.prototype.getDisplayedColumnsForRow = function (rowNode, displayedColumns, filterCallback, gapBeforeCallback) { var result = []; var lastConsideredCol = null; for (var i = 0; i < displayedColumns.length; i++) { var col = displayedColumns[i]; var colSpan = col.getColSpan(rowNode); if (colSpan > 1) { var colsToRemove = colSpan - 1; i += colsToRemove; } var filterPasses = filterCallback ? filterCallback(col) : true; if (filterPasses) { var gapBeforeColumn = gapBeforeCallback ? gapBeforeCallback(col) : false; var addInPreviousColumn = result.length === 0 && gapBeforeColumn && lastConsideredCol; if (addInPreviousColumn) { result.push(lastConsideredCol); } result.push(col); } lastConsideredCol = col; } return result; }; // + rowRenderer // if we are not column spanning, this just returns back the virtual centre columns, // however if we are column spanning, then different rows can have different virtual // columns, so we have to work out the list for each individual row. ColumnController.prototype.getAllDisplayedCenterVirtualColumnsForRow = function (rowNode) { var _this = this; if (!this.colSpanActive) { return this.allDisplayedCenterVirtualColumns; } var gapBeforeCallback = function (col) { return col.getLeft() > _this.viewportLeft; }; return this.getDisplayedColumnsForRow(rowNode, this.displayedCenterColumns, this.isColumnInViewport.bind(this), gapBeforeCallback); }; ColumnController.prototype.isColumnInViewport = function (col) { var columnLeft = col.getLeft(); var columnRight = col.getLeft() + col.getActualWidth(); var columnToMuchLeft = columnLeft < this.viewportLeft && columnRight < this.viewportLeft; var columnToMuchRight = columnLeft > this.viewportRight && columnRight > this.viewportRight; return !columnToMuchLeft && !columnToMuchRight; }; // used by: // + angularGrid -> setting pinned body width // todo: this needs to be cached ColumnController.prototype.getPinnedLeftContainerWidth = function () { return this.getWidthOfColsInList(this.displayedLeftColumns); }; // todo: this needs to be cached ColumnController.prototype.getPinnedRightContainerWidth = function () { return this.getWidthOfColsInList(this.displayedRightColumns); }; ColumnController.prototype.updatePrimaryColumnList = function (keys, masterList, actionIsAdd, columnCallback, eventType) { var _this = this; if (utils_1.Utils.missingOrEmpty(keys)) { return; } var atLeastOne = false; keys.forEach(function (key) { var columnToAdd = _this.getPrimaryColumn(key); if (!columnToAdd) { return; } if (actionIsAdd) { if (masterList.indexOf(columnToAdd) >= 0) { return; } masterList.push(columnToAdd); } else { if (masterList.indexOf(columnToAdd) < 0) { return; } utils_1.Utils.removeFromArray(masterList, columnToAdd); } columnCallback(columnToAdd); atLeastOne = true; }); if (!atLeastOne) { return; } this.updateDisplayedColumns(); var event = { type: eventType, columns: masterList, column: masterList.length === 1 ? masterList[0] : null, api: this.gridApi, columnApi: this.columnApi }; this.eventService.dispatchEvent(event); }; ColumnController.prototype.setRowGroupColumns = function (colKeys) { this.autoGroupsNeedBuilding = true; this.setPrimaryColumnList(colKeys, this.rowGroupColumns, events_1.Events.EVENT_COLUMN_ROW_GROUP_CHANGED, this.setRowGroupActive.bind(this)); }; ColumnController.prototype.setRowGroupActive = function (active, column) { if (active === column.isRowGroupActive()) { return; } column.setRowGroupActive(active); if (!active) { column.setVisible(true); } }; ColumnController.prototype.addRowGroupColumn = function (key) { this.addRowGroupColumns([key]); }; ColumnController.prototype.addRowGroupColumns = function (keys) { this.autoGroupsNeedBuilding = true; this.updatePrimaryColumnList(keys, this.rowGroupColumns, true, this.setRowGroupActive.bind(this, true), events_1.Events.EVENT_COLUMN_ROW_GROUP_CHANGED); }; ColumnController.prototype.removeRowGroupColumns = function (keys) { this.autoGroupsNeedBuilding = true; this.updatePrimaryColumnList(keys, this.rowGroupColumns, false, this.setRowGroupActive.bind(this, false), events_1.Events.EVENT_COLUMN_ROW_GROUP_CHANGED); }; ColumnController.prototype.removeRowGroupColumn = function (key) { this.removeRowGroupColumns([key]); }; ColumnController.prototype.addPivotColumns = function (keys) { this.updatePrimaryColumnList(keys, this.pivotColumns, true, function (column) { return column.setPivotActive(true); }, events_1.Events.EVENT_COLUMN_PIVOT_CHANGED); }; ColumnController.prototype.setPivotColumns = function (colKeys) { this.setPrimaryColumnList(colKeys, this.pivotColumns, events_1.Events.EVENT_COLUMN_PIVOT_CHANGED, function (added, column) { column.setPivotActive(added); }); }; ColumnController.prototype.addPivotColumn = function (key) { this.addPivotColumns([key]); }; ColumnController.prototype.removePivotColumns = function (keys) { this.updatePrimaryColumnList(keys, this.pivotColumns, false, function (column) { return column.setPivotActive(false); }, events_1.Events.EVENT_COLUMN_PIVOT_CHANGED); }; ColumnController.prototype.removePivotColumn = function (key) { this.removePivotColumns([key]); }; ColumnController.prototype.setPrimaryColumnList = function (colKeys, masterList, eventName, columnCallback) { var _this = this; masterList.length = 0; if (utils_1.Utils.exists(colKeys)) { colKeys.forEach(function (key) { var column = _this.getPrimaryColumn(key); masterList.push(column); }); } this.primaryColumns.forEach(function (column) { var added = masterList.indexOf(column) >= 0; columnCallback(added, column); }); this.updateDisplayedColumns(); var event = { type: eventName, columns: masterList, column: masterList.length === 1 ? masterList[0] : null, api: this.gridApi, columnApi: this.columnApi }; this.eventService.dispatchEvent(event); }; ColumnController.prototype.setValueColumns = function (colKeys) { this.setPrimaryColumnList(colKeys, this.valueColumns, events_1.Events.EVENT_COLUMN_VALUE_CHANGED, this.setValueActive.bind(this)); }; ColumnController.prototype.setValueActive = function (active, column) { if (active === column.isValueActive()) { return; } column.setValueActive(active); if (active && !column.getAggFunc()) { var defaultAggFunc = this.aggFuncService.getDefaultAggFunc(column); column.setAggFunc(defaultAggFunc); } }; ColumnController.prototype.addValueColumns = function (keys) { this.updatePrimaryColumnList(keys, this.valueColumns, true, this.setValueActive.bind(this, true), events_1.Events.EVENT_COLUMN_VALUE_CHANGED); }; ColumnController.prototype.addValueColumn = function (colKey) { this.addValueColumns([colKey]); }; ColumnController.prototype.removeValueColumn = function (colKey) { this.removeValueColumns([colKey]); }; ColumnController.prototype.removeValueColumns = function (keys) { this.updatePrimaryColumnList(keys, this.valueColumns, false, this.setValueActive.bind(this, false), events_1.Events.EVENT_COLUMN_VALUE_CHANGED); }; // returns the width we can set to this col, taking into consideration min and max widths ColumnController.prototype.normaliseColumnWidth = function (column, newWidth) { if (newWidth < column.getMinWidth()) { newWidth = column.getMinWidth(); } if (column.isGreaterThanMax(newWidth)) { newWidth = column.getMaxWidth(); } return newWidth; }; ColumnController.prototype.getPrimaryOrGridColumn = function (key) { var column = this.getPrimaryColumn(key); if (column) { return column; } else { return this.getGridColumn(key); } }; ColumnController.prototype.setColumnWidth = function (key, newWidth, finished) { var column = this.getPrimaryOrGridColumn(key); if (!column) { return; } newWidth = this.normaliseColumnWidth(column, newWidth); var widthChanged = column.getActualWidth() !== newWidth; if (widthChanged) { column.setActualWidth(newWidth); this.setLeftValues(); } this.updateBodyWidths(); this.checkDisplayedVirtualColumns(); // check for change first, to avoid unnecessary firing of events // however we always fire 'finished' events. this is important // when groups are resized, as if the group is changing slowly, // eg 1 pixel at a time, then each change will fire change events // in all the columns in the group, but only one with get the pixel. if (finished || widthChanged) { var event_3 = { type: events_1.Events.EVENT_COLUMN_RESIZED, columns: [column], column: column, finished: finished, api: this.gridApi, columnApi: this.columnApi }; this.eventService.dispatchEvent(event_3); } }; ColumnController.prototype.setColumnAggFunc = function (column, aggFunc) { column.setAggFunc(aggFunc); var event = { type: events_1.Events.EVENT_COLUMN_VALUE_CHANGED, columns: [column], column: column, api: this.gridApi, columnApi: this.columnApi }; this.eventService.dispatchEvent(event); }; ColumnController.prototype.moveRowGroupColumn = function (fromIndex, toIndex) { var column = this.rowGroupColumns[fromIndex]; this.rowGroupColumns.splice(fromIndex, 1); this.rowGroupColumns.splice(toIndex, 0, column); var event = { type: events_1.Events.EVENT_COLUMN_ROW_GROUP_CHANGED, columns: this.rowGroupColumns, column: this.rowGroupColumns.length === 1 ? this.rowGroupColumns[0] : null, api: this.gridApi, columnApi: this.columnApi }; this.eventService.dispatchEvent(event); }; ColumnController.prototype.moveColumns = function (columnsToMoveKeys, toIndex) { this.columnAnimationService.start(); if (toIndex > this.gridColumns.length - columnsToMoveKeys.length) { console.warn('ag-Grid: tried to insert columns in invalid location, toIndex = ' + toIndex); console.warn('ag-Grid: remember that you should not count the moving columns when calculating the new index'); return; } // we want to pull all the columns out first and put them into an ordered list var columnsToMove = this.getGridColumns(columnsToMoveKeys); var failedRules = !this.doesMovePassRules(columnsToMove, toIndex); if (failedRules) { return; } utils_1.Utils.moveInArray(this.gridColumns, columnsToMove, toIndex); this.updateDisplayedColumns(); var event = { type: events_1.Events.EVENT_COLUMN_MOVED, columns: columnsToMove, column: columnsToMove.length === 1 ? columnsToMove[0] : null, toIndex: toIndex, api: this.gridApi, columnApi: this.columnApi }; this.eventService.dispatchEvent(event); this.columnAnimationService.finish(); }; ColumnController.prototype.doesMovePassRules = function (columnsToMove, toIndex) { var allColumnsCopy = this.gridColumns.slice(); utils_1.Utils.moveInArray(allColumnsCopy, columnsToMove, toIndex); var rulesPass = true; this.columnUtils.depthFirstOriginalTreeSearch(this.gridBalancedTree, function (child) { if (!(child instanceof originalColumnGroup_1.OriginalColumnGroup)) { return; } var columnGroup = child; var marryChildren = columnGroup.getColGroupDef() && columnGroup.getColGroupDef().marryChildren; if (!marryChildren) { return; } var newIndexes = []; columnGroup.getLeafColumns().forEach(function (col) { var newColIndex = allColumnsCopy.indexOf(col); newIndexes.push(newColIndex); }); var maxIndex = Math.max.apply(Math, newIndexes); var minIndex = Math.min.apply(Math, newIndexes); // width is how far the first column in this group is away from the last column var spread = maxIndex - minIndex; var maxSpread = columnGroup.getLeafColumns().length - 1; // if the columns if (spread > maxSpread) { rulesPass = false; } // console.log(`maxIndex = ${maxIndex}, minIndex = ${minIndex}, spread = ${spread}, maxSpread = ${maxSpread}, fail = ${spread > (count-1)}`) // console.log(allColumnsCopy.map( col => col.getColDef().field).join(',')); }); return rulesPass; }; ColumnController.prototype.moveColumn = function (key, toIndex) { this.moveColumns([key], toIndex); }; ColumnController.prototype.moveColumnByIndex = function (fromIndex, toIndex) { var column = this.gridColumns[fromIndex]; this.moveColumn(column, toIndex); }; // used by: // + angularGrid -> for setting body width // + rowController -> setting main row widths (when inserting and resizing) // need to cache this ColumnController.prototype.getBodyContainerWidth = function () { return this.bodyWidth; }; ColumnController.prototype.getContainerWidth = function (pinned) { switch (pinned) { case column_1.Column.PINNED_LEFT: return this.leftWidth; case column_1.Column.PINNED_RIGHT: return this.rightWidth; default: return this.bodyWidth; } }; // after setColumnWidth or updateGroupsAndDisplayedColumns ColumnController.prototype.updateBodyWidths = function () { var newBodyWidth = this.getWidthOfColsInList(this.displayedCenterColumns); var newLeftWidth = this.getWidthOfColsInList(this.displayedLeftColumns); var newRightWidth = this.getWidthOfColsInList(this.displayedRightColumns); // this is used by virtual col calculation, for RTL only, as a change to body width can impact displayed // columns, due to RTL inverting the y coordinates this.bodyWidthDirty = this.bodyWidth !== newBodyWidth; var atLeastOneChanged = this.bodyWidth !== newBodyWidth || this.leftWidth !== newLeftWidth || this.rightWidth !== newRightWidth; if (atLeastOneChanged) { this.bodyWidth = newBodyWidth; this.leftWidth = newLeftWidth; this.rightWidth = newRightWidth; // when this fires, it is picked up by the gridPanel, which ends up in // gridPanel calling setWidthAndScrollPosition(), which in turn calls setVirtualViewportPosition() var event_4 = { type: events_1.Events.EVENT_DISPLAYED_COLUMNS_WIDTH_CHANGED, api: this.gridApi, columnApi: this.columnApi }; this.eventService.dispatchEvent(event_4); } }; // + rowController ColumnController.prototype.getValueColumns = function () { return this.valueColumns ? this.valueColumns : []; }; // + rowController ColumnController.prototype.getPivotColumns = function () { return this.pivotColumns ? this.pivotColumns : []; }; // + inMemoryRowModel ColumnController.prototype.isPivotActive = function () { return this.pivotColumns && this.pivotColumns.length > 0 && this.pivotMode; }; // + toolPanel ColumnController.prototype.getRowGroupColumns = function () { return this.rowGroupColumns ? this.rowGroupColumns : []; }; // + rowController -> while inserting rows ColumnController.prototype.getDisplayedCenterColumns = function () { return this.displayedCenterColumns; }; // + rowController -> while inserting rows ColumnController.prototype.getDisplayedLeftColumns = function () { return this.displayedLeftColumns; }; ColumnController.prototype.getDisplayedRightColumns = function () { return this.displayedRightColumns; }; ColumnController.prototype.getDisplayedColumns = function (type) { switch (type) { case column_1.Column.PINNED_LEFT: return this.getDisplayedLeftColumns(); case column_1.Column.PINNED_RIGHT: return this.getDisplayedRightColumns(); default: return this.getDisplayedCenterColumns(); } }; // used by: // + inMemoryRowController -> sorting, building quick filter text // + headerRenderer -> sorting (clearing icon) ColumnController.prototype.getAllPrimaryColumns = function () { return this.primaryColumns; }; // + moveColumnController ColumnController.prototype.getAllGridColumns = function () { return this.gridColumns; }; ColumnController.prototype.isEmpty = function () { return utils_1.Utils.missingOrEmpty(this.gridColumns); }; ColumnController.prototype.isRowGroupEmpty = function () { return utils_1.Utils.missingOrEmpty(this.rowGroupColumns); }; ColumnController.prototype.setColumnVisible = function (key, visible) { this.setColumnsVisible([key], visible); }; ColumnController.prototype.setColumnsVisible = function (keys, visible) { var _this = this; this.columnAnimationService.start(); this.actionOnGridColumns(keys, function (column) { column.setVisible(visible); return true; }, function () { var event = { type: events_1.Events.EVENT_COLUMN_VISIBLE, visible: visible, column: null, columns: null, api: _this.gridApi, columnApi: _this.columnApi }; return event; }); this.columnAnimationService.finish(); }; ColumnController.prototype.setColumnPinned = function (key, pinned) { this.setColumnsPinned([key], pinned); }; ColumnController.prototype.setColumnsPinned = function (keys, pinned) { var _this = this; this.columnAnimationService.start(); var actualPinned; if (pinned === true || pinned === column_1.Column.PINNED_LEFT) { actualPinned = column_1.Column.PINNED_LEFT; } else if (pinned === column_1.Column.PINNED_RIGHT) { actualPinned = column_1.Column.PINNED_RIGHT; } else { actualPinned = null; } this.actionOnGridColumns(keys, function (column) { column.setPinned(actualPinned); return true; }, function () { var event = { type: events_1.Events.EVENT_COLUMN_PINNED, pinned: actualPinned, column: null, columns: null, api: _this.gridApi, columnApi: _this.columnApi }; return event; }); this.columnAnimationService.finish(); }; // does an action on a set of columns. provides common functionality for looking up the // columns based on key, getting a list of effected columns, and then updated the event // with either one column (if it was just one col) or a list of columns // used by: autoResize, setVisible, setPinned ColumnController.prototype.actionOnGridColumns = function (// the column keys this action will be on keys, // the action to do - if this returns false, the column was skipped // and won't be included in the event action, // should return back a column event of the right type createEvent) { var _this = this; if (utils_1.Utils.missingOrEmpty(keys)) { return; } var updatedColumns = []; keys.forEach(function (key) { var column = _this.getGridColumn(key); if (!column) { return; } // need to check for false with type (ie !== instead of !=) // as not returning anything (undefined) would also be false var resultOfAction = action(column); if (resultOfAction !== false) { updatedColumns.push(column); } }); if (updatedColumns.length === 0) { return; } this.updateDisplayedColumns(); if (utils_1.Utils.exists(createEvent)) { var event_5 = createEvent(); event_5.columns = updatedColumns; event_5.column = updatedColumns.length === 1 ? updatedColumns[0] : null; this.eventService.dispatchEvent(event_5); } }; ColumnController.prototype.getDisplayedColBefore = function (col) { var allDisplayedColumns = this.getAllDisplayedColumns(); var oldIndex = allDisplayedColumns.indexOf(col); if (oldIndex > 0) { return allDisplayedColumns[oldIndex - 1]; } else { return null; } }; // used by: // + rowRenderer -> for navigation ColumnController.prototype.getDisplayedColAfter = function (col) { var allDisplayedColumns = this.getAllDisplayedColumns(); var oldIndex = allDisplayedColumns.indexOf(col); if (oldIndex < (allDisplayedColumns.length - 1)) { return allDisplayedColumns[oldIndex + 1]; } else { return null; } }; ColumnController.prototype.isPinningLeft = function () { return this.displayedLeftColumns.length > 0; }; ColumnController.prototype.isPinningRight = function () { return this.displayedRightColumns.length > 0; }; ColumnController.prototype.getPrimaryAndSecondaryAndAutoColumns = function () { var result = this.primaryColumns ? this.primaryColumns.slice(0) : []; if (utils_1.Utils.exists(this.groupAutoColumns)) { this.groupAutoColumns.forEach(function (col) { return result.push(col); }); } if (this.secondaryColumnsPresent) { this.secondaryColumns.forEach(function (column) { return result.push(column); }); } return result; }; ColumnController.prototype.createStateItemFromColumn = function (column) { var rowGroupIndex = column.isRowGroupActive() ? this.rowGroupColumns.indexOf(column) : null; var pivotIndex = column.isPivotActive() ? this.pivotColumns.indexOf(column) : null; var aggFunc = column.isValueActive() ? column.getAggFunc() : null; var resultItem = { colId: column.getColId(), hide: !column.isVisible(), aggFunc: aggFunc, width: column.getActualWidth(), pivotIndex: pivotIndex, pinned: column.getPinned(), rowGroupIndex: rowGroupIndex }; return resultItem; }; ColumnController.prototype.getColumnState = function () { if (utils_1.Utils.missing(this.primaryColumns)) { return []; } var columnStateList = this.primaryColumns.map(this.createStateItemFromColumn.bind(this)); if (!this.pivotMode) { this.orderColumnStateList(columnStateList); } return columnStateList; }; ColumnController.prototype.orderColumnStateList = function (columnStateList) { var gridColumnIds = this.gridColumns.map(function (column) { return column.getColId(); }); columnStateList.sort(function (itemA, itemB) { var posA = gridColumnIds.indexOf(itemA.colId); var posB = gridColumnIds.indexOf(itemB.colId); return posA - posB; }); }; ColumnController.prototype.resetColumnState = function () { // we can't use 'allColumns' as the order might of messed up, so get the primary ordered list var primaryColumns = this.getColumnsFromTree(this.primaryBalancedTree); var state = []; if (primaryColumns) { primaryColumns.forEach(function (column) { state.push({ colId: column.getColId(), aggFunc: column.getColDef().aggFunc, hide: column.getColDef().hide, pinned: column.getColDef().pinned, rowGroupIndex: column.getColDef().rowGroupIndex, pivotIndex: column.getColDef().pivotIndex, width: column.getColDef().width }); }); } this.setColumnState(state); }; ColumnController.prototype.setColumnState = function (columnState) { var _this = this; if (utils_1.Utils.missingOrEmpty(this.primaryColumns)) { return false; } this.autoGroupsNeedBuilding = true; // at the end below, this list will have all columns we got no state for var columnsWithNoState = this.primaryColumns.slice(); this.rowGroupColumns = []; this.valueColumns = []; this.pivotColumns = []; var success = true; var rowGroupIndexes = {}; var pivotIndexes = {}; if (columnState) { columnState.forEach(function (stateItem) { var column = _this.getPrimaryColumn(stateItem.colId); if (!column) { console.warn('ag-grid: column ' + stateItem.colId + ' not found'); success = false; } else { _this.syncColumnWithStateItem(column, stateItem, rowGroupIndexes, pivotIndexes); utils_1.Utils.removeFromArray(columnsWithNoState, column); } }); } // anything left over, we got no data for, so add in the column as non-value, non-rowGroup and hidden columnsWithNoState.forEach(this.syncColumnWithNoState.bind(this)); // sort the lists according to the indexes that were provided this.rowGroupColumns.sort(this.sortColumnListUsingIndexes.bind(this, rowGroupIndexes)); this.pivotColumns.sort(this.sortColumnListUsingIndexes.bind(this, pivotIndexes)); this.copyDownGridColumns(); var orderOfColIds = columnState.map(function (stateItem) { return stateItem.colId; }); this.gridColumns.sort(function (colA, colB) { var indexA = orderOfColIds.indexOf(colA.getId()); var indexB = orderOfColIds.indexOf(colB.getId()); return indexA - indexB; }); this.updateDisplayedColumns(); var event = { type: events_1.Events.EVENT_COLUMN_EVERYTHING_CHANGED, api: this.gridApi, columnApi: this.columnApi }; this.eventService.dispatchEvent(event); return success; }; ColumnController.prototype.sortColumnListUsingIndexes = function (indexes, colA, colB) { var indexA = indexes[colA.getId()]; var indexB = indexes[colB.getId()]; return indexA - indexB; }; ColumnController.prototype.syncColumnWithNoState = function (column) { column.setVisible(false); column.setAggFunc(null); column.setPinned(null); column.setRowGroupActive(false); column.setPivotActive(false); column.setValueActive(false); }; ColumnController.prototype.syncColumnWithStateItem = function (column, stateItem, rowGroupIndexes, pivotIndexes) { // following ensures we are left with boolean true or false, eg converts (null, undefined, 0) all to true column.setVisible(!stateItem.hide); // sets pinned to 'left' or 'right' column.setPinned(stateItem.pinned); // if width provided and valid, use it, otherwise stick with the old width if (stateItem.width >= this.gridOptionsWrapper.getMinColWidth()) { column.setActualWidth(stateItem.width); } if (typeof stateItem.aggFunc === 'string') { column.setAggFunc(stateItem.aggFunc); column.setValueActive(true); this.valueColumns.push(column); } else { if (utils_1.Utils.exists(stateItem.aggFunc)) { console.warn('ag-Grid: stateItem.aggFunc must be a string. if using your own aggregation ' + 'functions, register the functions first before using them in get/set state. This is because it is' + 'intended for the column state to be stored and retrieved as simple JSON.'); } column.setAggFunc(null); column.setValueActive(false); } if (typeof stateItem.rowGroupIndex === 'number') { this.rowGroupColumns.push(column); column.setRowGroupActive(true); rowGroupIndexes[column.getId()] = stateItem.rowGroupIndex; } else { column.setRowGroupActive(false); } if (typeof stateItem.pivotIndex === 'number') { this.pivotColumns.push(column); column.setPivotActive(true); pivotIndexes[column.getId()] = stateItem.pivotIndex; } else { column.setPivotActive(false); } }; ColumnController.prototype.getGridColumns = function (keys) { return this.getColumns(keys, this.getGridColumn.bind(this)); }; ColumnController.prototype.getColumns = function (keys, columnLookupCallback) { var foundColumns = []; if (keys) { keys.forEach(function (key) { var column = columnLookupCallback(key); if (column) { foundColumns.push(column); } }); } return foundColumns; }; // used by growGroupPanel ColumnController.prototype.getColumnWithValidation = function (key) { var column = this.getPrimaryColumn(key); if (!column) { console.warn('ag-Grid: could not find column ' + column); } return column; }; ColumnController.prototype.getPrimaryColumn = function (key) { return this.getColumn(key, this.primaryColumns); }; ColumnController.prototype.getGridColumn = function (key) { return this.getColumn(key, this.gridColumns); }; ColumnController.prototype.getColumn = function (key, columnList) { if (!key) { return null; } for (var i = 0; i < columnList.length; i++) { if (this.columnsMatch(columnList[i], key)) { return columnList[i]; } } return this.getAutoColumn(key); }; ColumnController.prototype.getAutoColumn = function (key) { var _this = this; if (!utils_1.Utils.exists(this.groupAutoColumns) || utils_1.Utils.missing(this.groupAutoColumns)) { return null; } return utils_1.Utils.find(this.groupAutoColumns, function (groupCol) { return _this.columnsMatch(groupCol, key); }); }; ColumnController.prototype.columnsMatch = function (column, key) { var columnMatches = column === key; var colDefMatches = column.getColDef() === key; var idMatches = column.getColId() == key; return columnMatches || colDefMatches || idMatches; }; ColumnController.prototype.getDisplayNameForColumn = function (column, location, includeAggFunc) { if (includeAggFunc === void 0) { includeAggFunc = false; } var headerName = this.getHeaderName(column.getColDef(), column, null, location); if (includeAggFunc) { return this.wrapHeaderNameWithAggFunc(column, headerName); } else { return headerName; } }; ColumnController.prototype.getDisplayNameForColumnGroup = function (columnGroup, location) { var colGroupDef = columnGroup.getOriginalColumnGroup().getColGroupDef(); if (colGroupDef) { return this.getHeaderName(colGroupDef, null, columnGroup, location); } else { return null; } }; // location is where the column is going to appear, ie who is calling us ColumnController.prototype.getHeaderName = function (colDef, column, columnGroup, location) { var headerValueGetter = colDef.headerValueGetter; if (headerValueGetter) { var params = { colDef: colDef, column: column, columnGroup: columnGroup, location: location, api: this.gridOptionsWrapper.getApi(), context: this.gridOptionsWrapper.getContext() }; if (typeof headerValueGetter === 'function') { // valueGetter is a function, so just call it return headerValueGetter(params); } else if (typeof headerValueGetter === 'string') { // valueGetter is an expression, so execute the expression return this.expressionService.evaluate(headerValueGetter, params); } else { console.warn('ag-grid: headerValueGetter must be a function or a string'); return ''; } } else { return colDef.headerName; } }; /* private getHeaderGroupName(columnGroup: ColumnGroup): string { let colGroupDef = columnGroup.getOriginalColumnGroup().getColGroupDef(); let headerValueGetter = colGroupDef.headerValueGetter; if (headerValueGetter) { let params = { columnGroup: columnGroup, colDef: colGroupDef, api: this.gridOptionsWrapper.getApi(), context: this.gridOptionsWrapper.getContext() }; if (typeof headerValueGetter === 'function') { // valueGetter is a function, so just call it return headerValueGetter(params); } else if (typeof headerValueGetter === 'string') { // valueGetter is an expression, so execute the expression return this.expressionService.evaluate(headerValueGetter, params); } else { console.warn('ag-grid: headerValueGetter must be a function or a string'); return ''; } } else { return colGroupDef.headerName; } } */ ColumnController.prototype.wrapHeaderNameWithAggFunc = function (column, headerName) { if (this.gridOptionsWrapper.isSuppressAggFuncInHeader()) { return headerName; } // only columns with aggregation active can have aggregations var pivotValueColumn = column.getColDef().pivotValueColumn; var pivotActiveOnThisColumn = utils_1.Utils.exists(pivotValueColumn); var aggFunc = null; var aggFuncFound; // otherwise we have a measure that is active, and we are doing aggregation on it if (pivotActiveOnThisColumn) { aggFunc = pivotValueColumn.getAggFunc(); aggFuncFound = true; } else { var measureActive = column.isValueActive(); var aggregationPresent = this.pivotMode || !this.isRowGroupEmpty(); if (measureActive && aggregationPresent) { aggFunc = column.getAggFunc(); aggFuncFound = true; } else { aggFuncFound = false; } } if (aggFuncFound) { var aggFuncString = (typeof aggFunc === 'string') ? aggFunc : 'func'; return aggFuncString + "(" + headerName + ")"; } else { return headerName; } }; // returns the group with matching colId and instanceId. If instanceId is missing, // matches only on the colId. ColumnController.prototype.getColumnGroup = function (colId, instanceId) { if (!colId) { return null; } if (colId instanceof columnGroup_1.ColumnGroup) { return colId; } var allColumnGroups = this.getAllDisplayedColumnGroups(); var checkInstanceId = typeof instanceId === 'number'; var result = null; this.columnUtils.depthFirstAllColumnTreeSearch(allColumnGroups, function (child) { if (child instanceof columnGroup_1.ColumnGroup) { var columnGroup = child; var matched = void 0; if (checkInstanceId) { matched = colId === columnGroup.getGroupId() && instanceId === columnGroup.getInstanceId(); } else { matched = colId === columnGroup.getGroupId(); } if (matched) { result = columnGroup; } } }); return result; }; ColumnController.prototype.setColumnDefs = function (columnDefs) { // always invalidate cache on changing columns, as the column id's for the new columns // could overlap with the old id's, so the cache would return old values for new columns. this.valueCache.expire(); // NOTE ================== // we should be destroying the existing columns and groups if they exist, for example, the original column // group adds a listener to the columns, it should be also removing the listeners this.autoGroupsNeedBuilding = true; var balancedTreeResult = this.balancedColumnTreeBuilder.createBalancedColumnGroups(columnDefs, true); this.primaryBalancedTree = balancedTreeResult.balancedTree; this.primaryHeaderRowCount = balancedTreeResult.treeDept + 1; this.primaryColumns = this.getColumnsFromTree(this.primaryBalancedTree); this.extractRowGroupColumns(); this.extractPivotColumns(); this.createValueColumns(); this.copyDownGridColumns(); this.updateDisplayedColumns(); this.checkDisplayedVirtualColumns(); this.ready = true; var eventEverythingChanged = { type: events_1.Events.EVENT_COLUMN_EVERYTHING_CHANGED, api: this.gridApi, columnApi: this.columnApi }; this.eventService.dispatchEvent(eventEverythingChanged); var newColumnsLoadedEvent = { type: events_1.Events.EVENT_NEW_COLUMNS_LOADED, api: this.gridApi, columnApi: this.columnApi }; this.eventService.dispatchEvent(newColumnsLoadedEvent); }; ColumnController.prototype.isReady = function () { return this.ready; }; ColumnController.prototype.extractRowGroupColumns = function () { var _this = this; this.rowGroupColumns.forEach(function (column) { return column.setRowGroupActive(false); }); this.rowGroupColumns = []; // pull out items with rowGroupIndex this.primaryColumns.forEach(function (column) { if (typeof column.getColDef().rowGroupIndex === 'number') { _this.rowGroupColumns.push(column); column.setRowGroupActive(true); } }); // then sort them this.rowGroupColumns.sort(function (colA, colB) { return colA.getColDef().rowGroupIndex - colB.getColDef().rowGroupIndex; }); // now just pull out items rowGroup, they will be added at the end // after the indexed ones, but in the order the columns appear this.primaryColumns.forEach(function (column) { if (column.getColDef().rowGroup) { // if user already specified rowGroupIndex then we skip it as this col already included if (_this.rowGroupColumns.indexOf(column) >= 0) { return; } _this.rowGroupColumns.push(column); column.setRowGroupActive(true); } }); }; ColumnController.prototype.extractPivotColumns = function () { var _this = this; this.pivotColumns.forEach(function (column) { return column.setPivotActive(false); }); this.pivotColumns = []; // pull out items with pivotIndex this.primaryColumns.forEach(function (column) { if (typeof column.getColDef().pivotIndex === 'number') { _this.pivotColumns.push(column); column.setPivotActive(true); } }); // then sort them this.pivotColumns.sort(function (colA, colB) { return colA.getColDef().pivotIndex - colB.getColDef().pivotIndex; }); // now check the boolean equivalent this.primaryColumns.forEach(function (column) { if (column.getColDef().pivot) { // if user already specified pivotIndex then we skip it as this col already included if (_this.pivotColumns.indexOf(column) >= 0) { return; } _this.pivotColumns.push(column); column.setPivotActive(true); } }); }; // called by headerRenderer - when a header is opened or closed ColumnController.prototype.setColumnGroupOpened = function (passedGroup, newValue, instanceId) { this.columnAnimationService.start(); var groupToUse = this.getColumnGroup(passedGroup, instanceId); if (!groupToUse) { return; } this.logger.log('columnGroupOpened(' + groupToUse.getGroupId() + ',' + newValue + ')'); groupToUse.setExpanded(newValue); this.updateGroupsAndDisplayedColumns(); var event = { type: events_1.Events.EVENT_COLUMN_GROUP_OPENED, columnGroup: groupToUse, api: this.gridApi, columnApi: this.columnApi }; this.eventService.dispatchEvent(event); this.columnAnimationService.finish(); }; // used by updateModel ColumnController.prototype.getColumnGroupState = function () { var groupState = {}; this.columnUtils.depthFirstDisplayedColumnTreeSearch(this.getAllDisplayedColumnGroups(), function (child) { if (child instanceof columnGroup_1.ColumnGroup) { var columnGroup = child; var key = columnGroup.getGroupId(); // if more than one instance of the group, we only record the state of the first item if (!groupState.hasOwnProperty(key)) { groupState[key] = columnGroup.isExpanded(); } } }); return groupState; }; // used by updateModel ColumnController.prototype.setColumnGroupState = function (groupState) { this.columnUtils.depthFirstDisplayedColumnTreeSearch(this.getAllDisplayedColumnGroups(), function (child) { if (child instanceof columnGroup_1.ColumnGroup) { var columnGroup = child; var key = columnGroup.getGroupId(); var shouldExpandGroup = groupState[key] === true && columnGroup.isExpandable(); if (shouldExpandGroup) { columnGroup.setExpanded(true); } } }); }; ColumnController.prototype.calculateColumnsForDisplay = function () { var columnsForDisplay; if (this.pivotMode && !this.secondaryColumnsPresent) { // pivot mode is on, but we are not pivoting, so we only // show columns we are aggregating on columnsForDisplay = this.createColumnsToDisplayFromValueColumns(); } else { // otherwise continue as normal. this can be working on the primary // or secondary columns, whatever the gridColumns are set to columnsForDisplay = utils_1.Utils.filter(this.gridColumns, function (column) { return column.isVisible(); }); } this.createGroupAutoColumnsIfNeeded(); if (utils_1.Utils.exists(this.groupAutoColumns)) { columnsForDisplay = this.groupAutoColumns.concat(columnsForDisplay); } return columnsForDisplay; }; ColumnController.prototype.checkColSpanActiveInCols = function (columns) { var result = false; columns.forEach(function (col) { if (utils_1.Utils.exists(col.getColDef().colSpan)) { result = true; } }); return result; }; ColumnController.prototype.calculateColumnsForGroupDisplay = function () { var _this = this; this.groupDisplayColumns = []; var checkFunc = function (col) { var colDef = col.getColDef(); if (colDef && utils_1.Utils.exists(colDef.showRowGroup)) { _this.groupDisplayColumns.push(col); } }; this.gridColumns.forEach(checkFunc); if (this.groupAutoColumns) { this.groupAutoColumns.forEach(checkFunc); } }; ColumnController.prototype.getGroupDisplayColumns = function () { return this.groupDisplayColumns; }; ColumnController.prototype.createColumnsToDisplayFromValueColumns = function () { var _this = this; // make a copy of the value columns, so we have to side effects var result = this.valueColumns.slice(); // order the columns as per the grid columns. having the order is // important as without it, reordering of columns would have no impact result.sort(function (colA, colB) { return _this.gridColumns.indexOf(colA) - _this.gridColumns.indexOf(colB); }); return result; }; ColumnController.prototype.updateDisplayedColumns = function () { // save opened / closed state var oldGroupState = this.getColumnGroupState(); var columnsForDisplay = this.calculateColumnsForDisplay(); this.buildDisplayedTrees(columnsForDisplay); // restore opened / closed state this.setColumnGroupState(oldGroupState); this.calculateColumnsForGroupDisplay(); // this is also called when a group is opened or closed this.updateGroupsAndDisplayedColumns(); this.setFirstRightAndLastLeftPinned(); }; ColumnController.prototype.isSecondaryColumnsPresent = function () { return this.secondaryColumnsPresent; }; ColumnController.prototype.setSecondaryColumns = function (colDefs) { var newColsPresent = colDefs && colDefs.length > 0; // if not cols passed, and we had to cols anyway, then do nothing if (!newColsPresent && !this.secondaryColumnsPresent) { return; } if (newColsPresent) { this.processSecondaryColumnDefinitions(colDefs); var balancedTreeResult = this.balancedColumnTreeBuilder.createBalancedColumnGroups(colDefs, false); this.secondaryBalancedTree = balancedTreeResult.balancedTree; this.secondaryHeaderRowCount = balancedTreeResult.treeDept + 1; this.secondaryColumns = this.getColumnsFromTree(this.secondaryBalancedTree); this.secondaryColumnsPresent = true; } else { this.secondaryBalancedTree = null; this.secondaryHeaderRowCount = -1; this.secondaryColumns = null; this.secondaryColumnsPresent = false; } this.copyDownGridColumns(); this.updateDisplayedColumns(); }; ColumnController.prototype.processSecondaryColumnDefinitions = function (colDefs) { var columnCallback = this.gridOptionsWrapper.getProcessSecondaryColDefFunc(); var groupCallback = this.gridOptionsWrapper.getProcessSecondaryColGroupDefFunc(); if (!columnCallback && !groupCallback) { return; } searchForColDefs(colDefs); function searchForColDefs(colDefs2) { colDefs2.forEach(function (abstractColDef) { var isGroup = utils_1.Utils.exists(abstractColDef.children); if (isGroup) { var colGroupDef = abstractColDef; if (groupCallback) { groupCallback(colGroupDef); } searchForColDefs(colGroupDef.children); } else { var colDef = abstractColDef; if (columnCallback) { columnCallback(colDef); } } }); } }; // called from: setColumnState, setColumnDefs, setAlternativeColumnDefs ColumnController.prototype.copyDownGridColumns = function () { if (this.secondaryColumns) { this.gridBalancedTree = this.secondaryBalancedTree.slice(); this.gridHeaderRowCount = this.secondaryHeaderRowCount; this.gridColumns = this.secondaryColumns.slice(); } else { this.gridBalancedTree = this.primaryBalancedTree.slice(); this.gridHeaderRowCount = this.primaryHeaderRowCount; this.gridColumns = this.primaryColumns.slice(); } this.clearDisplayedColumns(); this.colSpanActive = this.checkColSpanActiveInCols(this.gridColumns); var event = { type: events_1.Events.EVENT_GRID_COLUMNS_CHANGED, api: this.gridApi, columnApi: this.columnApi }; this.eventService.dispatchEvent(event); }; // gets called after we copy down grid columns, to make sure any part of the gui // that tries to draw, eg the header, it will get empty lists of columns rather // than stale columns. for example, the header will received gridColumnsChanged // event, so will try and draw, but it will draw successfully when it acts on the // virtualColumnsChanged event ColumnController.prototype.clearDisplayedColumns = function () { this.displayedLeftColumnTree = []; this.displayedRightColumnTree = []; this.displayedCentreColumnTree = []; this.displayedLeftHeaderRows = {}; this.displayedRightHeaderRows = {}; this.displayedCentreHeaderRows = {}; this.displayedLeftColumns = []; this.displayedRightColumns = []; this.displayedCenterColumns = []; this.allDisplayedColumns = []; this.allDisplayedVirtualColumns = []; }; ColumnController.prototype.updateGroupsAndDisplayedColumns = function () { this.updateGroups(); this.updateDisplayedColumnsFromTrees(); this.updateVirtualSets(); this.updateBodyWidths(); // this event is picked up by the gui, headerRenderer and rowRenderer, to recalculate what columns to display var event = { type: events_1.Events.EVENT_DISPLAYED_COLUMNS_CHANGED, api: this.gridApi, columnApi: this.columnApi }; this.eventService.dispatchEvent(event); }; ColumnController.prototype.updateDisplayedColumnsFromTrees = function () { this.addToDisplayedColumns(this.displayedLeftColumnTree, this.displayedLeftColumns); this.addToDisplayedColumns(this.displayedCentreColumnTree, this.displayedCenterColumns); this.addToDisplayedColumns(this.displayedRightColumnTree, this.displayedRightColumns); this.setupAllDisplayedColumns(); this.setLeftValues(); }; ColumnController.prototype.setupAllDisplayedColumns = function () { if (this.gridOptionsWrapper.isEnableRtl()) { this.allDisplayedColumns = this.displayedRightColumns .concat(this.displayedCenterColumns) .concat(this.displayedLeftColumns); } else { this.allDisplayedColumns = this.displayedLeftColumns .concat(this.displayedCenterColumns) .concat(this.displayedRightColumns); } }; // sets the left pixel position of each column ColumnController.prototype.setLeftValues = function () { this.setLeftValuesOfColumns(); this.setLeftValuesOfGroups(); }; ColumnController.prototype.setLeftValuesOfColumns = function () { var _this = this; // go through each list of displayed columns var allColumns = this.primaryColumns.slice(0); // let totalColumnWidth = this.getWidthOfColsInList() var doingRtl = this.gridOptionsWrapper.isEnableRtl(); [this.displayedLeftColumns, this.displayedRightColumns, this.displayedCenterColumns].forEach(function (columns) { if (doingRtl) { // when doing RTL, we start at the top most pixel (ie RHS) and work backwards var left_1 = _this.getWidthOfColsInList(columns); columns.forEach(function (column) { left_1 -= column.getActualWidth(); column.setLeft(left_1); }); } else { // otherwise normal LTR, we start at zero var left_2 = 0; columns.forEach(function (column) { column.setLeft(left_2); left_2 += column.getActualWidth(); }); } utils_1.Utils.removeAllFromArray(allColumns, columns); }); // items left in allColumns are columns not displayed, so remove the left position. this is // important for the rows, as if a col is made visible, then taken out, then made visible again, // we don't want the animation of the cell floating in from the old position, whatever that was. allColumns.forEach(function (column) { column.setLeft(null); }); }; ColumnController.prototype.setLeftValuesOfGroups = function () { // a groups left value is the lest left value of it's children [this.displayedLeftColumnTree, this.displayedRightColumnTree, this.displayedCentreColumnTree].forEach(function (columns) { columns.forEach(function (column) { if (column instanceof columnGroup_1.ColumnGroup) { var columnGroup = column; columnGroup.checkLeft(); } }); }); }; ColumnController.prototype.addToDisplayedColumns = function (displayedColumnTree, displayedColumns) { displayedColumns.length = 0; this.columnUtils.depthFirstDisplayedColumnTreeSearch(displayedColumnTree, function (child) { if (child instanceof column_1.Column) { displayedColumns.push(child); } }); }; ColumnController.prototype.updateDisplayedCenterVirtualColumns = function () { var skipVirtualisation = this.gridOptionsWrapper.isSuppressColumnVirtualisation() || this.gridOptionsWrapper.isForPrint(); if (skipVirtualisation) { // no virtualisation, so don't filter this.allDisplayedCenterVirtualColumns = this.displayedCenterColumns; } else { // filter out what should be visible this.allDisplayedCenterVirtualColumns = this.filterOutColumnsWithinViewport(); } this.allDisplayedVirtualColumns = this.allDisplayedCenterVirtualColumns .concat(this.displayedLeftColumns) .concat(this.displayedRightColumns); // return map of virtual col id's, for easy lookup when building the groups. // the map will be colId=>true, ie col id's mapping to 'true'. var result = {}; this.allDisplayedVirtualColumns.forEach(function (col) { result[col.getId()] = true; }); return result; }; ColumnController.prototype.getVirtualHeaderGroupRow = function (type, dept) { var result; switch (type) { case column_1.Column.PINNED_LEFT: result = this.displayedLeftHeaderRows[dept]; break; case column_1.Column.PINNED_RIGHT: result = this.displayedRightHeaderRows[dept]; break; default: result = this.displayedCentreHeaderRows[dept]; break; } if (utils_1.Utils.missing(result)) { result = []; } return result; }; ColumnController.prototype.updateDisplayedVirtualGroups = function (virtualColIds) { // go through each group, see if any of it's cols are displayed, and if yes, // then this group is included this.displayedLeftHeaderRows = {}; this.displayedRightHeaderRows = {}; this.displayedCentreHeaderRows = {}; testGroup(this.displayedLeftColumnTree, this.displayedLeftHeaderRows, 0); testGroup(this.displayedRightColumnTree, this.displayedRightHeaderRows, 0); testGroup(this.displayedCentreColumnTree, this.displayedCentreHeaderRows, 0); function testGroup(children, result, dept) { var returnValue = false; for (var i = 0; i < children.length; i++) { // see if this item is within viewport var child = children[i]; var addThisItem = void 0; if (child instanceof column_1.Column) { // for column, test if column is included addThisItem = virtualColIds[child.getId()] === true; } else { // if group, base decision on children var columnGroup = child; addThisItem = testGroup(columnGroup.getDisplayedChildren(), result, dept + 1); } if (addThisItem) { returnValue = true; if (!result[dept]) { result[dept] = []; } result[dept].push(child); } } return returnValue; } }; ColumnController.prototype.updateVirtualSets = function () { var virtualColIds = this.updateDisplayedCenterVirtualColumns(); this.updateDisplayedVirtualGroups(virtualColIds); }; ColumnController.prototype.filterOutColumnsWithinViewport = function () { return utils_1.Utils.filter(this.displayedCenterColumns, this.isColumnInViewport.bind(this)); }; // called from api ColumnController.prototype.sizeColumnsToFit = function (gridWidth) { var _this = this; // avoid divide by zero var allDisplayedColumns = this.getAllDisplayedColumns(); if (gridWidth <= 0 || allDisplayedColumns.length === 0) { return; } var colsToNotSpread = utils_1.Utils.filter(allDisplayedColumns, function (column) { return column.getColDef().suppressSizeToFit === true; }); var colsToSpread = utils_1.Utils.filter(allDisplayedColumns, function (column) { return column.getColDef().suppressSizeToFit !== true; }); // make a copy of the cols that are going to be resized var colsToFireEventFor = colsToSpread.slice(0); var finishedResizing = false; while (!finishedResizing) { finishedResizing = true; var availablePixels = gridWidth - this.getWidthOfColsInList(colsToNotSpread); if (availablePixels <= 0) { // no width, set everything to minimum colsToSpread.forEach(function (column) { column.setMinimum(); }); } else { var scale = availablePixels / this.getWidthOfColsInList(colsToSpread); // we set the pixels for the last col based on what's left, as otherwise // we could be a pixel or two short or extra because of rounding errors. var pixelsForLastCol = availablePixels; // backwards through loop, as we are removing items as we go for (var i = colsToSpread.length - 1; i >= 0; i--) { var column = colsToSpread[i]; var newWidth = Math.round(column.getActualWidth() * scale); if (newWidth < column.getMinWidth()) { column.setMinimum(); moveToNotSpread(column); finishedResizing = false; } else if (column.isGreaterThanMax(newWidth)) { column.setActualWidth(column.getMaxWidth()); moveToNotSpread(column); finishedResizing = false; } else { var onLastCol = i === 0; if (onLastCol) { column.setActualWidth(pixelsForLastCol); } else { column.setActualWidth(newWidth); } } pixelsForLastCol -= newWidth; } } } this.setLeftValues(); this.updateBodyWidths(); colsToFireEventFor.forEach(function (column) { var event = { type: events_1.Events.EVENT_COLUMN_RESIZED, column: column, columns: [column], finished: true, api: _this.gridApi, columnApi: _this.columnApi }; _this.eventService.dispatchEvent(event); }); function moveToNotSpread(column) { utils_1.Utils.removeFromArray(colsToSpread, column); colsToNotSpread.push(column); } }; ColumnController.prototype.buildDisplayedTrees = function (visibleColumns) { var leftVisibleColumns = utils_1.Utils.filter(visibleColumns, function (column) { return column.getPinned() === 'left'; }); var rightVisibleColumns = utils_1.Utils.filter(visibleColumns, function (column) { return column.getPinned() === 'right'; }); var centerVisibleColumns = utils_1.Utils.filter(visibleColumns, function (column) { return column.getPinned() !== 'left' && column.getPinned() !== 'right'; }); var groupInstanceIdCreator = new groupInstanceIdCreator_1.GroupInstanceIdCreator(); this.displayedLeftColumnTree = this.displayedGroupCreator.createDisplayedGroups(leftVisibleColumns, this.gridBalancedTree, groupInstanceIdCreator, this.displayedLeftColumnTree); this.displayedRightColumnTree = this.displayedGroupCreator.createDisplayedGroups(rightVisibleColumns, this.gridBalancedTree, groupInstanceIdCreator, this.displayedRightColumnTree); this.displayedCentreColumnTree = this.displayedGroupCreator.createDisplayedGroups(centerVisibleColumns, this.gridBalancedTree, groupInstanceIdCreator, this.displayedCentreColumnTree); }; ColumnController.prototype.updateGroups = function () { var allGroups = this.getAllDisplayedColumnGroups(); this.columnUtils.depthFirstAllColumnTreeSearch(allGroups, function (child) { if (child instanceof columnGroup_1.ColumnGroup) { var group = child; group.calculateDisplayedColumns(); } }); }; ColumnController.prototype.getGroupAutoColumns = function () { return this.groupAutoColumns; }; ColumnController.prototype.createGroupAutoColumnsIfNeeded = function () { if (!this.autoGroupsNeedBuilding) { return; } this.autoGroupsNeedBuilding = false; // see if we need to insert the default grouping column var needAutoColumns = this.rowGroupColumns.length > 0 && !this.gridOptionsWrapper.isGroupSuppressAutoColumn() && !this.gridOptionsWrapper.isGroupUseEntireRow() && !this.gridOptionsWrapper.isGroupSuppressRow(); if (needAutoColumns) { this.groupAutoColumns = this.autoGroupColService.createAutoGroupColumns(this.rowGroupColumns); } else { this.groupAutoColumns = null; } }; ColumnController.prototype.createValueColumns = function () { this.valueColumns.forEach(function (column) { return column.setValueActive(false); }); this.valueColumns = []; // override with columns that have the aggFunc specified explicitly for (var i = 0; i < this.primaryColumns.length; i++) { var column = this.primaryColumns[i]; if (column.getColDef().aggFunc) { column.setAggFunc(column.getColDef().aggFunc); this.valueColumns.push(column); column.setValueActive(true); } } }; ColumnController.prototype.getWidthOfColsInList = function (columnList) { var result = 0; for (var i = 0; i < columnList.length; i++) { result += columnList[i].getActualWidth(); } return result; }; ColumnController.prototype.getGridBalancedTree = function () { return this.gridBalancedTree; }; __decorate([ context_1.Autowired('gridOptionsWrapper'), __metadata("design:type", gridOptionsWrapper_1.GridOptionsWrapper) ], ColumnController.prototype, "gridOptionsWrapper", void 0); __decorate([ context_1.Autowired('expressionService'), __metadata("design:type", expressionService_1.ExpressionService) ], ColumnController.prototype, "expressionService", void 0); __decorate([ context_1.Autowired('balancedColumnTreeBuilder'), __metadata("design:type", balancedColumnTreeBuilder_1.BalancedColumnTreeBuilder) ], ColumnController.prototype, "balancedColumnTreeBuilder", void 0); __decorate([ context_1.Autowired('displayedGroupCreator'), __metadata("design:type", displayedGroupCreator_1.DisplayedGroupCreator) ], ColumnController.prototype, "displayedGroupCreator", void 0); __decorate([ context_1.Autowired('autoWidthCalculator'), __metadata("design:type", autoWidthCalculator_1.AutoWidthCalculator) ], ColumnController.prototype, "autoWidthCalculator", void 0); __decorate([ context_1.Autowired('eventService'), __metadata("design:type", eventService_1.EventService) ], ColumnController.prototype, "eventService", void 0); __decorate([ context_1.Autowired('columnUtils'), __metadata("design:type", columnUtils_1.ColumnUtils) ], ColumnController.prototype, "columnUtils", void 0); __decorate([ context_1.Autowired('gridPanel'), __metadata("design:type", gridPanel_1.GridPanel) ], ColumnController.prototype, "gridPanel", void 0); __decorate([ context_1.Autowired('context'), __metadata("design:type", context_1.Context) ], ColumnController.prototype, "context", void 0); __decorate([ context_1.Autowired('columnAnimationService'), __metadata("design:type", columnAnimationService_1.ColumnAnimationService) ], ColumnController.prototype, "columnAnimationService", void 0); __decorate([ context_1.Autowired('autoGroupColService'), __metadata("design:type", autoGroupColService_1.AutoGroupColService) ], ColumnController.prototype, "autoGroupColService", void 0); __decorate([ context_1.Optional('aggFuncService'), __metadata("design:type", Object) ], ColumnController.prototype, "aggFuncService", void 0); __decorate([ context_1.Optional('valueCache'), __metadata("design:type", valueCache_1.ValueCache) ], ColumnController.prototype, "valueCache", void 0); __decorate([ context_1.Autowired('columnApi'), __metadata("design:type", ColumnApi) ], ColumnController.prototype, "columnApi", void 0); __decorate([ context_1.Autowired('gridApi'), __metadata("design:type", gridApi_1.GridApi) ], ColumnController.prototype, "gridApi", void 0); __decorate([ context_1.PostConstruct, __metadata("design:type", Function), __metadata("design:paramtypes", []), __metadata("design:returntype", void 0) ], ColumnController.prototype, "init", null); __decorate([ __param(0, context_1.Qualifier('loggerFactory')), __metadata("design:type", Function), __metadata("design:paramtypes", [logger_1.LoggerFactory]), __metadata("design:returntype", void 0) ], ColumnController.prototype, "setBeans", null); ColumnController = __decorate([ context_1.Bean('columnController') ], ColumnController); return ColumnController; }()); exports.ColumnController = ColumnController;
({ *method(x = yield) {} })
loadIonicon('<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><path d="M217.9 256L345 129c9.4-9.4 9.4-24.6 0-33.9-9.4-9.4-24.6-9.3-34 0L167 239c-9.1 9.1-9.3 23.7-.7 33.1L310.9 417c4.7 4.7 10.9 7 17 7s12.3-2.3 17-7c9.4-9.4 9.4-24.6 0-33.9L217.9 256z"/></svg>','ios-arrow-back');
var path = require('path') , fs = require('fs') , exists = fs.existsSync || path.existsSync , resolve = path.resolve , dirname = path.dirname , extname = path.extname , basename = path.basename; /** * Express 3.x Layout & Partial support. * * The beloved feature from Express 2.x is back as a middleware. * * Example: * * var express = require('express') * , partials = require('express-partials') * , app = express(); * app.use(partials()); * // three ways to register a template engine: * partials.register('coffee','coffeekup'); * partials.register('coffee',require('coffeekup')); * partials.register('coffee',require('coffeekup').render); * app.get('/',function(req,res,next){ * res.render('index.ejs') // renders layout.ejs with index.ejs as `body`. * }) * * Options: * * none * */ module.exports = function(){ return function(req,res,next){ // res.partial(view,options) -> res.render() (ignores any layouts) res.partial = res.render; // in template partial(view,options) res.locals.partial = partial.bind(res); // layout support var _render = res.render.bind(res); res.render = function(name, options, fn){ var layout = options && options.layout; // default layout if( layout === true || layout === undefined ) layout = 'layout'; // layout if( layout ){ // first render normally _render(name, options, function(err, body){ if( err ) return fn ? fn(err) : req.next(err); options = options || {}; options.body = body; // calculate the layout vars var ext = extname(name) || '.'+(res.app.get('view engine') || 'ejs'); var root = req.app.get('views') || process.cwd() + '/views'; var dir = dirname(layout) == '.' ? root : resolve(root,dirname(layout)); var filename = dir+(path.sep||'/')+basename(layout,ext)+ext; // See if we even have a layout to use // If so, render it. If not, then fallback to just the original template if (exists(filename)) { layout = dirname(lookup(dir, layout, ext))+(path.sep||'/')+basename(layout,ext)+ext; _render(layout, options, fn); } else { // layout may be in the same folder than the view dir = dirname(name) == '.' ? root : resolve(root,dirname(name)); filename = dir+(path.sep||'/')+basename(layout,ext)+ext; if(exists(filename)) { layout = dirname(lookup(dir, layout, ext))+(path.sep||'/')+basename(layout,ext)+ext; _render(layout, options, fn); } else { _render(name, options, fn); } } }) // no layout } else { _render(name, options, fn); } } // done next(); } } /*** * Allow to register a specific rendering * function for a given extension. * (Similar to Express 2.x register() function.) * * The second argument might be: * a template module's name * a module with a `render` method * a synchronous `render` method */ function register(ext,render){ if(ext[0] != '.') { ext = '.' + ext; } if(typeof render == 'string') { render = require(render); } if(typeof render.render != 'undefined') { register[ext] = render.render; } else { register[ext] = render; } }; module.exports.register = register; /** * Automatically assign a render() function * from a module of the same name if none * has been registered. */ function renderer(ext){ if(ext[0] !== '.'){ ext = '.' + ext; } return register[ext] != null ? register[ext] : register[ext] = require(ext.slice(1)).render; }; module.exports.renderer = renderer; /** * Memory cache for resolved object names. */ var cache = {}; /** * Resolve partial object name from the view path. * * Examples: * * "user.ejs" becomes "user" * "forum thread.ejs" becomes "forumThread" * "forum/thread/post.ejs" becomes "post" * "blog-post.ejs" becomes "blogPost" * * @return {String} * @api private */ function resolveObjectName(view){ return cache[view] || (cache[view] = view .split(path.sep || '/') .slice(-1)[0] .split('.')[0] .replace(/^_/, '') .replace(/[^a-zA-Z0-9 ]+/g, ' ') .split(/ +/).map(function(word, i){ return i ? word[0].toUpperCase() + word.substr(1) : word; }).join('')); }; /** * Lookup: * * - partial `_<name>` * - any `<name>/index` * - non-layout `../<name>/index` * - any `<root>/<name>` * - partial `<root>/_<name>` * * @param {View} view * @return {String} * @api private */ function lookup(root, view, ext){ var name = resolveObjectName(view); var original = view; // Try root ex: <root>/user.jade view = resolve(root, basename(original,ext)+ext); if( exists(view) ) return view; // Try subdir ex: <root>/subdir/user.jade view = resolve(root, dirname(original), basename(original,ext)+ext); if( exists(view) ) return view; // Try _ prefix ex: ./views/_<name>.jade // taking precedence over the direct path view = resolve(root,'_'+name+ext) if( exists(view) ) return view; // Try index ex: ./views/user/index.jade view = resolve(root,name,'index'+ext); if( exists(view) ) return view; // Try ../<name>/index ex: ../user/index.jade // when calling partial('user') within the same dir view = resolve(root,'..',name,'index'+ext); if( exists(view) ) return view; // Try root ex: <root>/user.jade view = resolve(root,name+ext); if( exists(view) ) return view; return null; }; module.exports.lookup = lookup; /** * Render `view` partial with the given `options`. Optionally a * callback `fn(err, str)` may be passed instead of writing to * the socket. * * Options: * * - `object` Single object with name derived from the view (unless `as` is present) * * - `as` Variable name for each `collection` value, defaults to the view name. * * as: 'something' will add the `something` local variable * * as: this will use the collection value as the template context * * as: global will merge the collection value's properties with `locals` * * - `collection` Array of objects, the name is derived from the view name itself. * For example _video.html_ will have a object _video_ available to it. * * @param {String} view * @param {Object|Array} options, collection or object * @return {String} * @api public */ function partial(view, options){ var collection , object , locals , name; // parse options if( options ){ // collection if( options.collection ){ collection = options.collection; delete options.collection; } else if( 'length' in options ){ collection = options; options = {}; } // locals if( options.locals ){ locals = options.locals; delete options.locals; } // object if( 'Object' != options.constructor.name ){ object = options; options = {}; } else if( options.object != undefined ){ object = options.object; delete options.object; } } else { options = {}; } // merge locals into options if( locals ) options.__proto__ = locals; // merge app locals into for(var k in this.app.locals) options[k] = options[k] || this.app.locals[k]; // merge locals, which as set using app.use(function(...){ res.locals = X; }) for(var k in this.req.res.locals) options[k] = options[k] || this.req.res.locals[k]; // let partials render partials options.partial = partial.bind(this); // extract object name from view name = options.as || resolveObjectName(view); // find view var root = this.app.get('views') || process.cwd() + '/views' , ext = extname(view) || '.' + (this.app.get('view engine')||'ejs') , file = lookup(root, view, ext); // read view var source = fs.readFileSync(file,'utf8'); // set filename option for renderer (Jade requires this for includes) options.filename = file; // render partial function render(){ if (object) { if ('string' == typeof name) { options[name] = object; } else if (name === global) { // wtf? // merge(options, object); } } return renderer(ext)(source, options); } // Collection support if (collection) { var len = collection.length , buf = '' , keys , key , val; if ('number' == typeof len || Array.isArray(collection)) { options.collectionLength = len; for (var i = 0; i < len; ++i) { val = collection[i]; options.firstInCollection = i == 0; options.indexInCollection = i; options.lastInCollection = i == len - 1; object = val; buf += render(); } } else { keys = Object.keys(collection); len = keys.length; options.collectionLength = len; options.collectionKeys = keys; for (var i = 0; i < len; ++i) { key = keys[i]; val = collection[key]; options.keyInCollection = key; options.firstInCollection = i == 0; options.indexInCollection = i; options.lastInCollection = i == len - 1; object = val; buf += render(); } } return buf; } else { return render(); } }
/************************************************************* * * MathJax/jax/output/SVG/fonts/Gyre-Pagella/Symbols/Regular/Main.js * * Copyright (c) 2013-2014 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.OutputJax['SVG'].FONTDATA.FONTS['GyrePagellaMathJax_Symbols'] = { directory: 'Symbols/Regular', family: 'GyrePagellaMathJax_Symbols', id: 'GYREPAGELLASYMBOLS', 0x20: [0,0,250,0,0,''], 0xA0: [0,0,250,0,0,''], 0x2300: [564,64,788,80,708,'634 250c0 62 -18 116 -50 156l-346 -346c40 -32 94 -50 156 -50c144 0 240 96 240 240zM550 440c-40 32 -94 50 -156 50c-144 0 -240 -96 -240 -240c0 -62 18 -116 50 -156zM708 530l-80 -80c42 -51 66 -120 66 -200c0 -180 -120 -300 -300 -300c-80 0 -149 24 -200 66 l-80 -80c-4 7 -9 13 -15 19s-12 11 -19 15l80 80c-42 51 -66 120 -66 200c0 180 120 300 300 300c80 0 149 -24 200 -66l80 80c4 -7 9 -13 15 -19s12 -11 19 -15'], 0x2305: [444,-56,760,80,680,'680 384h-600c2 10 3 20 3 30c0 11 -1 21 -3 30h600c-2 -9 -3 -19 -3 -30c0 -10 1 -20 3 -30zM546 56c-12 2 -24 3 -36 3s-24 -1 -36 -3l-94 145l-94 -145c-12 2 -24 3 -36 3s-24 -1 -36 -3l136 208c10 -2 20 -3 30 -3s20 1 30 3'], 0x2306: [554,54,760,80,680,'680 274h-600c2 10 3 20 3 30c0 11 -1 21 -3 30h600c-2 -9 -3 -19 -3 -30c0 -10 1 -20 3 -30zM680 494h-600c2 10 3 20 3 30c0 11 -1 21 -3 30h600c-2 -9 -3 -19 -3 -30c0 -10 1 -20 3 -30zM546 -54c-12 2 -24 3 -36 3s-24 -1 -36 -3l-94 145l-94 -145c-12 2 -24 3 -36 3 s-24 -1 -36 -3l136 208c10 -2 20 -3 30 -3s20 1 30 3'], 0x2310: [280,0,790,80,710,'710 220h-570v-220c-10 2 -20 3 -30 3s-20 -1 -30 -3v250c6 4 12 8 17 13s9 11 13 17h600c-2 -10 -3 -20 -3 -30s1 -20 3 -30'], 0x2319: [500,-220,790,80,710,'710 220h-600c-4 6 -8 12 -13 17s-11 9 -17 13v250c10 -2 20 -3 30 -3s20 1 30 3v-220h570c-2 -10 -3 -20 -3 -30s1 -20 3 -30'], 0x231C: [680,-450,390,80,310,'310 620h-170v-170c-10 2 -20 3 -30 3s-20 -1 -30 -3v200c6 4 12 8 17 13s9 11 13 17h200c-2 -10 -3 -20 -3 -30s1 -20 3 -30'], 0x231D: [680,-450,390,80,310,'310 450c-10 2 -20 3 -30 3s-20 -1 -30 -3v170h-170c2 10 3 20 3 30s-1 20 -3 30h200c4 -6 8 -12 13 -17s11 -9 17 -13v-200'], 0x231E: [50,180,390,80,310,'310 -180h-200c-4 6 -8 12 -13 17s-11 9 -17 13v200c10 -2 20 -3 30 -3s20 1 30 3v-170h170c-2 -10 -3 -20 -3 -30s1 -20 3 -30'], 0x231F: [50,180,390,80,310,'310 -150c-6 -4 -12 -8 -17 -13s-9 -11 -13 -17h-200c2 10 3 20 3 30s-1 20 -3 30h170v170c10 -2 20 -3 30 -3s20 1 30 3v-200'], 0x2320: [1212,0,737,318,657,'657 1189c-8 -31 -15 -82 -11 -143h-76c-3 48 -4 81 -29 82c-59 3 -90 -36 -107 -127c-16 -88 -16 -667 -16 -1001h-100c0 331 0 868 34 986c8 26 13 49 25 65c37 47 64 75 100 115c18 21 71 46 100 46c28 0 57 -10 80 -23'], 0x2321: [1194,18,737,80,418,'418 1194c0 -331 0 -868 -33 -986c-8 -26 -13 -49 -25 -65c-37 -47 -64 -75 -100 -115c-18 -21 -71 -46 -100 -46c-28 0 -57 10 -80 23c8 31 15 82 11 143h76c3 -48 4 -81 29 -82c59 -3 90 36 107 127c15 88 15 667 15 1001h100'], 0x2329: [658,158,391,80,311,'311 -142c-7 -1 -13 -2 -19 -5c-7 -3 -12 -7 -17 -11l-195 408l195 408c5 -4 10 -8 17 -11c6 -3 12 -4 19 -5l-165 -392'], 0x232A: [658,158,391,80,311,'311 250l-195 -408c-5 4 -10 8 -17 11c-6 3 -12 4 -19 5l165 392l-165 392c7 1 13 2 19 5c7 3 12 7 17 11'], 0x239B: [1208,0,679,143,583,'583 1180c-245 -246 -360 -593 -360 -981v-199h-80v199c0 404 156 753 412 1009c3 -6 7 -11 12 -16s10 -9 16 -12'], 0x239C: [396,0,679,143,223,'223 0h-80v396h80v-396'], 0x239D: [1208,0,679,143,583,'583 28c-6 -3 -11 -7 -16 -12s-9 -10 -12 -16c-256 256 -412 605 -412 1009v199h80v-199c0 -388 115 -735 360 -981'], 0x239E: [1208,0,679,96,536,'536 0h-80v199c0 388 -114 735 -360 981c6 3 11 7 16 12s9 10 12 16c257 -256 412 -605 412 -1009v-199'], 0x239F: [396,0,679,456,536,'536 0h-80v396h80v-396'], 0x23A0: [1208,0,679,96,536,'536 1009c0 -404 -155 -753 -412 -1009c-3 6 -7 11 -12 16s-10 9 -16 12c246 246 360 593 360 981v199h80v-199'], 0x23A1: [1214,0,521,143,425,'425 1214c-2 -6 -3 -13 -3 -20s1 -14 3 -20h-202v-1174h-80v1214h282'], 0x23A2: [810,0,521,143,223,'223 810v-810h-80v810h80'], 0x23A3: [1214,0,521,143,425,'425 0h-282v1214h80v-1174h202c-2 -6 -3 -13 -3 -20s1 -14 3 -20'], 0x23A4: [1214,0,521,96,378,'378 0h-80v1174h-202c2 6 3 13 3 20s-1 14 -3 20h282v-1214'], 0x23A5: [810,0,521,298,378,'378 0h-80v810h80v-810'], 0x23A6: [1214,0,521,96,378,'378 0h-282c2 6 3 13 3 20s-1 14 -3 20h202v1174h80v-1214'], 0x23A7: [616,0,589,252,493,'493 578c-115 -31 -161 -135 -161 -279v-299h-80v299c0 176 91 280 231 317c0 -6 0 -13 2 -20c2 -6 5 -13 8 -18'], 0x23A8: [1194,0,589,96,332,'332 0h-80v299c0 173 -42 278 -156 278c2 6 3 13 3 20s-1 14 -3 20c114 0 156 105 156 278v299h80v-299c0 -161 -53 -259 -138 -298c85 -39 138 -137 138 -298v-299'], 0x23A9: [616,0,589,252,493,'493 39c-3 -6 -6 -12 -8 -19c-2 -6 -2 -13 -2 -20c-140 38 -231 142 -231 317v299h80v-299c0 -144 46 -248 161 -278'], 0x23AA: [596,0,589,257,337,'337 596v-596h-80v596h80'], 0x23AB: [616,0,589,96,337,'337 0h-80v299c0 144 -46 248 -161 279c4 5 6 12 8 18c2 7 3 14 2 20c141 -37 231 -141 231 -317v-299'], 0x23AC: [1194,0,589,257,493,'493 577c-114 0 -156 -105 -156 -278v-299h-80v299c0 161 53 259 138 298c-85 39 -138 137 -138 298v299h80v-299c0 -173 42 -278 156 -278c-2 -6 -3 -13 -3 -20s1 -14 3 -20'], 0x23AD: [616,0,589,96,337,'337 317c0 -175 -90 -279 -231 -317c1 7 0 14 -2 20c-2 7 -4 13 -8 19c115 30 161 134 161 278v299h80v-299'], 0x23AE: [580,0,760,328,432,'432 580v-580h-104v580h104'], 0x23B2: [829,0,1408,80,1248,'1248 632h-42l-7 86c-4 48 -37 57 -373 57h-599l470 -775h-136l-481 794l5 35l275 -4l888 4c-3 -45 -4 -67 -4 -99c0 -31 1 -53 4 -98'], 0x23B3: [896,4,1408,80,1328,'1328 259c-6 -66 -7 -158 -7 -263l-545 4l-696 -4v34l515 811l-34 55h136l-504 -794h722c339 0 356 7 364 88l8 69h41'], 0x23B7: [1623,0,770,120,610,'610 0c-13 2 -27 3 -40 3c-14 0 -27 -1 -41 -3l-342 1416h-67v60h153l277 -1143v1290h60v-1623'], 0x27C2: [650,0,760,80,680,'680 0h-600c2 10 3 20 3 30s-1 20 -3 30h270v590c10 -2 20 -3 30 -3s20 1 30 3v-590h270c-2 -10 -3 -20 -3 -30s1 -20 3 -30'], 0x27D8: [650,150,860,80,780,'780 -150h-700c2 10 3 20 3 30s-1 20 -3 30h320v740c10 -2 20 -3 30 -3s20 1 30 3v-740h320c-2 -10 -3 -20 -3 -30s1 -20 3 -30'], 0x27D9: [650,150,860,80,780,'780 590h-320v-740c-10 2 -20 3 -30 3s-20 -1 -30 -3v740h-320c2 10 3 20 3 30s-1 20 -3 30h700c-2 -10 -3 -20 -3 -30s1 -20 3 -30'], 0x27DA: [650,150,1203,80,1123,'1123 110h-400v-260c-10 2 -20 3 -30 3s-20 -1 -30 -3v800c10 -2 20 -3 30 -3s20 1 30 3v-260h400c-2 -10 -3 -20 -3 -30s1 -20 3 -30h-400v-160h400c-2 -10 -3 -20 -3 -30s1 -20 3 -30zM543 -150c-10 2 -20 3 -30 3s-20 -1 -30 -3v260h-400c-2 10 -3 20 -3 30s1 20 3 30 h400v160h-400c-2 10 -3 20 -3 30s1 20 3 30h400v260c10 -2 20 -3 30 -3s20 1 30 3v-800'], 0x27DB: [650,150,1203,80,1123,'1123 220h-400v-370c-10 2 -20 3 -30 3s-20 -1 -30 -3v800c10 -2 20 -3 30 -3s20 1 30 3v-370h400c-2 -10 -3 -20 -3 -30s1 -20 3 -30zM543 -150c-10 2 -20 3 -30 3s-20 -1 -30 -3v370h-400c-2 10 -3 20 -3 30s1 20 3 30h400v370c10 -2 20 -3 30 -3s20 1 30 3v-800'], 0x27DC: [410,-90,920,80,840,'840 220h-442c-12 -79 -72 -130 -158 -130c-96 0 -160 64 -160 160s64 160 160 160c86 0 146 -51 158 -130h442c-2 -10 -3 -20 -3 -30s1 -20 3 -30zM352 250c0 67 -45 112 -112 112s-112 -45 -112 -112s45 -112 112 -112s112 45 112 112'], 0x27DD: [650,150,1360,80,1280,'1280 220h-1140v-370c-10 2 -20 3 -30 3s-20 -1 -30 -3v800c10 -2 20 -3 30 -3s20 1 30 3v-370h1140c-2 -10 -3 -20 -3 -30s1 -20 3 -30'], 0x27DE: [650,150,1360,80,1280,'1280 -150c-10 2 -20 3 -30 3s-20 -1 -30 -3v370h-1140c2 10 3 20 3 30s-1 20 -3 30h1140v370c10 -2 20 -3 30 -3s20 1 30 3v-800'], 0x27E0: [576,76,595,80,515,'515 234l-192 -310c-8 2 -17 3 -25 3c-9 0 -18 -1 -26 -3l-192 310c2 5 3 11 3 16s-1 11 -3 16l192 310c8 -2 17 -3 26 -3c8 0 17 1 26 3l191 -310c-2 -5 -3 -11 -3 -16s1 -11 3 -16zM436 280l-138 224l-139 -224h277zM436 220h-277l139 -224'], 0x27E1: [471,-29,603,80,523,'442 250c-58 34 -107 82 -141 140c-33 -58 -82 -106 -140 -140c58 -34 107 -82 140 -140c34 58 83 106 141 140zM523 222c-90 -33 -161 -104 -193 -193c-10 2 -19 3 -29 3c-9 0 -18 -1 -28 -3c-32 89 -103 160 -193 193c2 9 3 19 3 28s-1 19 -3 28c90 33 161 104 193 193 c10 -2 19 -3 28 -3c10 0 19 1 28 3c33 -89 104 -160 194 -193c-2 -9 -3 -19 -3 -28s1 -19 3 -28'], 0x27E2: [471,-29,698,80,618,'618 222c-90 -33 -160 -104 -193 -193c-9 2 -19 3 -28 3c-10 0 -19 -1 -28 -3c-32 88 -101 158 -189 191h-100c2 10 3 20 3 30s-1 20 -3 30h101c87 34 156 103 188 191c9 -2 18 -3 28 -3c9 0 19 1 28 3c33 -89 103 -160 193 -193c-2 -9 -3 -19 -3 -28s1 -19 3 -28z M537 250c-58 34 -107 82 -140 140c-34 -58 -82 -106 -141 -140c59 -34 107 -82 141 -140c33 58 82 106 140 140'], 0x27E3: [471,-29,698,80,618,'618 220h-100c-88 -34 -156 -103 -188 -191c-10 2 -19 3 -29 3c-9 0 -18 -1 -28 -3c-32 89 -103 160 -193 193c2 9 3 19 3 28s-1 19 -3 28c90 33 161 104 193 193c10 -2 19 -3 28 -3c10 0 19 1 28 3c33 -88 102 -158 189 -191h100c-2 -10 -3 -20 -3 -30s1 -20 3 -30z M442 250c-58 34 -107 82 -141 140c-33 -58 -82 -106 -140 -140c58 -34 107 -82 140 -140c34 58 83 106 141 140'], 0x27E6: [670,170,430,120,350,'350 -130c-2 -6 -3 -13 -3 -20s1 -14 3 -20h-230v840h230c-2 -6 -3 -13 -3 -20s1 -14 3 -20h-75v-760h75zM235 630h-75v-760h75v760'], 0x27E7: [670,170,430,80,310,'310 670v-840h-230c2 6 3 13 3 20s-1 14 -3 20h75v760h-75c2 6 3 13 3 20s-1 14 -3 20h230zM270 -130v760h-75v-760h75'], 0x27EA: [658,158,611,80,531,'311 -142c-7 -1 -13 -2 -19 -5c-7 -3 -12 -7 -17 -11l-195 408l195 408c5 -4 10 -8 17 -11c6 -3 12 -4 19 -5l-165 -392zM531 -142c-7 -1 -14 -2 -20 -5s-12 -7 -17 -11l-194 408l194 408c5 -4 11 -8 17 -11s13 -4 20 -5l-166 -392'], 0x27EB: [658,158,611,80,531,'531 250l-195 -408c-5 4 -11 8 -17 11s-13 4 -19 5l165 392l-165 392c6 1 13 2 19 5s12 7 17 11zM311 250l-195 -408c-5 4 -10 8 -17 11c-6 3 -12 4 -19 5l165 392l-165 392c7 1 13 2 19 5c7 3 12 7 17 11'] }; MathJax.Ajax.loadComplete(MathJax.OutputJax.SVG.fontDir+"/Symbols/Regular/Main.js");
/** * ag-grid - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components * @version v10.0.1 * @link http://www.ag-grid.com/ * @license MIT */ "use strict"; var __extends = (this && this.__extends) || (function () { var extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; var __param = (this && this.__param) || function (paramIndex, decorator) { return function (target, key) { decorator(target, key, paramIndex); } }; Object.defineProperty(exports, "__esModule", { value: true }); var utils_1 = require("../utils"); var masterSlaveService_1 = require("../masterSlaveService"); var gridOptionsWrapper_1 = require("../gridOptionsWrapper"); var columnController_1 = require("../columnController/columnController"); var rowRenderer_1 = require("../rendering/rowRenderer"); var floatingRowModel_1 = require("../rowModels/floatingRowModel"); var borderLayout_1 = require("../layout/borderLayout"); var logger_1 = require("../logger"); var context_1 = require("../context/context"); var eventService_1 = require("../eventService"); var events_1 = require("../events"); var dragService_1 = require("../dragAndDrop/dragService"); var constants_1 = require("../constants"); var selectionController_1 = require("../selectionController"); var csvCreator_1 = require("../csvCreator"); var mouseEventService_1 = require("./mouseEventService"); var focusedCellController_1 = require("../focusedCellController"); var renderedRow_1 = require("../rendering/renderedRow"); var scrollVisibleService_1 = require("./scrollVisibleService"); var beanStub_1 = require("../context/beanStub"); var rowContainerComponent_1 = require("../rendering/rowContainerComponent"); var paginationProxy_1 = require("../rowModels/paginationProxy"); var popupEditorWrapper_1 = require("../rendering/cellEditors/popupEditorWrapper"); // in the html below, it is important that there are no white space between some of the divs, as if there is white space, // it won't render correctly in safari, as safari renders white space as a gap var gridHtml = '<div class="ag-root ag-font-style">' + // header '<div class="ag-header">' + '<div class="ag-pinned-left-header"></div>' + '<div class="ag-pinned-right-header"></div>' + '<div class="ag-header-viewport">' + '<div class="ag-header-container"></div>' + '</div>' + '<div class="ag-header-overlay"></div>' + '</div>' + // floating top '<div class="ag-floating-top">' + '<div class="ag-pinned-left-floating-top"></div>' + '<div class="ag-pinned-right-floating-top"></div>' + '<div class="ag-floating-top-viewport">' + '<div class="ag-floating-top-container"></div>' + '</div>' + '<div class="ag-floating-top-full-width-container"></div>' + '</div>' + // floating bottom '<div class="ag-floating-bottom">' + '<div class="ag-pinned-left-floating-bottom"></div>' + '<div class="ag-pinned-right-floating-bottom"></div>' + '<div class="ag-floating-bottom-viewport">' + '<div class="ag-floating-bottom-container"></div>' + '</div>' + '<div class="ag-floating-bottom-full-width-container"></div>' + '</div>' + // body '<div class="ag-body">' + '<div class="ag-pinned-left-cols-viewport">' + '<div class="ag-pinned-left-cols-container"></div>' + '</div>' + '<div class="ag-pinned-right-cols-viewport">' + '<div class="ag-pinned-right-cols-container"></div>' + '</div>' + '<div class="ag-body-viewport-wrapper">' + '<div class="ag-body-viewport">' + '<div class="ag-body-container"></div>' + '</div>' + '</div>' + '<div class="ag-full-width-viewport">' + '<div class="ag-full-width-container"></div>' + '</div>' + '</div>' + '</div>'; var gridForPrintHtml = '<div class="ag-root ag-font-style">' + // header '<div class="ag-header-container"></div>' + // floating '<div class="ag-floating-top-container"></div>' + // body '<div class="ag-body-container"></div>' + // floating bottom '<div class="ag-floating-bottom-container"></div>' + '</div>'; // wrapping in outer div, and wrapper, is needed to center the loading icon // The idea for centering came from here: http://www.vanseodesign.com/css/vertical-centering/ var mainOverlayTemplate = '<div class="ag-overlay-panel">' + '<div class="ag-overlay-wrapper ag-overlay-[OVERLAY_NAME]-wrapper">[OVERLAY_TEMPLATE]</div>' + '</div>'; var defaultLoadingOverlayTemplate = '<span class="ag-overlay-loading-center">[LOADING...]</span>'; var defaultNoRowsOverlayTemplate = '<span class="ag-overlay-no-rows-center">[NO_ROWS_TO_SHOW]</span>'; var GridPanel = (function (_super) { __extends(GridPanel, _super); function GridPanel() { var _this = _super !== null && _super.apply(this, arguments) || this; _this.requestAnimationFrameExists = typeof requestAnimationFrame === 'function'; _this.scrollLagCounter = 0; _this.scrollLagTicking = false; _this.lastLeftPosition = -1; _this.lastTopPosition = -1; _this.animationThreadCount = 0; return _this; } GridPanel.prototype.agWire = function (loggerFactory) { this.logger = loggerFactory.create('GridPanel'); // makes code below more readable if we pull 'forPrint' out this.forPrint = this.gridOptionsWrapper.isForPrint(); this.scrollWidth = this.gridOptionsWrapper.getScrollbarWidth(); this.useScrollLag = this.isUseScrollLag(); this.enableRtl = this.gridOptionsWrapper.isEnableRtl(); this.loadTemplate(); this.findElements(); }; GridPanel.prototype.getVerticalPixelRange = function () { var container = this.getPrimaryScrollViewport(); var result = { top: container.scrollTop, bottom: container.scrollTop + container.offsetHeight }; return result; }; // we override this, as the base class is missing the annotation GridPanel.prototype.destroy = function () { _super.prototype.destroy.call(this); }; GridPanel.prototype.onRowDataChanged = function () { this.showOrHideOverlay(); }; GridPanel.prototype.showOrHideOverlay = function () { if (this.paginationProxy.isEmpty() && !this.gridOptionsWrapper.isSuppressNoRowsOverlay()) { this.showNoRowsOverlay(); } else { this.hideOverlay(); } }; GridPanel.prototype.getLayout = function () { return this.layout; }; GridPanel.prototype.init = function () { this.addEventListeners(); this.addDragListeners(); this.layout = new borderLayout_1.BorderLayout({ overlays: { loading: utils_1.Utils.loadTemplate(this.createLoadingOverlayTemplate()), noRows: utils_1.Utils.loadTemplate(this.createNoRowsOverlayTemplate()) }, center: this.eRoot, dontFill: this.forPrint, name: 'eGridPanel' }); this.layout.addSizeChangeListener(this.setBodyAndHeaderHeights.bind(this)); this.layout.addSizeChangeListener(this.setLeftAndRightBounds.bind(this)); this.addScrollListener(); if (this.gridOptionsWrapper.isSuppressHorizontalScroll()) { this.eBodyViewport.style.overflowX = 'hidden'; } if (this.gridOptionsWrapper.isRowModelDefault() && !this.gridOptionsWrapper.getRowData()) { this.showLoadingOverlay(); } this.setPinnedContainersVisible(); this.setBodyAndHeaderHeights(); this.disableBrowserDragging(); this.addShortcutKeyListeners(); this.addMouseEvents(); this.addKeyboardEvents(); this.addBodyViewportListener(); this.addStopEditingWhenGridLosesFocus(); if (this.$scope) { this.addAngularApplyCheck(); } this.onDisplayedColumnsWidthChanged(); }; GridPanel.prototype.addStopEditingWhenGridLosesFocus = function () { var _this = this; if (this.gridOptionsWrapper.isStopEditingWhenGridLosesFocus()) { this.addDestroyableEventListener(this.eBody, 'focusout', function (event) { // this is the element the focus is moving to var elementWithFocus = event.relatedTarget; // see if the element the focus is going to is part of the grid var clickInsideGrid = false; var pointer = elementWithFocus; while (utils_1.Utils.exists(pointer) && !clickInsideGrid) { var isPopup = !!_this.gridOptionsWrapper.getDomData(pointer, popupEditorWrapper_1.PopupEditorWrapper.DOM_KEY_POPUP_EDITOR_WRAPPER); var isBody = _this.eBody == pointer; clickInsideGrid = isPopup || isBody; pointer = pointer.parentNode; } if (!clickInsideGrid) { _this.rowRenderer.stopEditing(); } }); } }; GridPanel.prototype.addAngularApplyCheck = function () { var _this = this; // this makes sure if we queue up requests, we only execute oe var applyTriggered = false; var listener = function () { // only need to do one apply at a time if (applyTriggered) { return; } applyTriggered = true; // mark 'need apply' to true setTimeout(function () { applyTriggered = false; _this.$scope.$apply(); }, 0); }; // these are the events we need to do an apply after - these are the ones that can end up // with columns added or removed this.addDestroyableEventListener(this.eventService, events_1.Events.EVENT_DISPLAYED_COLUMNS_CHANGED, listener); this.addDestroyableEventListener(this.eventService, events_1.Events.EVENT_VIRTUAL_COLUMNS_CHANGED, listener); }; // if we do not do this, then the user can select a pic in the grid (eg an image in a custom cell renderer) // and then that will start the browser native drag n' drop, which messes up with our own drag and drop. GridPanel.prototype.disableBrowserDragging = function () { this.eRoot.addEventListener('dragstart', function (event) { if (event.target instanceof HTMLImageElement) { event.preventDefault(); return false; } }); }; GridPanel.prototype.addEventListeners = function () { this.addDestroyableEventListener(this.eventService, events_1.Events.EVENT_DISPLAYED_COLUMNS_CHANGED, this.onDisplayedColumnsChanged.bind(this)); this.addDestroyableEventListener(this.eventService, events_1.Events.EVENT_DISPLAYED_COLUMNS_WIDTH_CHANGED, this.onDisplayedColumnsWidthChanged.bind(this)); this.addDestroyableEventListener(this.eventService, events_1.Events.EVENT_SCROLL_VISIBILITY_CHANGED, this.onScrollVisibilityChanged.bind(this)); this.addDestroyableEventListener(this.eventService, events_1.Events.EVENT_FLOATING_ROW_DATA_CHANGED, this.setBodyAndHeaderHeights.bind(this)); this.addDestroyableEventListener(this.eventService, events_1.Events.EVENT_ROW_DATA_CHANGED, this.onRowDataChanged.bind(this)); this.addDestroyableEventListener(this.eventService, events_1.Events.EVENT_ITEMS_ADDED, this.onRowDataChanged.bind(this)); this.addDestroyableEventListener(this.eventService, events_1.Events.EVENT_ITEMS_REMOVED, this.onRowDataChanged.bind(this)); this.addDestroyableEventListener(this.gridOptionsWrapper, gridOptionsWrapper_1.GridOptionsWrapper.PROP_HEADER_HEIGHT, this.setBodyAndHeaderHeights.bind(this)); this.addDestroyableEventListener(this.gridOptionsWrapper, gridOptionsWrapper_1.GridOptionsWrapper.PROP_PIVOT_HEADER_HEIGHT, this.setBodyAndHeaderHeights.bind(this)); this.addDestroyableEventListener(this.gridOptionsWrapper, gridOptionsWrapper_1.GridOptionsWrapper.PROP_GROUP_HEADER_HEIGHT, this.setBodyAndHeaderHeights.bind(this)); this.addDestroyableEventListener(this.gridOptionsWrapper, gridOptionsWrapper_1.GridOptionsWrapper.PROP_PIVOT_GROUP_HEADER_HEIGHT, this.setBodyAndHeaderHeights.bind(this)); this.addDestroyableEventListener(this.gridOptionsWrapper, gridOptionsWrapper_1.GridOptionsWrapper.PROP_FLOATING_FILTERS_HEIGHT, this.setBodyAndHeaderHeights.bind(this)); }; GridPanel.prototype.addDragListeners = function () { var _this = this; if (this.forPrint // no range select when doing 'for print' || !this.gridOptionsWrapper.isEnableRangeSelection() // no range selection if no property || utils_1.Utils.missing(this.rangeController)) { return; } var containers = [this.ePinnedLeftColsContainer, this.ePinnedRightColsContainer, this.eBodyContainer, this.eFloatingTop, this.eFloatingBottom]; containers.forEach(function (container) { var params = { dragStartPixels: 0, eElement: container, onDragStart: _this.rangeController.onDragStart.bind(_this.rangeController), onDragStop: _this.rangeController.onDragStop.bind(_this.rangeController), onDragging: _this.rangeController.onDragging.bind(_this.rangeController) }; _this.dragService.addDragSource(params); _this.addDestroyFunc(function () { return _this.dragService.removeDragSource(params); }); }); }; GridPanel.prototype.addMouseEvents = function () { var _this = this; var eventNames = ['click', 'mousedown', 'dblclick', 'contextmenu', 'mouseover', 'mouseout']; eventNames.forEach(function (eventName) { var listener = _this.processMouseEvent.bind(_this, eventName); _this.eAllCellContainers.forEach(function (container) { container.addEventListener(eventName, listener); _this.addDestroyFunc(function () { return container.removeEventListener(eventName, listener); }); }); }); }; GridPanel.prototype.addKeyboardEvents = function () { var _this = this; var eventNames = ['keydown', 'keypress']; eventNames.forEach(function (eventName) { var listener = _this.processKeyboardEvent.bind(_this, eventName); _this.eAllCellContainers.forEach(function (container) { _this.addDestroyableEventListener(container, eventName, listener); }); }); }; GridPanel.prototype.addBodyViewportListener = function () { var _this = this; // we never add this when doing 'forPrint' if (this.gridOptionsWrapper.isForPrint()) { return; } // we want to listen for clicks directly on the eBodyViewport, so the user has a way of showing // the context menu if no rows are displayed, or user simply clicks outside of a cell var listener = function (mouseEvent) { var target = utils_1.Utils.getTarget(mouseEvent); if (target === _this.eBodyViewport) { // show it _this.onContextMenu(mouseEvent); _this.preventDefaultOnContextMenu(mouseEvent); } }; this.addDestroyableEventListener(this.eBodyViewport, 'contextmenu', listener); }; GridPanel.prototype.getRowForEvent = function (event) { var sourceElement = utils_1.Utils.getTarget(event); while (sourceElement) { var renderedRow = this.gridOptionsWrapper.getDomData(sourceElement, renderedRow_1.RenderedRow.DOM_DATA_KEY_RENDERED_ROW); if (renderedRow) { return renderedRow; } sourceElement = sourceElement.parentElement; } return null; }; GridPanel.prototype.processKeyboardEvent = function (eventName, keyboardEvent) { var renderedCell = this.mouseEventService.getRenderedCellForEvent(keyboardEvent); if (!renderedCell) { return; } switch (eventName) { case 'keydown': var pageScrollingKeys = [ constants_1.Constants.DIAGONAL_SCROLL_KEYS, constants_1.Constants.HORIZONTAL_SCROLL_KEYS, constants_1.Constants.VERTICAL_SCROLL_KEYS ]; var result = testKeyboardBindingGroups(pageScrollingKeys, keyboardEvent); if (result) { this.handlePageScrollingKey(result.trappedKeyboardBindingGroup.id, result.trappedKeyboardBinding.id, keyboardEvent); } else { renderedCell.onKeyDown(keyboardEvent); } break; case 'keypress': renderedCell.onKeyPress(keyboardEvent); break; } }; GridPanel.prototype.handlePageScrollingKey = function (pagingKeyGroup, pagingKey, keyboardEvent) { switch (pagingKeyGroup) { case constants_1.Constants.DIAGONAL_SCROLL_KEYS_ID: this.pageDiagonally(pagingKey); break; case constants_1.Constants.VERTICAL_SCROLL_KEYS_ID: this.pageVertically(pagingKey); break; case constants_1.Constants.HORIZONTAL_SCROLL_KEYS_ID: this.pageHorizontally(pagingKey); break; } //*************************************************************************** //Stop event defaults and propagation keyboardEvent.preventDefault(); }; //Either CTL LEFT/RIGHT GridPanel.prototype.pageHorizontally = function (pagingKey) { //*************************************************************************** //column to select var allColumns = this.columnController.getAllDisplayedColumns(); var columnToSelect = pagingKey === constants_1.Constants.KEY_CTRL_LEFT_NAME ? allColumns[0] : allColumns[allColumns.length - 1]; var horizontalScroll = { type: ScrollType.HORIZONTAL, columnToScrollTo: columnToSelect, columnToFocus: columnToSelect }; this.performScroll(horizontalScroll); }; //Either HOME OR END GridPanel.prototype.pageDiagonally = function (pagingKey) { //*************************************************************************** //where to place the newly selected cell cursor after the scroll var pageSize = this.getPrimaryScrollViewport().offsetHeight; var selectionTopDelta = pagingKey === constants_1.Constants.KEY_PAGE_HOME_NAME ? 0 : pageSize; //*************************************************************************** //where to scroll to var rowIndexToScrollTo = pagingKey === constants_1.Constants.KEY_PAGE_HOME_NAME ? 0 : this.paginationProxy.getPageLastRow(); var rowToScrollTo = this.paginationProxy.getRow(rowIndexToScrollTo); //*************************************************************************** //column to select var allColumns = this.columnController.getAllDisplayedColumns(); var columnToSelect = pagingKey === constants_1.Constants.KEY_PAGE_HOME_NAME ? allColumns[0] : allColumns[allColumns.length - 1]; var diagonalScroll = { focusedRowTopDelta: selectionTopDelta, type: ScrollType.DIAGONAL, rowToScrollTo: rowToScrollTo, columnToScrollTo: columnToSelect }; this.performScroll(diagonalScroll); }; //EITHER CTRL UP/DOWN or PAGE UP/DOWN GridPanel.prototype.pageVertically = function (pagingKey) { if (pagingKey === constants_1.Constants.KEY_CTRL_UP_NAME) { this.performScroll({ rowToScrollTo: this.paginationProxy.getRow(0), focusedRowTopDelta: 0, type: ScrollType.VERTICAL }); return; } if (pagingKey === constants_1.Constants.KEY_CTRL_DOWN_NAME) { this.performScroll({ rowToScrollTo: this.paginationProxy.getRow(this.paginationProxy.getPageLastRow()), focusedRowTopDelta: this.getPrimaryScrollViewport().offsetHeight, type: ScrollType.VERTICAL }); return; } //*********PAGING KEYS****************************************************** //*************************************************************************** //where to place the newly selected cell cursor after the scroll // before we move the scroll // a) find the top position of the current selected cell // b) find what is the delta of that compared to the current scroll var focusedCell = this.focusedCellController.getFocusedCell(); var focusedRowNode = this.paginationProxy.getRow(focusedCell.rowIndex); var focusedAbsoluteTop = focusedRowNode.rowTop; var selectionTopDelta = (focusedAbsoluteTop - this.getPrimaryScrollViewport().scrollTop) - this.paginationProxy.getPixelOffset(); //*************************************************************************** //how much to scroll: // a) One entire page from or to // b) the top of the first row in the current view // c) then find what is the row that would appear the first one in the screen and adjust it to its top pos // this will avoid having half printed rows at the top var currentPageTopmostPixel = this.getPrimaryScrollViewport().scrollTop; var currentPageTopRow = this.paginationProxy.getRowIndexAtPixel(currentPageTopmostPixel + this.paginationProxy.getPixelOffset()); var currentPageTopmostRow = this.paginationProxy.getRow(currentPageTopRow); var viewportSize = this.getPrimaryScrollViewport().offsetHeight; var maxPageSize = this.paginationProxy.getCurrentPageHeight(); var pageSize = maxPageSize < viewportSize ? maxPageSize : viewportSize; var currentTopmostRowBottom = currentPageTopmostRow.rowTop + currentPageTopmostRow.rowHeight; var toScrollUnadjusted = pagingKey == constants_1.Constants.KEY_PAGE_DOWN_NAME ? pageSize + currentTopmostRowBottom : currentTopmostRowBottom - pageSize; var nextScreenTopmostRow = this.paginationProxy.getRow(this.paginationProxy.getRowIndexAtPixel(toScrollUnadjusted)); var verticalScroll = { rowToScrollTo: nextScreenTopmostRow, focusedRowTopDelta: selectionTopDelta, type: ScrollType.VERTICAL }; this.performScroll(verticalScroll); }; // gets called by rowRenderer when new data loaded, as it will want to scroll // to the top GridPanel.prototype.scrollToTop = function () { if (!this.forPrint) { this.getPrimaryScrollViewport().scrollTop = 0; } }; //Performs any scroll GridPanel.prototype.performScroll = function (scroll) { var verticalScroll; var diagonalScroll; var horizontalScroll; var focusedCellBeforeScrolling = this.focusedCellController.getFocusedCell(); //*************************************************************************** // Scroll screen var newScrollTop; switch (scroll.type) { case ScrollType.VERTICAL: verticalScroll = scroll; this.ensureIndexVisible(verticalScroll.rowToScrollTo.rowIndex); newScrollTop = verticalScroll.rowToScrollTo.rowTop - this.paginationProxy.getPixelOffset(); this.getPrimaryScrollViewport().scrollTop = newScrollTop; break; case ScrollType.DIAGONAL: diagonalScroll = scroll; this.ensureIndexVisible(diagonalScroll.rowToScrollTo.rowIndex); newScrollTop = diagonalScroll.rowToScrollTo.rowTop - this.paginationProxy.getPixelOffset(); this.getPrimaryScrollViewport().scrollTop = newScrollTop; this.getPrimaryScrollViewport().scrollLeft = diagonalScroll.columnToScrollTo.getLeft(); break; case ScrollType.HORIZONTAL: horizontalScroll = scroll; this.getPrimaryScrollViewport().scrollLeft = horizontalScroll.columnToScrollTo.getLeft(); break; } //*************************************************************************** // This is needed so that when we try to focus on the cell is actually rendered. var refreshViewParams = { onlyBody: true, suppressKeepFocus: true }; this.rowRenderer.refreshView(refreshViewParams); //*************************************************************************** // New focused cell var focusedRowIndex; var focusedColumn; switch (scroll.type) { case ScrollType.VERTICAL: focusedRowIndex = this.paginationProxy.getRowIndexAtPixel(newScrollTop + this.paginationProxy.getPixelOffset() + verticalScroll.focusedRowTopDelta); focusedColumn = focusedCellBeforeScrolling.column; break; case ScrollType.DIAGONAL: focusedRowIndex = this.paginationProxy.getRowIndexAtPixel(newScrollTop + this.paginationProxy.getPixelOffset() + diagonalScroll.focusedRowTopDelta); focusedColumn = diagonalScroll.columnToScrollTo; break; case ScrollType.HORIZONTAL: focusedRowIndex = focusedCellBeforeScrolling.rowIndex; focusedColumn = horizontalScroll.columnToScrollTo; break; } this.focusedCellController.setFocusedCell(focusedRowIndex, focusedColumn, null, true); }; GridPanel.prototype.processMouseEvent = function (eventName, mouseEvent) { var renderedCell = this.mouseEventService.getRenderedCellForEvent(mouseEvent); if (renderedCell) { renderedCell.onMouseEvent(eventName, mouseEvent); } var renderedRow = this.getRowForEvent(mouseEvent); if (renderedRow) { renderedRow.onMouseEvent(eventName, mouseEvent); } this.preventDefaultOnContextMenu(mouseEvent); }; GridPanel.prototype.onContextMenu = function (mouseEvent) { // to allow us to debug in chrome, we ignore the event if ctrl is pressed. // not everyone wants this, so first 'if' below allows to turn this hack off. if (!this.gridOptionsWrapper.isAllowContextMenuWithControlKey()) { // then do the check if (mouseEvent.ctrlKey || mouseEvent.metaKey) { return; } } if (this.contextMenuFactory && !this.gridOptionsWrapper.isSuppressContextMenu()) { this.contextMenuFactory.showMenu(null, null, null, mouseEvent); mouseEvent.preventDefault(); } }; GridPanel.prototype.preventDefaultOnContextMenu = function (mouseEvent) { // if we don't do this, then middle click will never result in a 'click' event, as 'mousedown' // will be consumed by the browser to mean 'scroll' (as you can scroll with the middle mouse // button in the browser). so this property allows the user to receive middle button clicks if // they want. if (this.gridOptionsWrapper.isSuppressMiddleClickScrolls() && mouseEvent.which === 2) { mouseEvent.preventDefault(); } }; GridPanel.prototype.addShortcutKeyListeners = function () { var _this = this; this.eAllCellContainers.forEach(function (container) { container.addEventListener('keydown', function (event) { // if the cell the event came from is editing, then we do not // want to do the default shortcut keys, otherwise the editor // (eg a text field) would not be able to do the normal cut/copy/paste var renderedCell = _this.mouseEventService.getRenderedCellForEvent(event); if (renderedCell && renderedCell.isEditing()) { return; } if (event.ctrlKey || event.metaKey) { switch (event.which) { case constants_1.Constants.KEY_A: return _this.onCtrlAndA(event); case constants_1.Constants.KEY_C: return _this.onCtrlAndC(event); case constants_1.Constants.KEY_V: return _this.onCtrlAndV(event); case constants_1.Constants.KEY_D: return _this.onCtrlAndD(event); } } }); }); }; GridPanel.prototype.onCtrlAndA = function (event) { if (this.rangeController && this.paginationProxy.isRowsToRender()) { var rowEnd; var floatingStart; var floatingEnd; if (this.floatingRowModel.isEmpty(constants_1.Constants.FLOATING_TOP)) { floatingStart = null; } else { floatingStart = constants_1.Constants.FLOATING_TOP; } if (this.floatingRowModel.isEmpty(constants_1.Constants.FLOATING_BOTTOM)) { floatingEnd = null; rowEnd = this.paginationProxy.getTotalRowCount() - 1; } else { floatingEnd = constants_1.Constants.FLOATING_BOTTOM; rowEnd = this.floatingRowModel.getFloatingBottomRowData().length = 1; } var allDisplayedColumns = this.columnController.getAllDisplayedColumns(); if (utils_1.Utils.missingOrEmpty(allDisplayedColumns)) { return; } this.rangeController.setRange({ rowStart: 0, floatingStart: floatingStart, rowEnd: rowEnd, floatingEnd: floatingEnd, columnStart: allDisplayedColumns[0], columnEnd: allDisplayedColumns[allDisplayedColumns.length - 1] }); } event.preventDefault(); return false; }; GridPanel.prototype.onCtrlAndC = function (event) { if (!this.clipboardService) { return; } var focusedCell = this.focusedCellController.getFocusedCell(); this.clipboardService.copyToClipboard(); event.preventDefault(); // the copy operation results in loosing focus on the cell, // because of the trickery the copy logic uses with a temporary // widget. so we set it back again. if (focusedCell) { this.focusedCellController.setFocusedCell(focusedCell.rowIndex, focusedCell.column, focusedCell.floating, true); } return false; }; GridPanel.prototype.onCtrlAndV = function (event) { if (!this.rangeController) { return; } this.clipboardService.pasteFromClipboard(); return false; }; GridPanel.prototype.onCtrlAndD = function (event) { if (!this.clipboardService) { return; } this.clipboardService.copyRangeDown(); event.preventDefault(); return false; }; GridPanel.prototype.createOverlayTemplate = function (name, defaultTemplate, userProvidedTemplate) { var template = mainOverlayTemplate .replace('[OVERLAY_NAME]', name); if (userProvidedTemplate) { template = template.replace('[OVERLAY_TEMPLATE]', userProvidedTemplate); } else { template = template.replace('[OVERLAY_TEMPLATE]', defaultTemplate); } return template; }; GridPanel.prototype.createLoadingOverlayTemplate = function () { var userProvidedTemplate = this.gridOptionsWrapper.getOverlayLoadingTemplate(); var templateNotLocalised = this.createOverlayTemplate('loading', defaultLoadingOverlayTemplate, userProvidedTemplate); var localeTextFunc = this.gridOptionsWrapper.getLocaleTextFunc(); var templateLocalised = templateNotLocalised.replace('[LOADING...]', localeTextFunc('loadingOoo', 'Loading...')); return templateLocalised; }; GridPanel.prototype.createNoRowsOverlayTemplate = function () { var userProvidedTemplate = this.gridOptionsWrapper.getOverlayNoRowsTemplate(); var templateNotLocalised = this.createOverlayTemplate('no-rows', defaultNoRowsOverlayTemplate, userProvidedTemplate); var localeTextFunc = this.gridOptionsWrapper.getLocaleTextFunc(); var templateLocalised = templateNotLocalised.replace('[NO_ROWS_TO_SHOW]', localeTextFunc('noRowsToShow', 'No Rows To Show')); return templateLocalised; }; GridPanel.prototype.ensureIndexVisible = function (index) { // if for print, everything is always visible if (this.gridOptionsWrapper.isForPrint()) { return; } this.logger.log('ensureIndexVisible: ' + index); var rowCount = this.paginationProxy.getTotalRowCount(); if (typeof index !== 'number' || index < 0 || index >= rowCount) { console.warn('invalid row index for ensureIndexVisible: ' + index); return; } this.paginationProxy.goToPageWithIndex(index); var nodeAtIndex = this.paginationProxy.getRow(index); var pixelOffset = this.paginationProxy.getPixelOffset(); var rowTopPixel = nodeAtIndex.rowTop - pixelOffset; var rowBottomPixel = rowTopPixel + nodeAtIndex.rowHeight; var vRange = this.getVerticalPixelRange(); var vRangeTop = vRange.top; var vRangeBottom = vRange.bottom; var scrollShowing = this.isHorizontalScrollShowing(); if (scrollShowing) { vRangeBottom -= this.scrollWidth; } var viewportScrolledPastRow = vRangeTop > rowTopPixel; var viewportScrolledBeforeRow = vRangeBottom < rowBottomPixel; var eViewportToScroll = this.getPrimaryScrollViewport(); if (viewportScrolledPastRow) { // if row is before, scroll up with row at top eViewportToScroll.scrollTop = rowTopPixel; this.rowRenderer.drawVirtualRowsWithLock(); } else if (viewportScrolledBeforeRow) { // if row is below, scroll down with row at bottom var viewportHeight = vRangeBottom - vRangeTop; var newScrollPosition = rowBottomPixel - viewportHeight; eViewportToScroll.scrollTop = newScrollPosition; this.rowRenderer.drawVirtualRowsWithLock(); } // otherwise, row is already in view, so do nothing }; GridPanel.prototype.getPrimaryScrollViewport = function () { if (this.enableRtl && this.columnController.isPinningLeft()) { return this.ePinnedLeftColsViewport; } else if (!this.enableRtl && this.columnController.isPinningRight()) { return this.ePinnedRightColsViewport; } else { return this.eBodyViewport; } }; // + moveColumnController GridPanel.prototype.getCenterWidth = function () { return this.eBodyViewport.clientWidth; }; GridPanel.prototype.isHorizontalScrollShowing = function () { var result = utils_1.Utils.isHorizontalScrollShowing(this.eBodyViewport); return result; }; GridPanel.prototype.isVerticalScrollShowing = function () { if (this.columnController.isPinningRight()) { return utils_1.Utils.isVerticalScrollShowing(this.ePinnedRightColsViewport); } else { return utils_1.Utils.isVerticalScrollShowing(this.eBodyViewport); } }; GridPanel.prototype.isBodyVerticalScrollShowing = function () { // if the scroll is on the pinned panel, then it is never in the center panel. // if LRT, then pinning right means scroll NOT on center if (!this.enableRtl && this.columnController.isPinningRight()) { return false; } // if RTL, then pinning left means scroll NOT on center if (this.enableRtl && this.columnController.isPinningLeft()) { return false; } return utils_1.Utils.isVerticalScrollShowing(this.eBodyViewport); }; // gets called every 500 ms. we use this to set padding on right pinned column GridPanel.prototype.periodicallyCheck = function () { if (this.forPrint) { return; } this.setBottomPaddingOnPinnedRight(); this.setMarginOnFullWidthCellContainer(); this.setScrollShowing(); }; GridPanel.prototype.setScrollShowing = function () { var params = { vBody: false, hBody: false, vPinnedLeft: false, vPinnedRight: false }; if (this.enableRtl) { if (this.columnController.isPinningLeft()) { params.vPinnedLeft = this.forPrint ? false : utils_1.Utils.isVerticalScrollShowing(this.ePinnedLeftColsViewport); } else { params.vBody = utils_1.Utils.isVerticalScrollShowing(this.eBodyViewport); } } else { if (this.columnController.isPinningRight()) { params.vPinnedRight = this.forPrint ? false : utils_1.Utils.isVerticalScrollShowing(this.ePinnedRightColsViewport); } else { params.vBody = utils_1.Utils.isVerticalScrollShowing(this.eBodyViewport); } } params.hBody = utils_1.Utils.isHorizontalScrollShowing(this.eBodyViewport); this.scrollVisibleService.setScrollsVisible(params); }; // the pinned container needs extra space at the bottom, some blank space, otherwise when // vertically scrolled all the way down, the last row will be hidden behind the scrolls. // this extra padding allows the last row to be lifted above the bottom scrollbar. GridPanel.prototype.setBottomPaddingOnPinnedRight = function () { if (this.forPrint) { return; } if (this.columnController.isPinningRight()) { var bodyHorizontalScrollShowing = this.eBodyViewport.clientWidth < this.eBodyViewport.scrollWidth; if (bodyHorizontalScrollShowing) { this.ePinnedRightColsContainer.style.marginBottom = this.scrollWidth + 'px'; } else { this.ePinnedRightColsContainer.style.marginBottom = ''; } } }; GridPanel.prototype.setMarginOnFullWidthCellContainer = function () { if (this.forPrint) { return; } // if either right or bottom scrollbars are showing, we need to make sure the // fullWidthCell panel isn't covering the scrollbars. originally i tried to do this using // margin, but the overflow was not getting clipped and going into the margin, // so used border instead. dunno why it works, trial and error found the solution. if (this.enableRtl) { if (this.isVerticalScrollShowing()) { this.eFullWidthCellViewport.style.borderLeft = this.scrollWidth + 'px solid transparent'; } else { this.eFullWidthCellViewport.style.borderLeft = ''; } } else { if (this.isVerticalScrollShowing()) { this.eFullWidthCellViewport.style.borderRight = this.scrollWidth + 'px solid transparent'; } else { this.eFullWidthCellViewport.style.borderRight = ''; } } if (this.isHorizontalScrollShowing()) { this.eFullWidthCellViewport.style.borderBottom = this.scrollWidth + 'px solid transparent'; } else { this.eFullWidthCellViewport.style.borderBottom = ''; } }; GridPanel.prototype.ensureColumnVisible = function (key) { // if for print, everything is always visible if (this.gridOptionsWrapper.isForPrint()) { return; } var column = this.columnController.getGridColumn(key); if (!column) { return; } if (column.isPinned()) { console.warn('calling ensureIndexVisible on a ' + column.getPinned() + ' pinned column doesn\'t make sense for column ' + column.getColId()); return; } if (!this.columnController.isColumnDisplayed(column)) { console.warn('column is not currently visible'); return; } var colLeftPixel = column.getLeft(); var colRightPixel = colLeftPixel + column.getActualWidth(); var viewportWidth = this.eBodyViewport.clientWidth; var scrollPosition = this.getBodyViewportScrollLeft(); var bodyWidth = this.columnController.getBodyContainerWidth(); var viewportLeftPixel; var viewportRightPixel; // the logic of working out left and right viewport px is both here and in the ColumnController, // need to refactor it out to one place if (this.enableRtl) { viewportLeftPixel = bodyWidth - scrollPosition - viewportWidth; viewportRightPixel = bodyWidth - scrollPosition; } else { viewportLeftPixel = scrollPosition; viewportRightPixel = viewportWidth + scrollPosition; } var viewportScrolledPastCol = viewportLeftPixel > colLeftPixel; var viewportScrolledBeforeCol = viewportRightPixel < colRightPixel; if (viewportScrolledPastCol) { // if viewport's left side is after col's left side, scroll right to pull col into viewport at left if (this.enableRtl) { var newScrollPosition = bodyWidth - viewportWidth - colLeftPixel; this.setBodyViewportScrollLeft(newScrollPosition); } else { this.setBodyViewportScrollLeft(colLeftPixel); } } else if (viewportScrolledBeforeCol) { // if viewport's right side is before col's right side, scroll left to pull col into viewport at right if (this.enableRtl) { var newScrollPosition = bodyWidth - colRightPixel; this.setBodyViewportScrollLeft(newScrollPosition); } else { var newScrollPosition = colRightPixel - viewportWidth; this.setBodyViewportScrollLeft(newScrollPosition); } } else { // otherwise, col is already in view, so do nothing } // this will happen anyway, as the move will cause a 'scroll' event on the body, however // it is possible that the ensureColumnVisible method is called from within ag-Grid and // the caller will need to have the columns rendered to continue, which will be before // the event has been worked on (which is the case for cell navigation). this.setLeftAndRightBounds(); }; GridPanel.prototype.showLoadingOverlay = function () { if (!this.gridOptionsWrapper.isSuppressLoadingOverlay()) { this.layout.showOverlay('loading'); } }; GridPanel.prototype.showNoRowsOverlay = function () { if (!this.gridOptionsWrapper.isSuppressNoRowsOverlay()) { this.layout.showOverlay('noRows'); } }; GridPanel.prototype.hideOverlay = function () { this.layout.hideOverlay(); }; GridPanel.prototype.getWidthForSizeColsToFit = function () { var availableWidth = this.eBody.clientWidth; // if pinning right, then the scroll bar can show, however for some reason // it overlays the grid and doesn't take space. so we are only interested // in the body scroll showing. var removeVerticalScrollWidth = this.isVerticalScrollShowing(); if (removeVerticalScrollWidth) { availableWidth -= this.scrollWidth; } return availableWidth; }; // method will call itself if no available width. this covers if the grid // isn't visible, but is just about to be visible. GridPanel.prototype.sizeColumnsToFit = function (nextTimeout) { var _this = this; var availableWidth = this.getWidthForSizeColsToFit(); if (availableWidth > 0) { this.columnController.sizeColumnsToFit(availableWidth); } else { if (nextTimeout === undefined) { setTimeout(function () { _this.sizeColumnsToFit(100); }, 0); } else if (nextTimeout === 100) { setTimeout(function () { _this.sizeColumnsToFit(-1); }, 100); } else { console.log('ag-Grid: tried to call sizeColumnsToFit() but the grid is coming back with ' + 'zero width, maybe the grid is not visible yet on the screen?'); } } }; GridPanel.prototype.getBodyContainer = function () { return this.eBodyContainer; }; GridPanel.prototype.getDropTargetBodyContainers = function () { if (this.forPrint) { return [this.eBodyContainer, this.eFloatingTopContainer, this.eFloatingBottomContainer]; } else { return [this.eBodyViewport, this.eFloatingTopViewport, this.eFloatingBottomViewport]; } }; GridPanel.prototype.getBodyViewport = function () { return this.eBodyViewport; }; GridPanel.prototype.getDropTargetLeftContainers = function () { if (this.forPrint) { return []; } else { return [this.ePinnedLeftColsViewport, this.ePinnedLeftFloatingBottom, this.ePinnedLeftFloatingTop]; } }; GridPanel.prototype.getDropTargetPinnedRightContainers = function () { if (this.forPrint) { return []; } else { return [this.ePinnedRightColsViewport, this.ePinnedRightFloatingBottom, this.ePinnedRightFloatingTop]; } }; GridPanel.prototype.getHeaderContainer = function () { return this.eHeaderContainer; }; GridPanel.prototype.getHeaderOverlay = function () { return this.eHeaderOverlay; }; GridPanel.prototype.getRoot = function () { return this.eRoot; }; GridPanel.prototype.getPinnedLeftHeader = function () { return this.ePinnedLeftHeader; }; GridPanel.prototype.getPinnedRightHeader = function () { return this.ePinnedRightHeader; }; GridPanel.prototype.queryHtmlElement = function (selector) { return this.eRoot.querySelector(selector); }; GridPanel.prototype.loadTemplate = function () { // the template we use is different when doing 'for print' var template = this.forPrint ? gridForPrintHtml : gridHtml; this.eRoot = utils_1.Utils.loadTemplate(template); // parts of the CSS need to know if we are in 'for print' mode or not, // so we add a class to allow applying CSS based on this. var scrollClass = this.forPrint ? 'ag-no-scrolls' : 'ag-scrolls'; utils_1.Utils.addCssClass(this.eRoot, scrollClass); }; GridPanel.prototype.findElements = function () { if (this.forPrint) { this.eHeaderContainer = this.queryHtmlElement('.ag-header-container'); this.eBodyContainer = this.queryHtmlElement('.ag-body-container'); this.eFloatingTopContainer = this.queryHtmlElement('.ag-floating-top-container'); this.eFloatingBottomContainer = this.queryHtmlElement('.ag-floating-bottom-container'); this.eAllCellContainers = [this.eBodyContainer, this.eFloatingTopContainer, this.eFloatingBottomContainer]; var containers = { body: new rowContainerComponent_1.RowContainerComponent({ eContainer: this.eBodyContainer, useDocumentFragment: true }), fullWidth: null, pinnedLeft: null, pinnedRight: null, floatingTop: new rowContainerComponent_1.RowContainerComponent({ eContainer: this.eFloatingTopContainer }), floatingTopPinnedLeft: null, floatingTopPinnedRight: null, floatingTopFullWidth: null, floatingBottom: new rowContainerComponent_1.RowContainerComponent({ eContainer: this.eFloatingBottomContainer }), floatingBottomPinnedLeft: null, floatingBottomPinnedRight: null, floatingBottomFullWith: null }; this.rowContainerComponents = containers; // when doing forPrint, we don't have any fullWidth containers, instead we add directly to the main // containers. this works in forPrint only as there are no pinned columns (no need for fullWidth to // span pinned columns) and the rows are already the full width of the grid (the reason for fullWidth) containers.fullWidth = containers.body; containers.floatingBottomFullWith = containers.floatingBottom; containers.floatingTopFullWidth = containers.floatingTop; } else { this.eBody = this.queryHtmlElement('.ag-body'); this.eBodyContainer = this.queryHtmlElement('.ag-body-container'); this.eBodyViewport = this.queryHtmlElement('.ag-body-viewport'); this.eBodyViewportWrapper = this.queryHtmlElement('.ag-body-viewport-wrapper'); this.eFullWidthCellContainer = this.queryHtmlElement('.ag-full-width-container'); this.eFullWidthCellViewport = this.queryHtmlElement('.ag-full-width-viewport'); this.ePinnedLeftColsContainer = this.queryHtmlElement('.ag-pinned-left-cols-container'); this.ePinnedRightColsContainer = this.queryHtmlElement('.ag-pinned-right-cols-container'); this.ePinnedLeftColsViewport = this.queryHtmlElement('.ag-pinned-left-cols-viewport'); this.ePinnedRightColsViewport = this.queryHtmlElement('.ag-pinned-right-cols-viewport'); this.ePinnedLeftHeader = this.queryHtmlElement('.ag-pinned-left-header'); this.ePinnedRightHeader = this.queryHtmlElement('.ag-pinned-right-header'); this.eHeader = this.queryHtmlElement('.ag-header'); this.eHeaderContainer = this.queryHtmlElement('.ag-header-container'); this.eHeaderOverlay = this.queryHtmlElement('.ag-header-overlay'); this.eHeaderViewport = this.queryHtmlElement('.ag-header-viewport'); this.eFloatingTop = this.queryHtmlElement('.ag-floating-top'); this.ePinnedLeftFloatingTop = this.queryHtmlElement('.ag-pinned-left-floating-top'); this.ePinnedRightFloatingTop = this.queryHtmlElement('.ag-pinned-right-floating-top'); this.eFloatingTopContainer = this.queryHtmlElement('.ag-floating-top-container'); this.eFloatingTopViewport = this.queryHtmlElement('.ag-floating-top-viewport'); this.eFloatingTopFullWidthCellContainer = this.queryHtmlElement('.ag-floating-top-full-width-container'); this.eFloatingBottom = this.queryHtmlElement('.ag-floating-bottom'); this.ePinnedLeftFloatingBottom = this.queryHtmlElement('.ag-pinned-left-floating-bottom'); this.ePinnedRightFloatingBottom = this.queryHtmlElement('.ag-pinned-right-floating-bottom'); this.eFloatingBottomContainer = this.queryHtmlElement('.ag-floating-bottom-container'); this.eFloatingBottomViewport = this.queryHtmlElement('.ag-floating-bottom-viewport'); this.eFloatingBottomFullWidthCellContainer = this.queryHtmlElement('.ag-floating-bottom-full-width-container'); this.eAllCellContainers = [ this.ePinnedLeftColsContainer, this.ePinnedRightColsContainer, this.eBodyContainer, this.eFloatingTop, this.eFloatingBottom, this.eFullWidthCellContainer ]; this.rowContainerComponents = { body: new rowContainerComponent_1.RowContainerComponent({ eContainer: this.eBodyContainer, eViewport: this.eBodyViewport, useDocumentFragment: true }), fullWidth: new rowContainerComponent_1.RowContainerComponent({ eContainer: this.eFullWidthCellContainer, hideWhenNoChildren: true, eViewport: this.eFullWidthCellViewport }), pinnedLeft: new rowContainerComponent_1.RowContainerComponent({ eContainer: this.ePinnedLeftColsContainer, eViewport: this.ePinnedLeftColsViewport, useDocumentFragment: true }), pinnedRight: new rowContainerComponent_1.RowContainerComponent({ eContainer: this.ePinnedRightColsContainer, eViewport: this.ePinnedRightColsViewport, useDocumentFragment: true }), floatingTop: new rowContainerComponent_1.RowContainerComponent({ eContainer: this.eFloatingTopContainer }), floatingTopPinnedLeft: new rowContainerComponent_1.RowContainerComponent({ eContainer: this.ePinnedLeftFloatingTop }), floatingTopPinnedRight: new rowContainerComponent_1.RowContainerComponent({ eContainer: this.ePinnedRightFloatingTop }), floatingTopFullWidth: new rowContainerComponent_1.RowContainerComponent({ eContainer: this.eFloatingTopFullWidthCellContainer, hideWhenNoChildren: true }), floatingBottom: new rowContainerComponent_1.RowContainerComponent({ eContainer: this.eFloatingBottomContainer }), floatingBottomPinnedLeft: new rowContainerComponent_1.RowContainerComponent({ eContainer: this.ePinnedLeftFloatingBottom }), floatingBottomPinnedRight: new rowContainerComponent_1.RowContainerComponent({ eContainer: this.ePinnedRightFloatingBottom }), floatingBottomFullWith: new rowContainerComponent_1.RowContainerComponent({ eContainer: this.eFloatingBottomFullWidthCellContainer, hideWhenNoChildren: true }), }; this.addMouseWheelEventListeners(); } }; GridPanel.prototype.getRowContainers = function () { return this.rowContainerComponents; }; GridPanel.prototype.addMouseWheelEventListeners = function () { // IE9, Chrome, Safari, Opera use 'mousewheel', Firefox uses 'DOMMouseScroll' this.addDestroyableEventListener(this.eBodyViewport, 'mousewheel', this.centerMouseWheelListener.bind(this)); this.addDestroyableEventListener(this.eBodyViewport, 'DOMMouseScroll', this.centerMouseWheelListener.bind(this)); if (this.enableRtl) { this.addDestroyableEventListener(this.ePinnedRightColsViewport, 'mousewheel', this.genericMouseWheelListener.bind(this)); this.addDestroyableEventListener(this.ePinnedRightColsViewport, 'DOMMouseScroll', this.genericMouseWheelListener.bind(this)); } else { this.addDestroyableEventListener(this.ePinnedLeftColsViewport, 'mousewheel', this.genericMouseWheelListener.bind(this)); this.addDestroyableEventListener(this.ePinnedLeftColsViewport, 'DOMMouseScroll', this.genericMouseWheelListener.bind(this)); } }; GridPanel.prototype.getHeaderViewport = function () { return this.eHeaderViewport; }; GridPanel.prototype.centerMouseWheelListener = function (event) { // we are only interested in mimicking the mouse wheel if we are not scrolling on the middle, // otherwise the body has scrolls and the mouse wheel works for free var bodyVScrollShowing = this.isBodyVerticalScrollActive(); if (!bodyVScrollShowing) { var targetPanel = this.enableRtl ? this.ePinnedLeftColsViewport : this.ePinnedRightColsViewport; return this.generalMouseWheelListener(event, targetPanel); } }; // used for listening to mouse wheel events on 1) left pinned and also the 2) fullWidthCell components. // the fullWidthCell listener is added in renderedRow, hence public. GridPanel.prototype.genericMouseWheelListener = function (event) { var targetPanel; var bodyVScrollActive = this.isBodyVerticalScrollActive(); if (bodyVScrollActive) { targetPanel = this.eBodyViewport; } else { targetPanel = this.enableRtl ? this.ePinnedLeftColsViewport : this.ePinnedRightColsViewport; } return this.generalMouseWheelListener(event, targetPanel); }; GridPanel.prototype.generalMouseWheelListener = function (event, targetPanel) { var wheelEvent = utils_1.Utils.normalizeWheel(event); // we need to detect in which direction scroll is happening to allow trackpads scroll horizontally // horizontal scroll if (Math.abs(wheelEvent.pixelX) > Math.abs(wheelEvent.pixelY)) { var newLeftPosition = this.eBodyViewport.scrollLeft + wheelEvent.pixelX; this.eBodyViewport.scrollLeft = newLeftPosition; } else { var newTopPosition = targetPanel.scrollTop + wheelEvent.pixelY; targetPanel.scrollTop = newTopPosition; } // allow the option to pass mouse wheel events to the browser // https://github.com/ceolter/ag-grid/issues/800 // in the future, this should be tied in with 'forPrint' option, or have an option 'no vertical scrolls' if (!this.gridOptionsWrapper.isSuppressPreventDefaultOnMouseWheel()) { // if we don't prevent default, then the whole browser will scroll also as well as the grid event.preventDefault(); } return false; }; GridPanel.prototype.onDisplayedColumnsChanged = function () { this.setPinnedContainersVisible(); this.setBodyAndHeaderHeights(); this.setLeftAndRightBounds(); }; GridPanel.prototype.onDisplayedColumnsWidthChanged = function () { this.setWidthsOfContainers(); this.setLeftAndRightBounds(); if (this.enableRtl) { // because RTL is all backwards, a change in the width of the row // can cause a change in the scroll position, without a scroll event, // because the scroll position in RTL is a function that depends on // the width. to be convinced of this, take out this line, enable RTL, // scroll all the way to the left and then resize a column this.horizontallyScrollHeaderCenterAndFloatingCenter(); } }; GridPanel.prototype.onScrollVisibilityChanged = function () { this.setWidthsOfContainers(); }; GridPanel.prototype.setWidthsOfContainers = function () { var mainRowWidth = this.columnController.getBodyContainerWidth() + 'px'; this.eBodyContainer.style.width = mainRowWidth; if (this.forPrint) { // pinned col doesn't exist when doing forPrint return; } this.eFloatingBottomContainer.style.width = mainRowWidth; this.eFloatingTopContainer.style.width = mainRowWidth; this.setPinnedLeftWidth(); this.setPinnedRightWidth(); }; GridPanel.prototype.setPinnedLeftWidth = function () { var pinnedLeftWidth = this.scrollVisibleService.getPinnedLeftWidth() + 'px'; var pinnedLeftWidthWithScroll = this.scrollVisibleService.getPinnedLeftWithScrollWidth() + 'px'; this.ePinnedLeftColsViewport.style.width = pinnedLeftWidthWithScroll; this.eBodyViewportWrapper.style.marginLeft = pinnedLeftWidthWithScroll; this.ePinnedLeftFloatingBottom.style.width = pinnedLeftWidthWithScroll; this.ePinnedLeftFloatingTop.style.width = pinnedLeftWidthWithScroll; this.ePinnedLeftColsContainer.style.width = pinnedLeftWidth; }; GridPanel.prototype.setPinnedRightWidth = function () { var pinnedRightWidth = this.scrollVisibleService.getPinnedRightWidth() + 'px'; var pinnedRightWidthWithScroll = this.scrollVisibleService.getPinnedRightWithScrollWidth() + 'px'; this.ePinnedRightColsViewport.style.width = pinnedRightWidthWithScroll; this.eBodyViewportWrapper.style.marginRight = pinnedRightWidthWithScroll; this.ePinnedRightFloatingBottom.style.width = pinnedRightWidthWithScroll; this.ePinnedRightFloatingTop.style.width = pinnedRightWidthWithScroll; this.ePinnedRightColsContainer.style.width = pinnedRightWidth; }; GridPanel.prototype.setPinnedContainersVisible = function () { // no need to do this if not using scrolls if (this.forPrint) { return; } var changeDetected = false; // if we are v scrolling, then one of these will have the scroll position. // we us this inside the if(changedDetected), so we don't always use it, however // it is changed when we make a pinned panel not visible, so we have to check it // before we change display on the pinned panels var scrollTop = Math.max(this.eBodyViewport.scrollTop, this.ePinnedLeftColsViewport.scrollTop, this.ePinnedRightColsViewport.scrollTop); var showLeftPinned = this.columnController.isPinningLeft(); if (showLeftPinned !== this.pinningLeft) { this.pinningLeft = showLeftPinned; this.ePinnedLeftHeader.style.display = showLeftPinned ? 'inline-block' : 'none'; this.ePinnedLeftColsViewport.style.display = showLeftPinned ? 'inline' : 'none'; changeDetected = true; } var showRightPinned = this.columnController.isPinningRight(); if (showRightPinned !== this.pinningRight) { this.pinningRight = showRightPinned; this.ePinnedRightHeader.style.display = showRightPinned ? 'inline-block' : 'none'; this.ePinnedRightColsViewport.style.display = showRightPinned ? 'inline' : 'none'; changeDetected = true; } if (changeDetected) { var bodyVScrollActive = this.isBodyVerticalScrollActive(); this.eBodyViewport.style.overflowY = bodyVScrollActive ? 'auto' : 'hidden'; // the body either uses it's scroll (when scrolling) or it's style.top // (when following the scroll of a pinned section), so we need to set it // back when changing from one to the other if (bodyVScrollActive) { this.eBodyContainer.style.top = '0px'; } else { this.eBodyViewport.scrollTop = 0; } // when changing the primary scroll viewport, we copy over the scroll position, // eg if body was getting scrolled and we were at position 100px, then we start // pinning and pinned viewport is now the primary, we need to set it to 100px var primaryScrollViewport = this.getPrimaryScrollViewport(); primaryScrollViewport.scrollTop = scrollTop; // this adjusts the scroll position of all the faking panels. they should already // be correct except body which has potentially just turned to be fake. this.fakeVerticalScroll(scrollTop); } }; // init, layoutChanged, floatingDataChanged, headerHeightChanged GridPanel.prototype.setBodyAndHeaderHeights = function () { if (this.forPrint) { // if doing 'for print', then the header and footers are laid // out naturally by the browser. it whatever size that's needed to fit. return; } var heightOfContainer = this.layout.getCentreHeight(); if (!heightOfContainer) { return; } var headerRowCount = this.columnController.getHeaderRowCount(); var totalHeaderHeight; var numberOfFloating = 0; var groupHeight; var headerHeight; if (!this.columnController.isPivotMode()) { utils_1.Utils.removeCssClass(this.eHeader, 'ag-pivot-on'); utils_1.Utils.addCssClass(this.eHeader, 'ag-pivot-off'); if (this.gridOptionsWrapper.isFloatingFilter()) { headerRowCount++; } numberOfFloating = (this.gridOptionsWrapper.isFloatingFilter()) ? 1 : 0; groupHeight = this.gridOptionsWrapper.getGroupHeaderHeight(); headerHeight = this.gridOptionsWrapper.getHeaderHeight(); } else { utils_1.Utils.removeCssClass(this.eHeader, 'ag-pivot-off'); utils_1.Utils.addCssClass(this.eHeader, 'ag-pivot-on'); numberOfFloating = 0; groupHeight = this.gridOptionsWrapper.getPivotGroupHeaderHeight(); headerHeight = this.gridOptionsWrapper.getPivotHeaderHeight(); } var numberOfNonGroups = 1 + numberOfFloating; var numberOfGroups = headerRowCount - numberOfNonGroups; totalHeaderHeight = numberOfFloating * this.gridOptionsWrapper.getFloatingFiltersHeight(); totalHeaderHeight += numberOfGroups * groupHeight; totalHeaderHeight += headerHeight; this.eHeader.style['height'] = totalHeaderHeight + 'px'; // padding top covers the header and the floating rows on top var floatingTopHeight = this.floatingRowModel.getFloatingTopTotalHeight(); var paddingTop = totalHeaderHeight + floatingTopHeight; // bottom is just the bottom floating rows var floatingBottomHeight = this.floatingRowModel.getFloatingBottomTotalHeight(); var floatingBottomTop = heightOfContainer - floatingBottomHeight; var bodyHeight = heightOfContainer - totalHeaderHeight - floatingBottomHeight - floatingTopHeight; this.eBody.style.top = paddingTop + 'px'; this.eBody.style.height = bodyHeight + 'px'; this.eFloatingTop.style.top = totalHeaderHeight + 'px'; this.eFloatingTop.style.height = floatingTopHeight + 'px'; this.eFloatingBottom.style.height = floatingBottomHeight + 'px'; this.eFloatingBottom.style.top = floatingBottomTop + 'px'; this.ePinnedLeftColsViewport.style.height = bodyHeight + 'px'; this.ePinnedRightColsViewport.style.height = bodyHeight + 'px'; // bodyHeight property is used by pagination service, that may change number of rows // in this page based on the height of the grid if (this.bodyHeight !== bodyHeight) { this.bodyHeight = bodyHeight; this.eventService.dispatchEvent(events_1.Events.EVENT_BODY_HEIGHT_CHANGED); } }; GridPanel.prototype.getBodyHeight = function () { return this.bodyHeight; }; GridPanel.prototype.setHorizontalScrollPosition = function (hScrollPosition) { this.eBodyViewport.scrollLeft = hScrollPosition; }; // tries to scroll by pixels, but returns what the result actually was GridPanel.prototype.scrollHorizontally = function (pixels) { var oldScrollPosition = this.eBodyViewport.scrollLeft; this.setHorizontalScrollPosition(oldScrollPosition + pixels); var newScrollPosition = this.eBodyViewport.scrollLeft; return newScrollPosition - oldScrollPosition; }; GridPanel.prototype.addScrollListener = function () { var _this = this; // if printing, then no scrolling, so no point in listening for scroll events if (this.forPrint) { return; } var wrapWithDebounce = function (func) { if (_this.useScrollLag) { return _this.debounce.bind(_this, func); } else { return func; } }; var bodyScrollListener = wrapWithDebounce(this.onBodyScroll.bind(this)); this.addDestroyableEventListener(this.eBodyViewport, 'scroll', bodyScrollListener); // below we add two things: // pinnedScrollListener -> when pinned panel with scrollbar gets scrolled, it updates body and other pinned // suppressScroll -> stops scrolling when pinned panel was moved - which can only happen when user is navigating // in the pinned container, as the pinned col should never scroll. so we rollback the scroll on the pinned. var onPinnedLeftVerticalScroll = this.onVerticalScroll.bind(this, this.ePinnedLeftColsViewport); var onPinnedRightVerticalScroll = this.onVerticalScroll.bind(this, this.ePinnedRightColsViewport); if (this.enableRtl) { var pinnedScrollListener = wrapWithDebounce(onPinnedLeftVerticalScroll); this.addDestroyableEventListener(this.ePinnedLeftColsViewport, 'scroll', pinnedScrollListener); var suppressRightScroll = function () { return _this.ePinnedRightColsViewport.scrollTop = 0; }; this.addDestroyableEventListener(this.ePinnedRightColsViewport, 'scroll', suppressRightScroll); } else { var pinnedScrollListener = wrapWithDebounce(onPinnedRightVerticalScroll); this.addDestroyableEventListener(this.ePinnedRightColsViewport, 'scroll', pinnedScrollListener); var suppressLeftScroll = function () { return _this.ePinnedLeftColsViewport.scrollTop = 0; }; this.addDestroyableEventListener(this.ePinnedLeftColsViewport, 'scroll', suppressLeftScroll); } var suppressCenterScroll = function () { if (_this.getPrimaryScrollViewport() !== _this.eBodyViewport) { _this.eBodyViewport.scrollTop = 0; } }; this.addDestroyableEventListener(this.eBodyViewport, 'scroll', suppressCenterScroll); this.addIEPinFix(onPinnedRightVerticalScroll, onPinnedLeftVerticalScroll); }; GridPanel.prototype.onBodyScroll = function () { this.onBodyHorizontalScroll(); this.onBodyVerticalScroll(); }; GridPanel.prototype.onBodyHorizontalScroll = function () { var newLeftPosition = this.eBodyViewport.scrollLeft; if (newLeftPosition !== this.lastLeftPosition) { this.eventService.dispatchEvent(events_1.Events.EVENT_BODY_SCROLL, { direction: 'horizontal' }); this.lastLeftPosition = newLeftPosition; this.horizontallyScrollHeaderCenterAndFloatingCenter(); this.masterSlaveService.fireHorizontalScrollEvent(newLeftPosition); this.setLeftAndRightBounds(); } }; GridPanel.prototype.onBodyVerticalScroll = function () { var bodyVScrollActive = this.isBodyVerticalScrollActive(); if (bodyVScrollActive) { this.onVerticalScroll(this.eBodyViewport); } }; GridPanel.prototype.onVerticalScroll = function (sourceElement) { var newTopPosition = sourceElement.scrollTop; if (newTopPosition !== this.lastTopPosition) { this.eventService.dispatchEvent(events_1.Events.EVENT_BODY_SCROLL, { direction: 'vertical' }); this.lastTopPosition = newTopPosition; this.fakeVerticalScroll(newTopPosition); this.rowRenderer.drawVirtualRowsWithLock(); } }; // if LTR, we hide body scroll if pinning right (as scroll is in right pinned), // if RTL, we hide body scroll if pinning left (as scroll is in left pinned) GridPanel.prototype.isBodyVerticalScrollActive = function () { var pinningRight = this.columnController.isPinningRight(); var pinningLeft = this.columnController.isPinningLeft(); var centerHasScroll = this.enableRtl ? !pinningLeft : !pinningRight; return centerHasScroll; }; // this bit is a fix / hack for IE due to this: // https://www.ag-grid.com/forum/showthread.php?tid=4303 // it gets the left panel to reposition itself after a model change GridPanel.prototype.addIEPinFix = function (onPinnedRightScroll, onPinnedLeftScroll) { var _this = this; var listener = function () { if (_this.columnController.isPinningRight()) { setTimeout(function () { if (_this.enableRtl) { onPinnedLeftScroll(); } else { onPinnedRightScroll(); } }, 0); } }; this.addDestroyableEventListener(this.eventService, events_1.Events.EVENT_MODEL_UPDATED, listener); }; // this gets called whenever a change in the viewport, so we can inform column controller it has to work // out the virtual columns again. gets called from following locations: // + ensureColVisible, scroll, init, layoutChanged, displayedColumnsChanged GridPanel.prototype.setLeftAndRightBounds = function () { if (this.gridOptionsWrapper.isForPrint()) { return; } var scrollWidth = this.eBodyViewport.clientWidth; var scrollPosition = this.getBodyViewportScrollLeft(); this.columnController.setVirtualViewportPosition(scrollWidth, scrollPosition); }; GridPanel.prototype.isUseScrollLag = function () { // if we are in IE or Safari, then we only redraw if there was no scroll event // in the 50ms following this scroll event. without this, these browsers have // a bad scrolling feel, where the redraws clog the scroll experience // (makes the scroll clunky and sticky). this method is like throttling // the scroll events. // let the user override scroll lag option if (this.gridOptionsWrapper.isSuppressScrollLag()) { return false; } else if (this.gridOptionsWrapper.getIsScrollLag()) { return this.gridOptionsWrapper.getIsScrollLag()(); } else { return utils_1.Utils.isBrowserIE() || utils_1.Utils.isBrowserSafari(); } }; GridPanel.prototype.debounce = function (callback) { var _this = this; if (this.requestAnimationFrameExists && utils_1.Utils.isBrowserSafari()) { if (!this.scrollLagTicking) { this.scrollLagTicking = true; requestAnimationFrame(function () { callback(); _this.scrollLagTicking = false; }); } } else { this.scrollLagCounter++; var scrollLagCounterCopy = this.scrollLagCounter; setTimeout(function () { if (_this.scrollLagCounter === scrollLagCounterCopy) { callback(); } }, 50); } }; GridPanel.prototype.getBodyViewportScrollLeft = function () { if (this.forPrint) { return 0; } // we defer to a util, as how you calculated scrollLeft when doing RTL depends on the browser return utils_1.Utils.getScrollLeft(this.eBodyViewport, this.enableRtl); }; GridPanel.prototype.setBodyViewportScrollLeft = function (value) { if (this.forPrint) { return; } // we defer to a util, as how you calculated scrollLeft when doing RTL depends on the browser utils_1.Utils.setScrollLeft(this.eBodyViewport, value, this.enableRtl); }; GridPanel.prototype.horizontallyScrollHeaderCenterAndFloatingCenter = function () { var scrollLeft = this.getBodyViewportScrollLeft(); var offset = this.enableRtl ? scrollLeft : -scrollLeft; this.eHeaderContainer.style.left = offset + 'px'; this.eFloatingBottomContainer.style.left = offset + 'px'; this.eFloatingTopContainer.style.left = offset + 'px'; }; // we say fake scroll as only one panel (left, right or body) has scrolls, // the other panels mimic the scroll by getting it's top position updated. GridPanel.prototype.fakeVerticalScroll = function (position) { if (this.enableRtl) { // RTL // if pinning left, then body scroll is faking var pinningLeft = this.columnController.isPinningLeft(); if (pinningLeft) { this.eBodyContainer.style.top = -position + 'px'; } // right is always faking this.ePinnedRightColsContainer.style.top = -position + 'px'; } else { // LTR // if pinning right, then body scroll is faking var pinningRight = this.columnController.isPinningRight(); if (pinningRight) { this.eBodyContainer.style.top = -position + 'px'; } // left is always faking this.ePinnedLeftColsContainer.style.top = -position + 'px'; } // always scroll fullWidth container, as this is never responsible for a scroll this.eFullWidthCellContainer.style.top = -position + 'px'; }; GridPanel.prototype.addScrollEventListener = function (listener) { this.eBodyViewport.addEventListener('scroll', listener); }; GridPanel.prototype.removeScrollEventListener = function (listener) { this.eBodyViewport.removeEventListener('scroll', listener); }; return GridPanel; }(beanStub_1.BeanStub)); __decorate([ context_1.Autowired('masterSlaveService'), __metadata("design:type", masterSlaveService_1.MasterSlaveService) ], GridPanel.prototype, "masterSlaveService", void 0); __decorate([ context_1.Autowired('gridOptionsWrapper'), __metadata("design:type", gridOptionsWrapper_1.GridOptionsWrapper) ], GridPanel.prototype, "gridOptionsWrapper", void 0); __decorate([ context_1.Autowired('columnController'), __metadata("design:type", columnController_1.ColumnController) ], GridPanel.prototype, "columnController", void 0); __decorate([ context_1.Autowired('rowRenderer'), __metadata("design:type", rowRenderer_1.RowRenderer) ], GridPanel.prototype, "rowRenderer", void 0); __decorate([ context_1.Autowired('floatingRowModel'), __metadata("design:type", floatingRowModel_1.FloatingRowModel) ], GridPanel.prototype, "floatingRowModel", void 0); __decorate([ context_1.Autowired('eventService'), __metadata("design:type", eventService_1.EventService) ], GridPanel.prototype, "eventService", void 0); __decorate([ context_1.Autowired('paginationProxy'), __metadata("design:type", paginationProxy_1.PaginationProxy) ], GridPanel.prototype, "paginationProxy", void 0); __decorate([ context_1.Optional('rangeController'), __metadata("design:type", Object) ], GridPanel.prototype, "rangeController", void 0); __decorate([ context_1.Autowired('dragService'), __metadata("design:type", dragService_1.DragService) ], GridPanel.prototype, "dragService", void 0); __decorate([ context_1.Autowired('selectionController'), __metadata("design:type", selectionController_1.SelectionController) ], GridPanel.prototype, "selectionController", void 0); __decorate([ context_1.Optional('clipboardService'), __metadata("design:type", Object) ], GridPanel.prototype, "clipboardService", void 0); __decorate([ context_1.Autowired('csvCreator'), __metadata("design:type", csvCreator_1.CsvCreator) ], GridPanel.prototype, "csvCreator", void 0); __decorate([ context_1.Autowired('mouseEventService'), __metadata("design:type", mouseEventService_1.MouseEventService) ], GridPanel.prototype, "mouseEventService", void 0); __decorate([ context_1.Autowired('focusedCellController'), __metadata("design:type", focusedCellController_1.FocusedCellController) ], GridPanel.prototype, "focusedCellController", void 0); __decorate([ context_1.Autowired('$scope'), __metadata("design:type", Object) ], GridPanel.prototype, "$scope", void 0); __decorate([ context_1.Autowired('scrollVisibleService'), __metadata("design:type", scrollVisibleService_1.ScrollVisibleService) ], GridPanel.prototype, "scrollVisibleService", void 0); __decorate([ context_1.Optional('contextMenuFactory'), __metadata("design:type", Object) ], GridPanel.prototype, "contextMenuFactory", void 0); __decorate([ context_1.Autowired('frameworkFactory'), __metadata("design:type", Object) ], GridPanel.prototype, "frameworkFactory", void 0); __decorate([ __param(0, context_1.Qualifier('loggerFactory')), __metadata("design:type", Function), __metadata("design:paramtypes", [logger_1.LoggerFactory]), __metadata("design:returntype", void 0) ], GridPanel.prototype, "agWire", null); __decorate([ context_1.PreDestroy, __metadata("design:type", Function), __metadata("design:paramtypes", []), __metadata("design:returntype", void 0) ], GridPanel.prototype, "destroy", null); __decorate([ context_1.PostConstruct, __metadata("design:type", Function), __metadata("design:paramtypes", []), __metadata("design:returntype", void 0) ], GridPanel.prototype, "init", null); GridPanel = __decorate([ context_1.Bean('gridPanel') ], GridPanel); exports.GridPanel = GridPanel; var ScrollType; (function (ScrollType) { ScrollType[ScrollType["HORIZONTAL"] = 0] = "HORIZONTAL"; ScrollType[ScrollType["VERTICAL"] = 1] = "VERTICAL"; ScrollType[ScrollType["DIAGONAL"] = 2] = "DIAGONAL"; })(ScrollType || (ScrollType = {})); function testKeyboardBindingGroups(keyboardBindingGroups, event) { for (var i = 0; i < keyboardBindingGroups.length; i++) { var keyboardBindingGroup = keyboardBindingGroups[i]; for (var j = 0; j < keyboardBindingGroup.bindings.length; j++) { var keyboardBinding = keyboardBindingGroup.bindings[j]; if (testKeyboardBinding(keyboardBinding, event)) { return { trappedKeyboardBinding: keyboardBinding, trappedKeyboardBindingGroup: keyboardBindingGroup }; } } } return null; } function testKeyboardBinding(keyboardBinding, event) { var key = event.which || event.keyCode; return (keyboardBinding.ctlRequired === event.ctrlKey) && (keyboardBinding.keyCode === key) && (keyboardBinding.altRequired === event.altKey); }
// =SECTION Setup // Local config overrides var config = localStorage.getItem("interactiveOverrides"); if (config) { config = JSON.parse(config); window.TogetherJSConfig = config; for (var a in config) { TogetherJS.config(a, config[a]); } } Test.require("ui", "chat", "util", "session", "jquery", "storage", "peers", "cursor", "windowing", "elementFinder", "templates-en-US"); // => Loaded ... printChained( Test.resetSettings(), storage.settings.set("seenIntroDialog", true), storage.settings.set("seenWalkthrough", true), storage.settings.set("dontShowRtcInfo", true), Test.startTogetherJS()); // => ... function addPeer(id) { var name = "Faker"; if (id) { name += " " + id; } id = id || 'faker'; var color = "#" + Math.floor(Math.random() * 0xffffff).toString(16); Test.newPeer({ name: name, color: color, clientId: id }); var len = peers.getAllPeers().length; var pageHeight = $(document).height(); var left = (len * 40) % $(window).width(); var top = len % 2 ? (len * 10) : (pageHeight - 100 - len * 10); Test.incoming({ type: "cursor-update", top: top, left: left, clientId: id }); Test.incoming({ type: "scroll-update", clientId: id, position: { location: "body", offset: 20, absoluteTop: 20, documentHeight: $(document).height() } }); } function pick(seq) { if (! seq) { seq = peers.getAllPeers(true); } return seq[Math.floor(Math.random() * seq.length)]; } addPeer(); // => ... // =SECTION Controls Test.addControl( $("<button>Animate in cursor/box</button>").click(function () { //$(".togetherjs-cursor").fadeOut(); }), $("<button>Animate out cursor/box</button>").click(function () { //$(".togetherjs-cursor").fadeOut(); }), $("<button>Faker Join</button>").click(function () { addPeer(); }), $("<button>Join Random</button>").click(function () { addPeer("faker-" + Math.floor(Math.random() * 1000)); }), $('<button>Leave</button>').click(function () { var peer = pick(); Test.incoming({ type: "bye", clientId: peer.id }); }), $('<button>Decline</button>').click(function () { var peer = pick(); Test.incoming({ type: "bye", clientId: peer.id, reason: "declined-join" }); }) ); Test.addControl( $('<input placeholder="Change Faker URL">').keypress(function (ev) { if (ev.which == 13) { Test.newPeer({url: ev.target.value}); ev.target.value = ""; } }), $('<button>Other URL</button>').click(function () { Test.newPeer({url: "http://example.com/?" + Date.now()}); }), $('<button>Same URL</button>').click(function () { var url = location.href.replace(/\#.*/, ""); Test.newPeer({url: url}); }) ); Test.addControl($('<button>Nudge Me</button>').click(function () { var peer = pick(); Test.incoming({ type: "url-change-nudge", clientId: peer.id, url: peer.url, to: peers.Self.id }); })); var focused = {}; Test.addControl($('<button>Focus something</button>').click(function () { var peer = pick(); if (focused[peer.id]) { Test.incoming({ type: "form-focus", element: null, clientId: peer.id, url: peer.url }); focused[peer.id] = null; return; } var els = $("#controls textarea:visible, #controls input:visible, #controls select:visible"); var el = $(els[Math.floor(els.length * Math.random())]); focused[peer.id] = el; Test.incoming({ type: "form-focus", element: elementFinder.elementLocation(el), clientId: peer.id, url: peer.url }); })); Test.addControl($('<input placeholder="Incoming chat">').keypress(function (event) { var el = $(event.target); if (event.which == 13) { var peer = pick(); Test.incoming({ type: "chat", text: el.val(), messageId: 'message-' + Date.now(), clientId: peer.id }); el.val(""); } })); var el = $('<div><label for="idle-check">Quick idle <input type="checkbox" id="idle-check"></label>' + '<label for="expire-check">Quick expire <input type="checkbox" id="expire-check"></label>' + '<label for="include-hash">includeHashInUrl <input type="checkbox" id="include-hash"></label></div>'); el.find("#idle-check").change(function (event) { if (event.target.checked) { TogetherJSTestSpy.setIdleTime(100); } else { TogetherJSTestSpy.setIdleTime(3*60*1000); } }); el.find("#expire-check").change(function (event) { if (event.target.checked) { TogetherJSTestSpy.setByeTime(10*1000); } else { TogetherJSTestSpy.setIdleTime(10*60*1000); } }); el.find("#include-hash").change(function (event) { var config = localStorage.getItem("interactiveOverrides"); if (config) { config = JSON.parse(config); } else { config = {}; } config.includeHashInUrl = event.target.checked; localStorage.setItem("interactiveOverrides", JSON.stringify(config)); alert("Reload required"); }); if (TogetherJS.config.get("includeHashInUrl")) { el.find("#include-hash").prop("checked", true); } Test.addControl(el); Test.addControl( $('<button>Inactive</button>').click(function () { Test.incoming({ type: "idle-status", idle: "inactive", clientId: "faker" }); }), $('<button>Active</button>').click(function () { Test.incoming({ type: "idle-status", idle: "active", clientId: "faker" }); }), $('<button>Keyboard</button>').click(function () { Test.incoming({ type: "keydown", clientId: "faker" }); }) ); Test.addControl($('<input placeholder="Tool name">').keypress(function (event) { var el = $(event.target); if (event.which == 13) { TogetherJS.config("toolName", el.val() || null); el.val(""); } }));
/************************************************************* * * MathJax/jax/output/HTML-CSS/entities/n.js * * Copyright (c) 2010-2014 The MathJax Consortium * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ (function (MATHML) { MathJax.Hub.Insert(MATHML.Parse.Entity,{ 'NJcy': '\u040A', 'Nacute': '\u0143', 'Ncaron': '\u0147', 'Ncedil': '\u0145', 'Ncy': '\u041D', 'NegativeMediumSpace': '\u200B', 'NegativeThickSpace': '\u200B', 'NegativeThinSpace': '\u200B', 'NegativeVeryThinSpace': '\u200B', 'NewLine': '\u000A', 'NoBreak': '\u2060', 'NonBreakingSpace': '\u00A0', 'Not': '\u2AEC', 'NotCongruent': '\u2262', 'NotCupCap': '\u226D', 'NotEqualTilde': '\u2242\u0338', 'NotGreaterFullEqual': '\u2267\u0338', 'NotGreaterGreater': '\u226B\u0338', 'NotGreaterLess': '\u2279', 'NotGreaterSlantEqual': '\u2A7E\u0338', 'NotGreaterTilde': '\u2275', 'NotHumpDownHump': '\u224E\u0338', 'NotHumpEqual': '\u224F\u0338', 'NotLeftTriangleBar': '\u29CF\u0338', 'NotLessGreater': '\u2278', 'NotLessLess': '\u226A\u0338', 'NotLessSlantEqual': '\u2A7D\u0338', 'NotLessTilde': '\u2274', 'NotNestedGreaterGreater': '\u2AA2\u0338', 'NotNestedLessLess': '\u2AA1\u0338', 'NotPrecedesEqual': '\u2AAF\u0338', 'NotReverseElement': '\u220C', 'NotRightTriangleBar': '\u29D0\u0338', 'NotSquareSubset': '\u228F\u0338', 'NotSquareSubsetEqual': '\u22E2', 'NotSquareSuperset': '\u2290\u0338', 'NotSquareSupersetEqual': '\u22E3', 'NotSubset': '\u2282\u20D2', 'NotSucceedsEqual': '\u2AB0\u0338', 'NotSucceedsTilde': '\u227F\u0338', 'NotSuperset': '\u2283\u20D2', 'NotTildeEqual': '\u2244', 'NotTildeFullEqual': '\u2247', 'NotTildeTilde': '\u2249', 'Ntilde': '\u00D1', 'Nu': '\u039D', 'nGg': '\u22D9\u0338', 'nGt': '\u226B\u20D2', 'nGtv': '\u226B\u0338', 'nLl': '\u22D8\u0338', 'nLt': '\u226A\u20D2', 'nLtv': '\u226A\u0338', 'nabla': '\u2207', 'nacute': '\u0144', 'nang': '\u2220\u20D2', 'nap': '\u2249', 'napE': '\u2A70\u0338', 'napid': '\u224B\u0338', 'napos': '\u0149', 'napprox': '\u2249', 'natural': '\u266E', 'naturals': '\u2115', 'nbsp': '\u00A0', 'nbump': '\u224E\u0338', 'nbumpe': '\u224F\u0338', 'ncap': '\u2A43', 'ncaron': '\u0148', 'ncedil': '\u0146', 'ncong': '\u2247', 'ncongdot': '\u2A6D\u0338', 'ncup': '\u2A42', 'ncy': '\u043D', 'ndash': '\u2013', 'ne': '\u2260', 'neArr': '\u21D7', 'nearhk': '\u2924', 'nearrow': '\u2197', 'nedot': '\u2250\u0338', 'nequiv': '\u2262', 'nesear': '\u2928', 'nesim': '\u2242\u0338', 'nexist': '\u2204', 'nexists': '\u2204', 'ngE': '\u2267\u0338', 'nge': '\u2271', 'ngeq': '\u2271', 'ngeqq': '\u2267\u0338', 'ngeqslant': '\u2A7E\u0338', 'nges': '\u2A7E\u0338', 'ngsim': '\u2275', 'ngt': '\u226F', 'ngtr': '\u226F', 'nhArr': '\u21CE', 'nhpar': '\u2AF2', 'ni': '\u220B', 'nis': '\u22FC', 'nisd': '\u22FA', 'niv': '\u220B', 'njcy': '\u045A', 'nlArr': '\u21CD', 'nlE': '\u2266\u0338', 'nldr': '\u2025', 'nle': '\u2270', 'nleftarrow': '\u219A', 'nleftrightarrow': '\u21AE', 'nleq': '\u2270', 'nleqq': '\u2266\u0338', 'nleqslant': '\u2A7D\u0338', 'nles': '\u2A7D\u0338', 'nless': '\u226E', 'nlsim': '\u2274', 'nlt': '\u226E', 'nltri': '\u22EA', 'nltrie': '\u22EC', 'nmid': '\u2224', 'notin': '\u2209', 'notinE': '\u22F9\u0338', 'notindot': '\u22F5\u0338', 'notinva': '\u2209', 'notinvb': '\u22F7', 'notinvc': '\u22F6', 'notni': '\u220C', 'notniva': '\u220C', 'notnivb': '\u22FE', 'notnivc': '\u22FD', 'npar': '\u2226', 'nparallel': '\u2226', 'nparsl': '\u2AFD\u20E5', 'npart': '\u2202\u0338', 'npolint': '\u2A14', 'npr': '\u2280', 'nprcue': '\u22E0', 'npre': '\u2AAF\u0338', 'nprec': '\u2280', 'npreceq': '\u2AAF\u0338', 'nrArr': '\u21CF', 'nrarrc': '\u2933\u0338', 'nrarrw': '\u219D\u0338', 'nrightarrow': '\u219B', 'nrtri': '\u22EB', 'nrtrie': '\u22ED', 'nsc': '\u2281', 'nsccue': '\u22E1', 'nsce': '\u2AB0\u0338', 'nshortmid': '\u2224', 'nshortparallel': '\u2226', 'nsim': '\u2241', 'nsime': '\u2244', 'nsimeq': '\u2244', 'nsmid': '\u2224', 'nspar': '\u2226', 'nsqsube': '\u22E2', 'nsqsupe': '\u22E3', 'nsub': '\u2284', 'nsubE': '\u2AC5\u0338', 'nsube': '\u2288', 'nsubset': '\u2282\u20D2', 'nsubseteq': '\u2288', 'nsubseteqq': '\u2AC5\u0338', 'nsucc': '\u2281', 'nsucceq': '\u2AB0\u0338', 'nsup': '\u2285', 'nsupE': '\u2AC6\u0338', 'nsupe': '\u2289', 'nsupset': '\u2283\u20D2', 'nsupseteq': '\u2289', 'nsupseteqq': '\u2AC6\u0338', 'ntgl': '\u2279', 'ntilde': '\u00F1', 'ntlg': '\u2278', 'ntriangleleft': '\u22EA', 'ntrianglelefteq': '\u22EC', 'ntriangleright': '\u22EB', 'ntrianglerighteq': '\u22ED', 'num': '\u0023', 'numero': '\u2116', 'numsp': '\u2007', 'nvHarr': '\u2904', 'nvap': '\u224D\u20D2', 'nvge': '\u2265\u20D2', 'nvgt': '\u003E\u20D2', 'nvinfin': '\u29DE', 'nvlArr': '\u2902', 'nvle': '\u2264\u20D2', 'nvlt': '\u003C\u20D2', 'nvltrie': '\u22B4\u20D2', 'nvrArr': '\u2903', 'nvrtrie': '\u22B5\u20D2', 'nvsim': '\u223C\u20D2', 'nwArr': '\u21D6', 'nwarhk': '\u2923', 'nwarrow': '\u2196', 'nwnear': '\u2927' }); MathJax.Ajax.loadComplete(MATHML.entityDir+"/n.js"); })(MathJax.InputJax.MathML);
// For an introduction to the Page Control template, see the following documentation: // http://go.microsoft.com/fwlink/?LinkId=232511 (function () { "use strict"; var app = WinJS.Application; var nav = WinJS.Navigation; var sched = WinJS.Utilities.Scheduler; var ui = WinJS.UI; WinJS.UI.Pages.define("pages/main/main.html", { // This function is called whenever a user navigates to this page. It // populates the page elements with the app's data. ready: function (element, options) { var launchtiles = document.querySelectorAll('.launchtile'); for (var n = 0; n < launchtiles.length; n++) { var launchtile = launchtiles[n]; launchtile.addEventListener('click', this.launchtileInvoked.bind(this)); } }, toggleNavBarVisibility: function (ev) { document.getElementById('createNavBar').winControl.show(); }, launchtileInvoked: function (ev) { var tile = ev.currentTarget; var location = "pages/" + tile.dataset.page + "/" + tile.dataset.page + ".html"; nav.navigate(location); var trigger = document.querySelector(".nav-trigger"); trigger.checked = false; }, unload: function () { // TODO: Respond to navigations away from this page. }, updateLayout: function (element) { /// <param name="element" domElement="true" /> // TODO: Respond to changes in layout. } }); })();
describe("module:ng.directive:ngClick", function() { beforeEach(function() { browser.get("./examples/example-example24/index.html"); }); it('should check ng-click', function() { expect(element(by.binding('count')).getText()).toMatch('0'); element(by.css('button')).click(); expect(element(by.binding('count')).getText()).toMatch('1'); }); });
!function(e,t,n,i){"function"==typeof define&&define.amd?(n=Object.values(n),define(e,n,i)):"undefined"!=typeof module&&module.exports?(n=Object.keys(n).map(e=>require(e)),module.exports=i(...n)):(n=Object.values(n).map(e=>t[e]),t[e]=i(...n))}("Monio","undefined"!=typeof globalThis?globalThis:"undefined"!=typeof global?global:"undefined"!=typeof window?window:"undefined"!=typeof self?self:new Function("return this")(),{"./lib/util.js":"MonioUtil","./just.js":"Just","./nothing.js":"Nothing","./maybe.js":"Maybe","./either.js":"Either","./async-either.js":"AsyncEither","./io.js":"IO","./io-helpers.js":"IOHelpers","./io-event-stream.js":"IOEventStream"},function(e,t,n,i,o,s,l,r,u){"use strict";let d={};return d.MonioUtil=e,d.Just=t,d.Nothing=n,d.Maybe=i,d.Either=o,d.AsyncEither=s,d.IO=l,d.RIO=l,d.Reader=l,d.IOHelpers=r,d.IOEventStream=u,d});
/* Copyright (c) 2003-2015, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or http://ckeditor.com/license */ CKEDITOR.plugins.setLang( 'save', 'ru', { toolbar: 'Сохранить' } );