code
stringlengths 2
1.05M
|
---|
/*!
* froala_editor v3.1.1 (https://www.froala.com/wysiwyg-editor)
* License https://froala.com/wysiwyg-editor/terms/
* Copyright 2014-2020 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;
/**
* Arabic
*/
FE.LANGUAGE['ar'] = {
translation: {
// Place holder
'Type something': "\u0627\u0643\u062A\u0628 \u0634\u064A\u0626\u0627",
// Basic formatting
'Bold': "\u063A\u0627\u0645\u0642",
'Italic': "\u0645\u0627\u0626\u0644",
'Underline': "\u062A\u0633\u0637\u064A\u0631",
'Strikethrough': "\u064A\u062A\u0648\u0633\u0637 \u062E\u0637",
// Main buttons
'Insert': "\u0625\u062F\u0631\u0627\u062C",
'Delete': "\u062D\u0630\u0641",
'Cancel': "\u0625\u0644\u063A\u0627\u0621",
'OK': "\u0645\u0648\u0627\u0641\u0642",
'Back': "\u0638\u0647\u0631",
'Remove': "\u0625\u0632\u0627\u0644\u0629",
'More': "\u0623\u0643\u062B\u0631",
'Update': "\u0627\u0644\u062A\u062D\u062F\u064A\u062B",
'Style': "\u0623\u0633\u0644\u0648\u0628",
// Font
'Font Family': "\u0639\u0627\u0626\u0644\u0629 \u0627\u0644\u062E\u0637",
'Font Size': "\u062D\u062C\u0645 \u0627\u0644\u062E\u0637",
// Colors
'Colors': "\u0627\u0644\u0623\u0644\u0648\u0627\u0646",
'Background': "\u0627\u0644\u062E\u0644\u0641\u064A\u0629",
'Text': "\u0627\u0644\u0646\u0635",
'HEX Color': 'عرافة اللون',
// Paragraphs
'Paragraph Format': "\u062A\u0646\u0633\u064A\u0642 \u0627\u0644\u0641\u0642\u0631\u0629",
'Normal': "\u0637\u0628\u064A\u0639\u064A",
'Code': "\u0643\u0648\u062F",
'Heading 1': "\u0627\u0644\u0639\u0646\u0627\u0648\u064A\u0646 1",
'Heading 2': "\u0627\u0644\u0639\u0646\u0627\u0648\u064A\u0646 2",
'Heading 3': "\u0627\u0644\u0639\u0646\u0627\u0648\u064A\u0646 3",
'Heading 4': "\u0627\u0644\u0639\u0646\u0627\u0648\u064A\u0646 4",
// Style
'Paragraph Style': "\u0646\u0645\u0637 \u0627\u0644\u0641\u0642\u0631\u0629",
'Inline Style': "\u0627\u0644\u0646\u0645\u0637 \u0627\u0644\u0645\u0636\u0645\u0646",
// Alignment
'Align': "\u0645\u062D\u0627\u0630\u0627\u0629",
'Align Left': "\u0645\u062D\u0627\u0630\u0627\u0629 \u0627\u0644\u0646\u0635 \u0644\u0644\u064A\u0633\u0627\u0631",
'Align Center': "\u062A\u0648\u0633\u064A\u0637",
'Align Right': "\u0645\u062D\u0627\u0630\u0627\u0629 \u0627\u0644\u0646\u0635 \u0644\u0644\u064A\u0645\u064A\u0646",
'Align Justify': "\u0636\u0628\u0637",
'None': "\u0644\u0627 \u0634\u064A\u0621",
// Lists
'Ordered List': "\u0642\u0627\u0626\u0645\u0629 \u0645\u0631\u062A\u0628\u0629",
'Default': 'الافتراضي',
'Lower Alpha': 'أقل ألفا',
'Lower Greek': 'أقل اليونانية',
'Lower Roman': 'انخفاض الروماني',
'Upper Alpha': 'العلوي ألفا',
'Upper Roman': 'الروماني العلوي',
'Unordered List': "\u0642\u0627\u0626\u0645\u0629 \u063A\u064A\u0631 \u0645\u0631\u062A\u0628\u0629",
'Circle': 'دائرة',
'Disc': 'القرص',
'Square': 'ميدان',
// Line height
'Line Height': 'ارتفاع خط',
'Single': 'غير مرتبطة',
'Double': 'مزدوج',
// Indent
'Decrease Indent': "\u0627\u0646\u062E\u0641\u0627\u0636 \u0627\u0644\u0645\u0633\u0627\u0641\u0629 \u0627\u0644\u0628\u0627\u062F\u0626\u0629",
'Increase Indent': "\u0632\u064A\u0627\u062F\u0629 \u0627\u0644\u0645\u0633\u0627\u0641\u0629 \u0627\u0644\u0628\u0627\u062F\u0626\u0629",
// Links
'Insert Link': "\u0625\u062F\u0631\u0627\u062C \u0631\u0627\u0628\u0637",
'Open in new tab': "\u0641\u062A\u062D \u0641\u064A \u0639\u0644\u0627\u0645\u0629 \u062A\u0628\u0648\u064A\u0628 \u062C\u062F\u064A\u062F\u0629",
'Open Link': "\u0627\u0641\u062A\u062D \u0627\u0644\u0631\u0627\u0628\u0637",
'Edit Link': "\u0627\u0631\u062A\u0628\u0627\u0637 \u062A\u062D\u0631\u064A\u0631",
'Unlink': "\u062D\u0630\u0641 \u0627\u0644\u0631\u0627\u0628\u0637",
'Choose Link': "\u0627\u062E\u062A\u064A\u0627\u0631 \u0635\u0644\u0629",
// Images
'Insert Image': "\u0625\u062F\u0631\u0627\u062C \u0635\u0648\u0631\u0629",
'Upload Image': "\u062A\u062D\u0645\u064A\u0644 \u0635\u0648\u0631\u0629",
'By URL': "\u0628\u0648\u0627\u0633\u0637\u0629 URL",
'Browse': "\u062A\u0635\u0641\u062D",
'Drop image': "\u0625\u0633\u0642\u0627\u0637 \u0635\u0648\u0631\u0629",
'or click': "\u0623\u0648 \u0627\u0646\u0642\u0631 \u0641\u0648\u0642",
'Manage Images': "\u0625\u062F\u0627\u0631\u0629 \u0627\u0644\u0635\u0648\u0631",
'Loading': "\u062A\u062D\u0645\u064A\u0644",
'Deleting': "\u062D\u0630\u0641",
'Tags': "\u0627\u0644\u0643\u0644\u0645\u0627\u062A",
'Are you sure? Image will be deleted.': "\u0647\u0644 \u0623\u0646\u062A \u0645\u062A\u0623\u0643\u062F\u061F \u0633\u064A\u062A\u0645 \u062D\u0630\u0641 \u0627\u0644\u0635\u0648\u0631\u0629.",
'Replace': "\u0627\u0633\u062A\u0628\u062F\u0627\u0644",
'Uploading': "\u062A\u062D\u0645\u064A\u0644",
'Loading image': "\u0635\u0648\u0631\u0629 \u062A\u062D\u0645\u064A\u0644",
'Display': "\u0639\u0631\u0636",
'Inline': "\u0641\u064A \u062E\u0637",
'Break Text': "\u0646\u0635 \u0627\u0633\u062A\u0631\u0627\u062D\u0629",
'Alternative Text': "\u0646\u0635 \u0628\u062F\u064A\u0644",
'Change Size': "\u062A\u063A\u064A\u064A\u0631 \u062D\u062C\u0645",
'Width': "\u0639\u0631\u0636",
'Height': "\u0627\u0631\u062A\u0641\u0627\u0639",
'Something went wrong. Please try again.': ".\u062D\u062F\u062B \u062E\u0637\u0623 \u0645\u0627. \u062D\u0627\u0648\u0644 \u0645\u0631\u0629 \u0627\u062E\u0631\u0649",
'Image Caption': 'تعليق على الصورة',
'Advanced Edit': 'تعديل متقدم',
// Video
'Insert Video': "\u0625\u062F\u0631\u0627\u062C \u0641\u064A\u062F\u064A\u0648",
'Embedded Code': "\u0627\u0644\u062A\u0639\u0644\u064A\u0645\u0627\u062A \u0627\u0644\u0628\u0631\u0645\u062C\u064A\u0629 \u0627\u0644\u0645\u0636\u0645\u0646\u0629",
'Paste in a video URL': 'لصق في عنوان ورل للفيديو',
'Drop video': 'انخفاض الفيديو',
'Your browser does not support HTML5 video.': 'متصفحك لا يدعم فيديو HTML5.',
'Upload Video': 'رفع فيديو',
// Tables
'Insert Table': "\u0625\u062F\u0631\u0627\u062C \u062C\u062F\u0648\u0644",
'Table Header': "\u0631\u0623\u0633 \u0627\u0644\u062C\u062F\u0648\u0644",
'Remove Table': "\u0625\u0632\u0627\u0644\u0629 \u0627\u0644\u062C\u062F\u0648\u0644",
'Table Style': "\u0646\u0645\u0637 \u0627\u0644\u062C\u062F\u0648\u0644",
'Horizontal Align': "\u0645\u062D\u0627\u0630\u0627\u0629 \u0623\u0641\u0642\u064A\u0629",
'Row': "\u0635\u0641",
'Insert row above': "\u0625\u062F\u0631\u0627\u062C \u0635\u0641 \u0644\u0644\u0623\u0639\u0644\u0649",
'Insert row below': "\u0625\u062F\u0631\u0627\u062C \u0635\u0641 \u0644\u0644\u0623\u0633\u0641\u0644",
'Delete row': "\u062D\u0630\u0641 \u0635\u0641",
'Column': "\u0639\u0645\u0648\u062F",
'Insert column before': "\u0625\u062F\u0631\u0627\u062C \u0639\u0645\u0648\u062F \u0644\u0644\u064A\u0633\u0627\u0631",
'Insert column after': "\u0625\u062F\u0631\u0627\u062C \u0639\u0645\u0648\u062F \u0644\u0644\u064A\u0645\u064A\u0646",
'Delete column': "\u062D\u0630\u0641 \u0639\u0645\u0648\u062F",
'Cell': "\u062E\u0644\u064A\u0629",
'Merge cells': "\u062F\u0645\u062C \u062E\u0644\u0627\u064A\u0627",
'Horizontal split': "\u0627\u0646\u0642\u0633\u0627\u0645 \u0623\u0641\u0642\u064A",
'Vertical split': "\u0627\u0644\u0627\u0646\u0642\u0633\u0627\u0645 \u0627\u0644\u0639\u0645\u0648\u062F\u064A",
'Cell Background': "\u062E\u0644\u0641\u064A\u0629 \u0627\u0644\u062E\u0644\u064A\u0629",
'Vertical Align': "\u0645\u062D\u0627\u0630\u0627\u0629 \u0639\u0645\u0648\u062F\u064A\u0629",
'Top': "\u0623\u0639\u0644\u0649",
'Middle': "\u0648\u0633\u0637",
'Bottom': "\u0623\u0633\u0641\u0644",
'Align Top': "\u0645\u062D\u0627\u0630\u0627\u0629 \u0623\u0639\u0644\u0649",
'Align Middle': "\u0645\u062D\u0627\u0630\u0627\u0629 \u0648\u0633\u0637",
'Align Bottom': "\u0645\u062D\u0627\u0630\u0627\u0629 \u0627\u0644\u0623\u0633\u0641\u0644",
'Cell Style': "\u0646\u0645\u0637 \u0627\u0644\u062E\u0644\u064A\u0629",
// Files
'Upload File': "\u062A\u062D\u0645\u064A\u0644 \u0627\u0644\u0645\u0644\u0641",
'Drop file': "\u0627\u0646\u062E\u0641\u0627\u0636 \u0627\u0644\u0645\u0644\u0641",
// Emoticons
'Emoticons': "\u0627\u0644\u0645\u0634\u0627\u0639\u0631",
'Grinning face': "\u064A\u0643\u0634\u0631 \u0648\u062C\u0647\u0647",
'Grinning face with smiling eyes': "\u0645\u0628\u062A\u0633\u0645\u0627 \u0648\u062C\u0647 \u0645\u0639 \u064A\u0628\u062A\u0633\u0645 \u0627\u0644\u0639\u064A\u0646",
'Face with tears of joy': "\u0648\u062C\u0647 \u0645\u0639 \u062F\u0645\u0648\u0639 \u0627\u0644\u0641\u0631\u062D",
'Smiling face with open mouth': "\u0627\u0644\u0648\u062C\u0647 \u0627\u0644\u0645\u0628\u062A\u0633\u0645 \u0645\u0639 \u0641\u062A\u062D \u0627\u0644\u0641\u0645",
'Smiling face with open mouth and smiling eyes': "\u0627\u0644\u0648\u062C\u0647 \u0627\u0644\u0645\u0628\u062A\u0633\u0645 \u0645\u0639 \u0641\u062A\u062D \u0627\u0644\u0641\u0645 \u0648\u0627\u0644\u0639\u064A\u0646\u064A\u0646 \u064A\u0628\u062A\u0633\u0645",
'Smiling face with open mouth and cold sweat': "\u0627\u0644\u0648\u062C\u0647 \u0627\u0644\u0645\u0628\u062A\u0633\u0645 \u0645\u0639 \u0641\u062A\u062D \u0627\u0644\u0641\u0645 \u0648\u0627\u0644\u0639\u0631\u0642 \u0627\u0644\u0628\u0627\u0631\u062F",
'Smiling face with open mouth and tightly-closed eyes': "\u0627\u0644\u0648\u062C\u0647 \u0627\u0644\u0645\u0628\u062A\u0633\u0645 \u0645\u0639 \u0641\u062A\u062D \u0627\u0644\u0641\u0645 \u0648\u0627\u0644\u0639\u064A\u0646\u064A\u0646 \u0645\u063A\u0644\u0642\u0629 \u0628\u0625\u062D\u0643\u0627\u0645",
'Smiling face with halo': "\u0627\u0644\u0648\u062C\u0647 \u0627\u0644\u0645\u0628\u062A\u0633\u0645 \u0645\u0639 \u0647\u0627\u0644\u0629",
'Smiling face with horns': "\u0627\u0644\u0648\u062C\u0647 \u0627\u0644\u0645\u0628\u062A\u0633\u0645 \u0628\u0642\u0631\u0648\u0646",
'Winking face': "\u0627\u0644\u063A\u0645\u0632 \u0648\u062C\u0647",
'Smiling face with smiling eyes': "\u064A\u0628\u062A\u0633\u0645 \u0648\u062C\u0647 \u0645\u0639 \u0639\u064A\u0648\u0646 \u062A\u0628\u062A\u0633\u0645",
'Face savoring delicious food': "\u064A\u0648\u0627\u062C\u0647 \u0644\u0630\u064A\u0630 \u0627\u0644\u0645\u0630\u0627\u0642 \u0644\u0630\u064A\u0630 \u0627\u0644\u0637\u0639\u0627\u0645",
'Relieved face': "\u0648\u062C\u0647 \u0628\u0627\u0644\u0627\u0631\u062A\u064A\u0627\u062D",
'Smiling face with heart-shaped eyes': "\u0627\u0644\u0648\u062C\u0647 \u0627\u0644\u0645\u0628\u062A\u0633\u0645 \u0628\u0639\u064A\u0646\u064A\u0646 \u0639\u0644\u0649 \u0634\u0643\u0644 \u0642\u0644\u0628",
'Smiling face with sunglasses': "\u0627\u0644\u0648\u062C\u0647 \u0627\u0644\u0645\u0628\u062A\u0633\u0645 \u0645\u0639 \u0627\u0644\u0646\u0638\u0627\u0631\u0627\u062A \u0627\u0644\u0634\u0645\u0633\u064A\u0629",
'Smirking face': "\u0633\u0645\u064A\u0631\u0643\u064A\u0646\u062C \u0627\u0644\u0648\u062C\u0647",
'Neutral face': "\u0645\u062D\u0627\u064A\u062F \u0627\u0644\u0648\u062C\u0647",
'Expressionless face': "\u0648\u062C\u0647 \u0627\u0644\u062A\u0639\u0627\u0628\u064A\u0631",
'Unamused face': "\u0644\u0627 \u0645\u0633\u0644\u064A\u0627 \u0627\u0644\u0648\u062C\u0647",
'Face with cold sweat': "\u0648\u062C\u0647 \u0645\u0639 \u0639\u0631\u0642 \u0628\u0627\u0631\u062F",
'Pensive face': "\u0648\u062C\u0647 \u0645\u062A\u0623\u0645\u0644",
'Confused face': "\u0648\u062C\u0647 \u0627\u0644\u062E\u0644\u0637",
'Confounded face': "\u0648\u062C\u0647 \u0645\u0631\u062A\u0628\u0643",
'Kissing face': "\u062A\u0642\u0628\u064A\u0644 \u0627\u0644\u0648\u062C\u0647",
'Face throwing a kiss': "\u0645\u0648\u0627\u062C\u0647\u0629 \u0631\u0645\u064A \u0642\u0628\u0644\u0629",
'Kissing face with smiling eyes': "\u062A\u0642\u0628\u064A\u0644 \u0648\u062C\u0647 \u0645\u0639 \u0639\u064A\u0648\u0646 \u062A\u0628\u062A\u0633\u0645",
'Kissing face with closed eyes': "\u062A\u0642\u0628\u064A\u0644 \u0648\u062C\u0647 \u0645\u0639 \u0639\u064A\u0648\u0646 \u0645\u063A\u0644\u0642\u0629",
'Face with stuck out tongue': "\u0627\u0644\u0648\u062C\u0647 \u0645\u0639 \u062A\u0645\u0633\u0643 \u0628\u0647\u0627 \u0627\u0644\u0644\u0633\u0627\u0646",
'Face with stuck out tongue and winking eye': "\u0627\u0644\u0648\u062C\u0647 \u0645\u0639 \u062A\u0645\u0633\u0643 \u0628\u0647\u0627 \u0627\u0644\u0644\u0633\u0627\u0646 \u0648\u0627\u0644\u0639\u064A\u0646 \u0627\u0644\u062A\u063A\u0627\u0636\u064A",
'Face with stuck out tongue and tightly-closed eyes': "\u0627\u0644\u0648\u062C\u0647 \u0645\u0639 \u062A\u0645\u0633\u0643 \u0628\u0647\u0627 \u0627\u0644\u0644\u0633\u0627\u0646 \u0648\u0627\u0644\u0639\u064A\u0648\u0646 \u0645\u063A\u0644\u0642\u0629 \u0628\u0623\u062D\u0643\u0627\u0645-",
'Disappointed face': "\u0648\u062C\u0647\u0627 \u062E\u064A\u0628\u0629 \u0623\u0645\u0644",
'Worried face': "\u0648\u062C\u0647\u0627 \u0627\u0644\u0642\u0644\u0642\u0648\u0646",
'Angry face': "\u0648\u062C\u0647 \u063A\u0627\u0636\u0628",
'Pouting face': "\u0627\u0644\u0639\u0628\u0648\u0633 \u0648\u062C\u0647",
'Crying face': "\u0627\u0644\u0628\u0643\u0627\u0621 \u0627\u0644\u0648\u062C\u0647",
'Persevering face': "\u0627\u0644\u0645\u062B\u0627\u0628\u0631\u0629 \u0648\u062C\u0647\u0647",
'Face with look of triumph': "\u0648\u0627\u062C\u0647 \u0645\u0639 \u0646\u0638\u0631\u0629 \u0627\u0646\u062A\u0635\u0627\u0631",
'Disappointed but relieved face': "\u0628\u062E\u064A\u0628\u0629 \u0623\u0645\u0644 \u0648\u0644\u0643\u0646 \u064A\u0639\u0641\u0649 \u0648\u062C\u0647",
'Frowning face with open mouth': "\u0645\u0642\u0637\u0628 \u0627\u0644\u0648\u062C\u0647 \u0645\u0639 \u0641\u062A\u062D \u0627\u0644\u0641\u0645",
'Anguished face': "\u0627\u0644\u0648\u062C\u0647 \u0627\u0644\u0645\u0624\u0644\u0645",
'Fearful face': "\u0627\u0644\u0648\u062C\u0647 \u0627\u0644\u0645\u062E\u064A\u0641",
'Weary face': "\u0648\u062C\u0647\u0627 \u0628\u0627\u0644\u0636\u062C\u0631",
'Sleepy face': "\u0648\u062C\u0647 \u0646\u0639\u0633\u0627\u0646",
'Tired face': "\u0648\u062C\u0647 \u0645\u062A\u0639\u0628",
'Grimacing face': "\u0648\u062E\u0631\u062C \u0633\u064A\u0633 \u0627\u0644\u0648\u062C\u0647",
'Loudly crying face': "\u0627\u0644\u0628\u0643\u0627\u0621 \u0628\u0635\u0648\u062A \u0639\u0627\u0644 \u0648\u062C\u0647\u0647",
'Face with open mouth': "\u0648\u0627\u062C\u0647 \u0645\u0639 \u0641\u062A\u062D \u0627\u0644\u0641\u0645",
'Hushed face': "\u0648\u062C\u0647\u0627 \u0627\u0644\u062A\u0643\u062A\u0645",
'Face with open mouth and cold sweat': "\u0648\u0627\u062C\u0647 \u0645\u0639 \u0641\u062A\u062D \u0627\u0644\u0641\u0645 \u0648\u0627\u0644\u0639\u0631\u0642 \u0627\u0644\u0628\u0627\u0631\u062F",
'Face screaming in fear': "\u0648\u0627\u062C\u0647 \u064A\u0635\u0631\u062E \u0641\u064A \u062E\u0648\u0641",
'Astonished face': "\u0648\u062C\u0647\u0627 \u062F\u0647\u0634",
'Flushed face': "\u0627\u062D\u0645\u0631\u0627\u0631 \u0627\u0644\u0648\u062C\u0647",
'Sleeping face': "\u0627\u0644\u0646\u0648\u0645 \u0627\u0644\u0648\u062C\u0647",
'Dizzy face': "\u0648\u062C\u0647\u0627 \u0628\u0627\u0644\u062F\u0648\u0627\u0631",
'Face without mouth': "\u0648\u0627\u062C\u0647 \u062F\u0648\u0646 \u0627\u0644\u0641\u0645",
'Face with medical mask': "\u0648\u0627\u062C\u0647 \u0645\u0639 \u0642\u0646\u0627\u0639 \u0627\u0644\u0637\u0628\u064A\u0629",
// Line breaker
'Break': "\u0627\u0644\u0627\u0646\u0642\u0633\u0627\u0645",
// Math
'Subscript': "\u0645\u0646\u062E\u0641\u0636",
'Superscript': "\u062D\u0631\u0641 \u0641\u0648\u0642\u064A",
// Full screen
'Fullscreen': "\u0643\u0627\u0645\u0644 \u0627\u0644\u0634\u0627\u0634\u0629",
// Horizontal line
'Insert Horizontal Line': "\u0625\u062F\u0631\u0627\u062C \u062E\u0637 \u0623\u0641\u0642\u064A",
// Clear formatting
'Clear Formatting': "\u0625\u0632\u0627\u0644\u0629 \u0627\u0644\u062A\u0646\u0633\u064A\u0642",
// Save
'Save': "\u062D\u0641\u0638",
// Undo, redo
'Undo': "\u062A\u0631\u0627\u062C\u0639",
'Redo': "\u0625\u0639\u0627\u062F\u0629",
// Select all
'Select All': "\u062A\u062D\u062F\u064A\u062F \u0627\u0644\u0643\u0644",
// Code view
'Code View': "\u0639\u0631\u0636 \u0627\u0644\u062A\u0639\u0644\u064A\u0645\u0627\u062A \u0627\u0644\u0628\u0631\u0645\u062C\u064A\u0629",
// Quote
'Quote': "\u0627\u0642\u062A\u0628\u0633",
'Increase': "\u0632\u064A\u0627\u062F\u0629",
'Decrease': "\u0627\u0646\u062E\u0641\u0627\u0636",
// Quick Insert
'Quick Insert': "\u0625\u062F\u0631\u0627\u062C \u0633\u0631\u064A\u0639",
// Spcial Characters
'Special Characters': 'أحرف خاصة',
'Latin': 'لاتينية',
'Greek': 'الإغريقي',
'Cyrillic': 'السيريلية',
'Punctuation': 'علامات ترقيم',
'Currency': 'دقة',
'Arrows': 'السهام',
'Math': 'الرياضيات',
'Misc': 'متفرقات',
// Print.
'Print': 'طباعة',
// Spell Checker.
'Spell Checker': 'مدقق املائي',
// Help
'Help': 'مساعدة',
'Shortcuts': 'اختصارات',
'Inline Editor': 'محرر مضمنة',
'Show the editor': 'عرض المحرر',
'Common actions': 'الإجراءات المشتركة',
'Copy': 'نسخ',
'Cut': 'يقطع',
'Paste': 'معجون',
'Basic Formatting': 'التنسيق الأساسي',
'Increase quote level': 'زيادة مستوى الاقتباس',
'Decrease quote level': 'انخفاض مستوى الاقتباس',
'Image / Video': 'صورة / فيديو',
'Resize larger': 'تغيير حجم أكبر',
'Resize smaller': 'تغيير حجم أصغر',
'Table': 'الطاولة',
'Select table cell': 'حدد خلية الجدول',
'Extend selection one cell': 'توسيع اختيار خلية واحدة',
'Extend selection one row': 'تمديد اختيار صف واحد',
'Navigation': 'التنقل',
'Focus popup / toolbar': 'التركيز المنبثقة / شريط الأدوات',
'Return focus to previous position': 'عودة التركيز إلى الموقف السابق',
// Embed.ly
'Embed URL': 'تضمين عنوان ورل',
'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?': 'المحتوى الذي تم لصقه قادم من وثيقة كلمة ميكروسوفت. هل تريد الاحتفاظ بالتنسيق أو تنظيفه؟',
'Keep': 'احتفظ',
'Clean': 'نظيف',
'Word Paste Detected': 'تم اكتشاف معجون الكلمات',
// Character Counter
'Characters': 'الشخصيات',
// More Buttons
'More Text': 'المزيد من النص',
'More Paragraph': ' المزيد من الفقرة',
'More Rich': ' أكثر ثراء',
'More Misc': ' أكثر متفرقات'
},
direction: 'rtl'
};
})));
//# sourceMappingURL=ar.js.map
|
var request = require('request'),
log = require('bole')('npme-send-data'),
config = require('../../../config')
module.exports = function (formGuid, data, callback) {
var hubspot = config.license.hubspot.forms
.replace(":portal_id", config.license.hubspot.portal_id)
.replace(":form_guid", formGuid);
request.post(hubspot, function (er, resp) {
// we can ignore 302 responses
if (resp.statusCode === 204 || resp.statusCode === 302) {
return callback(null);
}
log.error('unexpected status code from hubspot; status=' + resp.statusCode + '; data=', data);
callback(new Error('unexpected status code: ' + resp.statusCode));
}).form(data);
} |
module.exports = {
env: {
mocha: true
},
plugins: [
'mocha'
]
};
|
/* eslint-disable flowtype/require-parameter-type, flowtype/require-return-type, no-magic-numbers */
import {test} from "tap"
import {spy} from "sinon"
import aside from "./"
test(({equal, end}) => {
const unction = spy(() => "b")
equal(aside([unction])("a"), "a")
end()
})
test(({ok, end}) => {
const unction = spy(() => "b")
aside([unction])("a")
ok(unction.calledWith("a"))
end()
})
test(({equal, end}) => {
const unction = spy(() => "b")
equal(aside([unction])("a"), "a")
end()
})
test(({ok, equal, end}) => {
const unctionA = spy(() => "b")
const unctionB = spy(() => "c")
equal(aside([unctionA, unctionB])("a"), "a")
ok(unctionA.calledWith("a"))
ok(unctionB.calledWith("b"))
end()
})
|
var doNothing = function () {}
/**
* The `Base` log defines methods that transports will share.
*/
var Base = module.exports = function (config, defaults) {
var cedar = require('../../cedar')
// A log is a shorthand for `log.log`, among other things.
var log = function () {
log.log.apply(log, arguments)
}
// Don't run `setMethods` until all config properties are set.
var setMethods = doNothing
// Define properties that trigger `setMethods`.
Base.resetters.forEach(function (property) {
var value
Object.defineProperty(log, property, {
get: function () {
return value
},
set: function (newValue) {
value = newValue
setMethods.apply(log)
}
})
})
// Copy `config` properties to the `log`.
Base.decorate(log, config, true)
// Apply default properties.
Base.decorate(log, defaults || Base.defaults)
// Set up logging methods.
Base.setMethods.apply(log)
// Re-run `setMethods` if `resetters` change.
setMethods = Base.setMethods
// Return the fully-decorated log function.
return log
}
/**
* Some properties will reset methods if changed.
*/
Base.resetters = ['level', 'prefixes', 'format', 'showTrace']
/**
* Cedar supports 7 levels of logging.
*/
Base.levels = ['trace', 'debug', 'log', 'info', 'warn', 'error', 'fatal']
/**
* Share defaults between log objects.
*/
Base.defaults = {
// Show all log messages by default.
level: 'trace',
// Stream to `stdout` (using `write`).
stream: process.stdout,
// Don't add any space to JSON.
space: '',
// Stringify with `JSON.stringify`.
stringify: JSON.stringify,
// Join arguments together as an array.
join: function (args) {
var list = []
for (var index = 0, length = args.length; index < length; index++) {
var arg = args[index]
if (arg instanceof Error) {
arg = '"' + (arg.stack || arg.toString()).replace(/\n/, '\\n') + '"'
} else {
arg = JSON.stringify(arg, null, this.space)
}
list.push(arg)
}
return '[' + list.join(',') + ']'
},
// Start messages with a prefix for each log method.
prefixes: {
trace: 'TRACE ',
debug: 'DEBUG ',
log: 'LOG ',
info: 'INFO ',
warn: 'WARN ',
error: 'ERROR ',
fatal: 'FATAL '
},
// Format a log message.
format: function (message, type, prefix) {
return prefix + message + '\n'
}
}
/**
* Decorate an object with the properties of another.
*/
Base.decorate = function (object, defaults, shouldOverwrite) {
object = object || {}
for (var key in defaults) {
if (shouldOverwrite || (typeof object[key] === 'undefined')) {
object[key] = defaults[key]
}
}
return object
}
/**
* Create logging methods based on the configured `level`.
*/
Base.setMethods = function () {
var self = this
var found = false
if ((Base.levels.indexOf(self.level) < 0) && self.level !== 'nothing') {
self.error('Unknown log level: "' + self.level + '".')
} else {
Base.levels.forEach(function (methodName, index) {
if (methodName === self.level) {
found = true
}
var prefix = self.prefixes[methodName] || ''
var format = self.format
// If this log is an Emitter, we can catch and emit errors.
if (self.emit) {
self[methodName] = found ? function () {
var message = self.join(arguments)
message = format.call(self, message, methodName, prefix)
try {
self.stream.write(message)
} catch (e) {
self.emit('error', e)
}
} : doNothing
// Otherwise, they'll just throw.
} else {
self[methodName] = found ? function () {
var message = self.join(arguments)
message = format.call(self, message, methodName, prefix)
self.stream.write(message)
} : doNothing
}
})
// Wrap the trace method with a stack tracer.
if (self.trace !== doNothing) {
var traceMethod = self.trace
self.trace = function () {
var e = new Error('')
Error.captureStackTrace(e, self.trace)
var l = arguments.length
arguments[l] = e.stack.split('\n').splice(2).join('\n')
arguments.length = ++l
traceMethod.apply(self, arguments)
}
}
}
}
|
import type {ResponseType} from "./base.type";
function parseJSON(response: ResponseType): Object {
return response.json();
}
export {parseJSON};
|
var request = require('request'),
mongoose = require('mongoose'),
util = require('util'),
url = require('url'),
helpers = require('./helpers'),
sync = require('./sync')
// turn off request pooling
request.defaults({ agent:false })
// cache elasticsearch url options for elmongo.search() to use
var elasticUrlOptions = null
/**
* Attach mongoose plugin for elasticsearch indexing
*
* @param {Object} schema mongoose schema
* @param {Object} options elasticsearch options object. Keys: host, port, index, type
*/
module.exports = elmongo = function (schema, options) {
// attach methods to schema
schema.methods.index = index
schema.methods.unindex = unindex
schema.statics.sync = function (cb) {
options = helpers.mergeModelOptions(options, this)
return sync.call(this, schema, options, cb)
}
schema.statics.search = function (searchOpts, cb) {
options = helpers.mergeModelOptions(options, this)
var searchUri = helpers.makeTypeUri(options) + '/_search?search_type=dfs_query_then_fetch&preference=_primary_first'
return helpers.doSearchAndNormalizeResults(searchUri, searchOpts, cb)
}
// attach mongoose middleware hooks
schema.post('save', function () {
options = helpers.mergeModelOptions(options, this)
this.index(options)
})
schema.post('remove', function () {
options = helpers.mergeModelOptions(options, this)
this.unindex(options)
})
}
/**
* Search across multiple collections. Same usage as model search, but with an extra key on `searchOpts` - `collections`
* @param {Object} searchOpts
* @param {Function} cb
*/
elmongo.search = function (searchOpts, cb) {
// merge elasticsearch url config options
elasticUrlOptions = helpers.mergeOptions(elasticUrlOptions)
// determine collections to search on
var collections = searchOpts.collections;
if (elasticUrlOptions.prefix) {
// prefix was specified - namespace the index names to use the prefix for each collection's index
if (searchOpts.collections && searchOpts.collections.length) {
// collections were specified - prepend the prefix on each collection name
collections = collections.map(function (collection) {
return elasticUrlOptions.prefix + '-' + collection
})
} else {
// no collections specified, but prefix specified - use wildcard index with prefix
collections = [ elasticUrlOptions.prefix + '*' ]
}
} else {
// no prefix used
// if collections specified, just use their names without the prefix
if (!collections) {
// no collections were specified so use _all (searches all collections), without prefix
searchOpts.collections = [ '_all' ]
}
}
var searchUri = helpers.makeDomainUri(elasticUrlOptions) + '/' + collections.join(',') + '/_search?search_type=dfs_query_then_fetch&preference=_primary_first'
return helpers.doSearchAndNormalizeResults(searchUri, searchOpts, cb)
}
/**
* Configure the Elasticsearch url options for `elmongo.search()`.
*
* @param {Object} options - keys: host, port, prefix (optional)
*/
elmongo.search.config = function (options) {
// only overwrite `options` values that are being specified in this call to `config`
if (elasticUrlOptions) {
Object
.keys(elasticUrlOptions)
.forEach(function (key) {
elasticUrlOptions[key] = options[key] || elasticUrlOptions[key]
})
}
// normalize the `options` object
elasticUrlOptions = helpers.mergeOptions(options)
}
/**
* Index a document in elasticsearch (create if not existing)
*
* @param {Object} options elasticsearch options object. Keys: host, port, index, type
*/
function index (options) {
var self = this
// strip mongoose-added functions, depopulate any populated fields, and serialize the doc
var esearchDoc = helpers.serializeModel(this)
var indexUri = helpers.makeDocumentUri(options, self)
var reqOpts = {
method: 'PUT',
url: indexUri,
body: JSON.stringify(esearchDoc)
}
// console.log('index:', indexUri)
helpers.backOffRequest(reqOpts, function (err, res, body) {
if (err) {
var error = new Error('Elasticsearch document indexing error: '+util.inspect(err, true, 10, true))
error.details = err
self.emit('error', error)
return
}
self.emit('elmongo-indexed', body)
})
}
/**
* Remove a document from elasticsearch
*
* @param {Object} options elasticsearch options object. Keys: host, port, index, type
*/
function unindex (options) {
var self = this
var unindexUri = helpers.makeDocumentUri(options, self)
// console.log('unindex:', unindexUri)
var reqOpts = {
method: 'DELETE',
url: unindexUri
}
helpers.backOffRequest(reqOpts, function (err, res, body) {
if (err) {
var error = new Error('Elasticsearch document index deletion error: '+util.inspect(err, true, 10, true))
error.details = err
self.emit('error', error)
return
}
self.emit('elmongo-unindexed', body)
})
}
|
/**
* Copyright 2015 Telerik AD
*
* 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(f, define){
define([], f);
})(function(){
(function( window, undefined ) {
var kendo = window.kendo || (window.kendo = { cultures: {} });
kendo.cultures["qut"] = {
name: "qut",
numberFormat: {
pattern: ["-n"],
decimals: 2,
",": ",",
".": ".",
groupSize: [3],
percent: {
pattern: ["-n %","n %"],
decimals: 2,
",": ",",
".": ".",
groupSize: [3],
symbol: "%"
},
currency: {
name: "",
abbr: "",
pattern: ["($n)","$n"],
decimals: 2,
",": ",",
".": ".",
groupSize: [3],
symbol: "Q"
}
},
calendars: {
standard: {
days: {
names: ["juq\u0027ij","kaq\u0027ij","oxq\u0027ij","kajq\u0027ij","joq\u0027ij","waqq\u0027ij","wuqq\u0027ij"],
namesAbbr: ["juq\u0027","kaq\u0027","oxq\u0027","kajq\u0027","joq\u0027","waqq\u0027","wuqq\u0027"],
namesShort: ["ju","ka","ox","kj","jo","wa","wu"]
},
months: {
names: ["nab\u0027e ik\u0027","ukab\u0027 ik\u0027","urox ik\u0027","ukaj ik\u0027","uro ik\u0027","uwaq ik\u0027","uwuq ik\u0027","uwajxaq ik\u0027","ub\u0027elej ik\u0027","ulaj ik\u0027","ujulaj ik\u0027","ukab\u0027laj ik\u0027"],
namesAbbr: ["nab\u0027e","ukab\u0027","urox","ukaj","uro","uwaq","uwuq","uwajxaq","ub\u0027elej","ulaj","ujulaj","ukab\u0027laj"]
},
AM: ["a.m.","a.m.","A.M."],
PM: ["p.m.","p.m.","P.M."],
patterns: {
d: "dd/MM/yyyy",
D: "dddd, dd' rech 'MMMM' rech 'yyyy",
F: "dddd, dd' rech 'MMMM' rech 'yyyy h:mm:ss tt",
g: "dd/MM/yyyy h:mm tt",
G: "dd/MM/yyyy h:mm:ss tt",
m: "d' rech 'MMMM",
M: "d' rech 'MMMM",
s: "yyyy'-'MM'-'dd'T'HH':'mm':'ss",
t: "h:mm tt",
T: "h:mm:ss tt",
u: "yyyy'-'MM'-'dd HH':'mm':'ss'Z'",
y: "MMMM' rech 'yyyy",
Y: "MMMM' rech 'yyyy"
},
"/": "/",
":": ":",
firstDay: 1
}
}
}
})(this);
return window.kendo;
}, typeof define == 'function' && define.amd ? define : function(_, f){ f(); }); |
// flow-typed signature: 573c576fe34eb3c3c65dd7a9c90a46d2
// flow-typed version: b43dff3e0e/http-errors_v1.x.x/flow_>=v0.25.x
declare module 'http-errors' {
declare class SpecialHttpError extends HttpError {
constructor(): SpecialHttpError;
}
declare class HttpError extends Error {
expose: bool;
message: string;
status: number;
statusCode: number;
}
declare module.exports: {
(status?: number, message?: string, props?: Object): HttpError;
HttpError: typeof HttpError;
BadRequest: typeof SpecialHttpError;
Unauthorized: typeof SpecialHttpError;
PaymentRequired: typeof SpecialHttpError;
Forbidden: typeof SpecialHttpError;
NotFound: typeof SpecialHttpError;
MethodNotAllowed: typeof SpecialHttpError;
NotAcceptable: typeof SpecialHttpError;
ProxyAuthenticationRequired: typeof SpecialHttpError;
RequestTimeout: typeof SpecialHttpError;
Conflict: typeof SpecialHttpError;
Gone: typeof SpecialHttpError;
LengthRequired: typeof SpecialHttpError;
PreconditionFailed: typeof SpecialHttpError;
PayloadTooLarge: typeof SpecialHttpError;
URITooLong: typeof SpecialHttpError;
UnsupportedMediaType: typeof SpecialHttpError;
RangeNotStatisfiable: typeof SpecialHttpError;
ExpectationFailed: typeof SpecialHttpError;
ImATeapot: typeof SpecialHttpError;
MisdirectedRequest: typeof SpecialHttpError;
UnprocessableEntity: typeof SpecialHttpError;
Locked: typeof SpecialHttpError;
FailedDependency: typeof SpecialHttpError;
UnorderedCollection: typeof SpecialHttpError;
UpgradeRequired: typeof SpecialHttpError;
PreconditionRequired: typeof SpecialHttpError;
TooManyRequests: typeof SpecialHttpError;
RequestHeaderFieldsTooLarge: typeof SpecialHttpError;
UnavailableForLegalReasons: typeof SpecialHttpError;
InternalServerError: typeof SpecialHttpError;
NotImplemented: typeof SpecialHttpError;
BadGateway: typeof SpecialHttpError;
ServiceUnavailable: typeof SpecialHttpError;
GatewayTimeout: typeof SpecialHttpError;
HTTPVersionNotSupported: typeof SpecialHttpError;
VariantAlsoNegotiates: typeof SpecialHttpError;
InsufficientStorage: typeof SpecialHttpError;
LoopDetected: typeof SpecialHttpError;
BandwidthLimitExceeded: typeof SpecialHttpError;
NotExtended: typeof SpecialHttpError;
NetworkAuthenticationRequired: typeof SpecialHttpError;
}
}
|
var PixiText = require('../../lib/pixi/src/core/text/Text'),
utils = require('../core/utils'),
math = require('../../lib/pixi/src/core/math'),
Sprite = require('../display/Sprite'),
CONST = require('../core/const');
function Text(text, style, resolution){
this._init(text, style, resolution);
}
Text.prototype = Object.create(PixiText.prototype);
Text.prototype.constructor = Text;
Text.fontPropertiesCache = {};
Text.fontPropertiesCanvas = document.createElement('canvas');
Text.fontPropertiesContext = Text.fontPropertiesCanvas.getContext('2d');
Text.prototype._init = function(text, style, resolution){
text = text || ' ';
PixiText.call(this, text, style, resolution);
this.speed = new math.Point();
this.anchor = new math.Point(0.5, 0.5);
this.pivot = new math.Point(0.5, 0.5);
};
Text.prototype.displayObjectUpdateTransform = function(){
// create some matrix refs for easy access
var pt = this.parent.worldTransform;
var wt = this.worldTransform;
//anchor, pivot, and flip variables
var sx = (this.flipX) ? -this.scale.x : this.scale.x,
sy = (this.flipY) ? -this.scale.y : this.scale.y,
ax = (this.flipX) ? 1-this.anchor.x : this.anchor.x,
ay = (this.flipY) ? 1-this.anchor.y : this.anchor.y,
px = (this.flipX) ? 1-this.pivot.x : this.pivot.x,
py = (this.flipY) ? 1-this.pivot.y : this.pivot.y;
// temporary matrix variables
var a, b, c, d, tx, ty;
//Avoid use _width or _height when are 0
if(!this._width||!this._height){
this._width = this.width/this.scale.x;
this._height = this.height/this.scale.y;
}
var anchorWidth = ax * this._width * sx,
anchorHeight = ay * this._height * sy,
pivotWidth = px * this._width * sx,
pivotHeight = py * this._height * sy;
// so if rotation is between 0 then we can simplify the multiplication process...
if (this.rotation % CONST.PI_2)
{
// check to see if the rotation is the same as the previous render. This means we only need to use sin and cos when rotation actually changes
if (this.rotation !== this.rotationCache)
{
this.rotationCache = this.rotation;
this._sr = Math.sin(this.rotation);
this._cr = Math.cos(this.rotation);
}
// get the matrix values of the displayobject based on its transform properties..
a = this._cr * sx;
b = this._sr * sx;
c = -this._sr * sy;
d = this._cr * sy;
tx = this.position.x + pivotWidth - anchorWidth;
ty = this.position.y + pivotHeight - anchorHeight;
if (pivotWidth || pivotHeight)
{
tx -= pivotWidth * this._cr + pivotHeight * -this._sr;
ty -= pivotWidth * this._sr + pivotHeight * this._cr;
}
// concat the parent matrix with the objects transform.
wt.a = a * pt.a + b * pt.c;
wt.b = a * pt.b + b * pt.d;
wt.c = c * pt.a + d * pt.c;
wt.d = c * pt.b + d * pt.d;
wt.tx = tx * pt.a + ty * pt.c + pt.tx;
wt.ty = tx * pt.b + ty * pt.d + pt.ty;
}
else
{
// lets do the fast version as we know there is no rotation..
a = sx;
d = sy;
tx = this.position.x - anchorWidth;
ty = this.position.y - anchorHeight;
wt.a = a * pt.a;
wt.b = a * pt.b;
wt.c = d * pt.c;
wt.d = d * pt.d;
wt.tx = tx * pt.a + ty * pt.c + pt.tx;
wt.ty = tx * pt.b + ty * pt.d + pt.ty;
}
// multiply the alphas..
this.worldAlpha = this.alpha * this.parent.worldAlpha;
// reset the bounds each time this is called!
this._currentBounds = null;
};
Text.prototype._renderCanvas = function (renderer)
{
if (this.dirty)
{
// this.resolution = 1//renderer.resolution;
this.updateText();
}
//Sprite.prototype._renderCanvas.call(this, renderer);
this._customRenderCanvas(renderer);
};
Text.prototype._customRenderCanvas = function(renderer){
if (this.texture.crop.width <= 0 || this.texture.crop.height <= 0)
{
return;
}
if (this.blendMode !== renderer.currentBlendMode)
{
renderer.currentBlendMode = this.blendMode;
renderer.context.globalCompositeOperation = renderer.blendModes[renderer.currentBlendMode];
}
// Ignore null sources
if (this.texture.valid)
{
var texture = this._texture,
wt = this.worldTransform,
dx,
dy,
width,
height;
var resolution = texture.baseTexture.resolution / renderer.resolution;
renderer.context.globalAlpha = this.worldAlpha;
// If smoothingEnabled is supported and we need to change the smoothing property for this texture
if (renderer.smoothProperty && renderer.currentScaleMode !== texture.baseTexture.scaleMode)
{
renderer.currentScaleMode = texture.baseTexture.scaleMode;
renderer.context[renderer.smoothProperty] = (renderer.currentScaleMode === CONST.SCALE_MODES.LINEAR);
}
// If the texture is trimmed we offset by the trim x/y, otherwise we use the frame dimensions
if(texture.rotate)
{
// cheeky rotation!
var a = wt.a;
var b = wt.b;
wt.a = -wt.c;
wt.b = -wt.d;
wt.c = a;
wt.d = b;
width = texture.crop.height; //TODO: Width assigned to height???
height = texture.crop.width;
dx = (texture.trim) ? texture.trim.y - this.anchor.y * texture.trim.height : this.anchor.y * -texture._frame.height;
dy = (texture.trim) ? texture.trim.x - this.anchor.x * texture.trim.width : this.anchor.x * -texture._frame.width;
}
else
{
width = texture.crop.width;
height = texture.crop.height;
dx = (texture.trim) ? texture.trim.x - this.anchor.x * texture.trim.width : this.anchor.x * -texture._frame.width;
dy = (texture.trim) ? texture.trim.y - this.anchor.y * texture.trim.height : this.anchor.y * -texture._frame.height;
}
// Allow for pixel rounding
if (renderer.roundPixels)
{
renderer.context.setTransform(
wt.a,
wt.b,
wt.c,
wt.d,
(wt.tx * renderer.resolution) | 0,
(wt.ty * renderer.resolution) | 0
);
dx = dx | 0;
dy = dy | 0;
}
else
{
renderer.context.setTransform(
wt.a,
wt.b,
wt.c,
wt.d,
wt.tx * renderer.resolution,
wt.ty * renderer.resolution
);
}
var anchorWidth = this.anchor.x * this._width/resolution,
anchorHeight = this.anchor.y * this._height/resolution;
if (this.tint !== 0xFFFFFF)
{
if (this.cachedTint !== this.tint)
{
this.cachedTint = this.tint;
// TODO clean up caching - how to clean up the caches?
// TODO: dont works with spritesheets
this.tintedTexture = CanvasTinter.getTintedTexture(this, this.tint);
}
renderer.context.drawImage(
this.tintedTexture,
0,
0,
width * resolution * renderer.resolution,
height * resolution * renderer.resolution,
dx / resolution,
dy / resolution,
width * renderer.resolution,
height * renderer.resolution
);
}
else
{
//TODO: cuando la resolución del renderer es mayor a 1 los sprites se muestran mal
renderer.context.drawImage(
texture.baseTexture.source,
texture.crop.x * resolution,
texture.crop.y * resolution,
width * resolution * renderer.resolution,
height * resolution * renderer.resolution,
dx / resolution + anchorWidth,
dy / resolution + anchorHeight,
width * renderer.resolution,
height * renderer.resolution
);
}
}
};
Text.prototype.renderWebGL = function (renderer)
{
if (this.dirty)
{
//this.resolution = 1//renderer.resolution;
this.updateText();
}
Sprite.prototype.renderWebGL.call(this, renderer);
};
Text.prototype.updateText = function (){
var style = this._style;
this.context.font = style.font;
// word wrap
// preserve original text
var outputText = style.wordWrap ? this.wordWrap(this._text) : this._text;
// split text into lines
var lines = outputText.split(/(?:\r\n|\r|\n)/);
// calculate text width
var lineWidths = new Array(lines.length);
var maxLineWidth = 0;
var fontProperties = this.determineFontProperties(style.font);
for (var i = 0; i < lines.length; i++)
{
var lineWidth = this.context.measureText(lines[i]).width;
lineWidths[i] = lineWidth;
maxLineWidth = Math.max(maxLineWidth, lineWidth);
}
var width = maxLineWidth + style.strokeThickness;
if (style.dropShadow)
{
width += style.dropShadowDistance;
}
this.canvas.width = ( width + this.context.lineWidth ) * this.resolution;
// calculate text height
var lineHeight = this.style.lineHeight || fontProperties.fontSize + style.strokeThickness;
var height = lineHeight * lines.length;
if (style.dropShadow)
{
height += style.dropShadowDistance;
}
this.canvas.height = ( height + this._style.padding * 2 ) * this.resolution;
this.context.scale( this.resolution, this.resolution);
if (navigator.isCocoonJS)
{
this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
}
//this.context.fillStyle="#FF0000";
//this.context.fillRect(0, 0, this.canvas.width, this.canvas.height);
this.context.font = style.font;
this.context.strokeStyle = (typeof style.stroke === "number") ? utils.hex2string(style.stroke) : style.stroke;
this.context.lineWidth = style.strokeThickness;
this.context.textBaseline = style.textBaseline;
this.context.lineJoin = style.lineJoin;
this.context.miterLimit = style.miterLimit;
var linePositionX;
var linePositionY;
if (style.dropShadow)
{
this.context.fillStyle = style.dropShadowColor;
var xShadowOffset = Math.cos(style.dropShadowAngle) * style.dropShadowDistance;
var yShadowOffset = Math.sin(style.dropShadowAngle) * style.dropShadowDistance;
for (i = 0; i < lines.length; i++)
{
linePositionX = style.strokeThickness / 2;
linePositionY = (style.strokeThickness / 2 + i * lineHeight) + fontProperties.ascent;
if (style.align === 'right')
{
linePositionX += maxLineWidth - lineWidths[i];
}
else if (style.align === 'center')
{
linePositionX += (maxLineWidth - lineWidths[i]) / 2;
}
if (style.fill)
{
this.context.fillText(lines[i], linePositionX + xShadowOffset, linePositionY + yShadowOffset + this._style.padding);
}
}
}
//set canvas text styles
this.context.fillStyle = (typeof style.fill === "number") ? utils.hex2string(style.fill) : style.fill;
//draw lines line by line
for (i = 0; i < lines.length; i++)
{
linePositionX = style.strokeThickness / 2;
linePositionY = (style.strokeThickness / 2 + i * lineHeight) + fontProperties.ascent;
if (style.align === 'right')
{
linePositionX += maxLineWidth - lineWidths[i];
}
else if (style.align === 'center')
{
linePositionX += (maxLineWidth - lineWidths[i]) / 2;
}
if (style.stroke && style.strokeThickness)
{
this.context.strokeText(lines[i], linePositionX, linePositionY + this._style.padding);
}
if (style.fill)
{
this.context.fillText(lines[i], linePositionX, linePositionY + this._style.padding);
}
}
this.updateTexture();
};
Text.prototype.setStyle = function(style){
this.style = style;
return this;
};
Text.prototype.setText = function(text, keys){
if(keys)text = utils.parseTextKeys(text, keys);
this.text = text;
return this;
};
Text.prototype.setWordWrap = function(value){
if(value === false){
this.style.wordWrap = value;
}else{
this.style.wordWrap = true;
this.style.wordWrapWidth = value;
}
this.dirty = true;
return this;
};
Text.prototype.containsPoint = Sprite.prototype.containsPoint;
Text.prototype.getLocalBounds = Sprite.prototype.getLocalBounds;
module.exports = Text;
|
/**
* A wrapper around JSLint to drop things into the console
*
* Copyright (C) 2011 Nikolay Nemshilov
*/
var RightJS = require('./right-server.js');
var JSLint = require('./jslint').JSLINT;
var fs = require('fs');
exports.Linter = new RightJS.Class({
extend: {
Options: {
debug: false, // no debug
devel: false, // no console.log s
evil: false, // no evals
passfail: false, // don't stop on errors
onevar: false, // allow more than one 'var' definition
forin: true , // allow for in without ownershipt checks
indent: 2 , // enforce 2 spaces indent
maxerr: 12 , // max number of errors
},
Okays: [
"Move 'var' declarations to the top of the function.",
"Do not use 'new' for side effects.",
"The Function constructor is eval."
]
},
/**
* Basic constructor
*
* @param {String} the source
* @param {String} the linter options
* @return void
*/
initialize: function(src, options) {
this.source = src;
this.options = options;
},
/**
* Runs the linter
*
* @return {Linter} this
*/
run: function() {
var options = {}, okays = [], patches = '';
// extracting the additional options
try { // skipping non-existing patch files
patches = fs.readFileSync(this.options).toString();
} catch(e) {}
eval(patches);
JSLint.okays = this.constructor.Okays.concat(okays);
JSLint(
fs.readFileSync(this.source).toString(),
Object.merge(this.constructor.Options, options)
);
this.errors = JSLint.errors.compact();
this.failed = this.errors.length > 0;
return this;
},
/**
* Prints out the check report
*
* @return {Linter} this
*/
report: function() {
if (this.errors.empty()) {
console.log("\u001B[32m - JSLint check successfully passed\u001B[0m");
} else {
console.log("\u001B[31m - JSLint check failed in: "+ this.source + "\u001B[0m");
this.errors.each(function(error) {
var report = "\n", j=0, pointer='';
for (; j < error.character-1; j++) { pointer += '-'; }
report += " \u001B[35m"+ error.reason +"\u001B[0m ";
if (error.evidence) {
report += "Line: "+ error.line + ", Char: "+ error.character + "\n";
report += " "+ error.evidence + "\n";
report += " \u001B[33m"+ pointer + "^\u001B[0m";
}
console.log(report);
});
console.log("\n")
}
return this;
}
}); |
import React, { PropTypes } from 'react'
import ActionDelete from 'material-ui/svg-icons/action/delete'
import { colors } from '/styles'
import moduleStyles from '/styles/fileTree'
const RemoveBtn = ({ onClick }) => (
<ActionDelete
onClick={onClick}
style={moduleStyles.listIcon.base}
color={colors.light}
hoverColor={colors.hover.red} />
)
export default RemoveBtn
|
import { Observable } from './observable'
export default function drop(count, source) {
return Observable(add => {
let dropped = 0
return source.subscribe((val, name) => {
if (dropped++ >= count) add(val, name)
})
})
}
|
import React, { Component } from 'react'
import {
FlexGrid, Content, Container,
AdminItemsViewTable,
Table, Button
} from 'components'
import {
AddItemAboutContainer,
AddItemPhotoContainer,
SpecialSetupContainer
} from 'containers'
import { adminLink } from 'config'
import s from './AdminItemsView.sass'
class ToggleButton extends Component {
state = {value: this.props.value};
componentWillMount() {
this.setState({value: this.props.value})
}
componentWillReceiveProps(nextProps) {
if (nextProps.value !== this.props.value) {
this.setState({value: nextProps.value});
}
}
onClick = () => {
if (!this.props.onChange)
return;
const { field, id, value } = this.props;
const newValue = !value;
this.props.onChange({
[field]: newValue,
id
});
this.setState({value: newValue})
};
render() {
const { children } = this.props;
const { onClick } = this;
const { value } = this.state;
return (
<FlexGrid className={s.toggle} direction="column"
justify="center" align="center">
<Content size="5" center gray>{children}</Content>
<Table.RowItem className={s.toggle__icon} tag="span"
onClick={onClick}
circle circleActive={value}/>
</FlexGrid>
)
}
}
export default class AdminItemsView extends Component {
render() {
const {
data, parent_id, brands, categories,
onChange, onDelete, onAboutChange,
aboutData, onSave, onColorChange, onSpecialChange
} = this.props;
if (!data || data.id == null)
return null;
const { id } = data;
return (
<div className={s.wrapper}>
<AdminItemsViewTable data={data} brands={brands}
onChange={onChange}
categories={categories} />
<div className={s.line} />
<Container className={s.content}>
<FlexGrid justify="start" align="start">
<div className={s.grid}>
<FlexGrid className={s.toggle__wrapper}
justify="start" align="start">
<ToggleButton id={id} onChange={onChange} field="is_top"
value={data.is_top}>Топ</ToggleButton>
<ToggleButton id={id} onChange={onChange} field="is_new"
value={data.is_new}>Новинка</ToggleButton>
<ToggleButton id={id} onChange={onChange} field="is_special_active"
value={data.is_special_active}>Акция</ToggleButton>
<ToggleButton id={id} onChange={onChange} field="warranty"
value={data.warranty}>Гарантия</ToggleButton>
</FlexGrid>
<Content className={s.title} regular size="5">
Изображения
</Content>
<AddItemPhotoContainer __onChange={onColorChange} color={data.color} custom/>
<SpecialSetupContainer onChange={onSpecialChange} />
</div>
<div className={s.grid}>
<AddItemAboutContainer data={aboutData} custom
onSave={onSave}
__onChange={onAboutChange}/>
</div>
</FlexGrid>
<div className={s.actions}>
<Button type="blue" to={`${adminLink.path}/items/${parent_id}`}>
Отредактировать модель
</Button>
<Button className={s.btn} type="pink"
onClick={onDelete}>
Удалить
</Button>
</div>
</Container>
</div>
)
}
}
|
const LogTestPlugin = require("../../helpers/LogTestPlugin");
/** @type {import("../../../").Configuration} */
module.exports = {
mode: "production",
entry: "./index",
stats: "normal",
plugins: [new LogTestPlugin()]
};
|
import { expect } from 'chai'
import browser from '../../src/util/browser'
describe('util (node)', () => {
describe('browser', () => {
it('is false', () => {
expect(browser).to.be.false
})
})
})
|
// Seriously awesome GLSL noise functions. (C) Credits and kudos go to
// Copyright (C) Stefan Gustavson, Ian McEwan Ashima Arts
// MIT License.
define(function(require, exports){
exports.permute1 = function(x){
return mod((34.0 * x + 1.0) * x, 289.0)
}
exports.permute3 = function(x){
return mod((34.0 * x + 1.0) * x, 289.0)
}
exports.permute4 = function(x){
return mod((34.0 * x + 1.0) * x, 289.0)
}
exports.isqrtT1 = function(r){
return 1.79284291400159 - 0.85373472095314 * r
}
exports.isqrtT4 = function(r){
return vec4(1.79284291400159 - 0.85373472095314 * r)
}
exports.snoise2 = function(x, y){
return snoise2v(vec2(x,y,z))
}
exports.noise2d =
exports.s2d =
exports.snoise2v = function(v){
var C = vec4(0.211324865405187,0.366025403784439,-0.577350269189626,0.024390243902439)
var i = floor(v + dot(v, C.yy) )
var x0 = v - i + dot(i, C.xx)
var i1 = (x0.x > x0.y) ? vec2(1.0, 0.0) : vec2(0.0, 1.0)
var x12 = x0.xyxy + C.xxzz
x12.xy -= i1
i = mod(i, 289.0) // Avoid truncation effects in permutation
var p = permute3(permute3(i.y + vec3(0.0, i1.y, 1.0)) + i.x + vec3(0.0, i1.x, 1.0 ))
var m = max(0.5 - vec3(dot(x0,x0), dot(x12.xy,x12.xy), dot(x12.zw,x12.zw)), 0.0)
m = m*m
m = m*m
var x = 2.0 * fract(p * C.www) - 1.0
var h = abs(x) - 0.5
var ox = floor(x + 0.5)
var a0 = x - ox
m *= (1.79284291400159 - 0.85373472095314 * ( a0*a0 + h*h ))
var g = vec3()
g.x = a0.x * x0.x + h.x * x0.y
g.yz = a0.yz * x12.xz + h.yz * x12.yw
return 130.0 * dot(m, g)
}
exports.snoise3 = function(x, y, z){
return snoise3v(vec3(x,y,z))
}
exports.noise3d =
exports.snoise3v = function(v){
var C = vec2(1.0/6.0, 1.0/3.0)
var D = vec4(0.0, 0.5, 1.0, 2.0)
// First corner
var i = floor(v + dot(v, C.yyy))
var x0 = v - i + dot(i, C.xxx)
var g = step(x0.yzx, x0.xyz)
var l = 1.0 - g
var i1 = min(g.xyz, l.zxy)
var i2 = max(g.xyz, l.zxy)
var x1 = x0 - i1 + 1.0 * C.xxx
var x2 = x0 - i2 + 2.0 * C.xxx
var x3 = x0 - 1. + 3.0 * C.xxx
// Permutations
i = mod(i, 289.0)
var p = permute4(permute4(permute4(
i.z + vec4(0.0, i1.z, i2.z, 1.0))
+ i.y + vec4(0.0, i1.y, i2.y, 1.0))
+ i.x + vec4(0.0, i1.x, i2.x, 1.0))
// ( N*N points uniformly over a square, mapped onto an octahedron.)
var n_ = 1.0/7.0
var ns = n_ * D.wyz - D.xzx
var j = p - 49.0 * floor(p * ns.z *ns.z)
var x_ = floor(j * ns.z)
var y_ = floor(j - 7.0 * x_)
var x = x_ * ns.x + ns.yyyy
var y = y_ * ns.x + ns.yyyy
var h = 1.0 - abs(x) - abs(y)
var b0 = vec4( x.xy, y.xy )
var b1 = vec4( x.zw, y.zw )
var s0 = floor(b0)*2.0 + 1.0
var s1 = floor(b1)*2.0 + 1.0
var sh = -step(h, vec4(0.0))
var a0 = b0.xzyw + s0.xzyw*sh.xxyy
var a1 = b1.xzyw + s1.xzyw*sh.zzww
var p0 = vec3(a0.xy, h.x)
var p1 = vec3(a0.zw, h.y)
var p2 = vec3(a1.xy, h.z)
var p3 = vec3(a1.zw, h.w)
//Normalise gradients
var norm = isqrtT4(vec4(dot(p0,p0), dot(p1,p1), dot(p2, p2), dot(p3,p3)))
p0 *= norm.x;
p1 *= norm.y;
p2 *= norm.z;
p3 *= norm.w;
// Mix final noise value
var m = max(0.6 - vec4(dot(x0,x0), dot(x1,x1), dot(x2,x2), dot(x3,x3)), 0.0)
m = m * m
return 42.0 * dot( m*m, vec4( dot(p0,x0), dot(p1,x1),
dot(p2,x2), dot(p3,x3) ) )
}
exports.snoise4_g = function(j, ip){
var p = vec4()
p.xyz = floor( fract (vec3(j) * ip.xyz) * 7.0) * ip.z - 1.0
p.w = 1.5 - dot(abs(p.xyz), vec3(1.0,1.0,1.0))
var s = vec4(lessThan(p, vec4(0.0)))
p.xyz = p.xyz + (s.xyz*2.0 - 1.0) * s.www
return p
}
exports.snoise4 = function(x, y, z, w){
return snoise4v(vec4(x,y,z,w))
}
exports.snoise4v = function(v){
var C = vec4(0.138196601125011,0.276393202250021,0.414589803375032,-0.447213595499958)
// First corner
var i = floor(v + dot(v, vec4(0.309016994374947451)) )
var x0 = v - i + dot(i, C.xxxx)
var i0 = vec4()
var isX = step( x0.yzw, x0.xxx )
var isYZ = step( x0.zww, x0.yyz )
i0.x = isX.x + isX.y + isX.z
i0.yzw = 1.0 - isX
i0.y += isYZ.x + isYZ.y
i0.zw += 1.0 - isYZ.xy
i0.z += isYZ.z
i0.w += 1.0 - isYZ.z
var i3 = clamp( i0, 0.0, 1.0 )
var i2 = clamp( i0-1.0, 0.0, 1.0 )
var i1 = clamp( i0-2.0, 0.0, 1.0 )
var x1 = x0 - i1 + C.xxxx
var x2 = x0 - i2 + C.yyyy
var x3 = x0 - i3 + C.zzzz
var x4 = x0 + C.wwww
// Permutations
i = mod(i, 289.0 )
var j0 = permute1( permute1( permute1( permute1(i.w) + i.z) + i.y) + i.x)
var j1 = permute4( permute4( permute4( permute4(
i.w + vec4(i1.w, i2.w, i3.w, 1.0 ))
+ i.z + vec4(i1.z, i2.z, i3.z, 1.0 ))
+ i.y + vec4(i1.y, i2.y, i3.y, 1.0 ))
+ i.x + vec4(i1.x, i2.x, i3.x, 1.0 ))
// Gradients: 7x7x6 points over a cube, mapped onto a 4-cross polytope
// 7*7*6 = 294, which is close to the ring size 17*17 = 289.
var ip = vec4(1.0/294.0, 1.0/49.0, 1.0/7.0, 0.0)
var p0 = snoise4_g(j0, ip)
var p1 = snoise4_g(j1.x, ip)
var p2 = snoise4_g(j1.y, ip)
var p3 = snoise4_g(j1.z, ip)
var p4 = snoise4_g(j1.w, ip)
// Normalise gradients
var nr = isqrtT4(vec4(dot(p0,p0), dot(p1,p1), dot(p2, p2), dot(p3,p3)))
p0 *= nr.x
p1 *= nr.y
p2 *= nr.z
p3 *= nr.w
p4 *= isqrtT1(dot(p4,p4))
// Mix contributions from the five corners
var m0 = max(0.6 - vec3(dot(x0,x0), dot(x1,x1), dot(x2,x2)), 0.0)
var m1 = max(0.6 - vec2(dot(x3,x3), dot(x4,x4)), 0.0)
m0 = m0 * m0
m1 = m1 * m1
return 49.0 * (dot(m0*m0, vec3(dot( p0, x0 ), dot(p1, x1), dot(p2, x2)))
+ dot(m1*m1, vec2( dot(p3, x3), dot(p4, x4))))
}
exports.cell2v = function(v){
return cell3v(vec3(v.x, v.y,0))
}
exports.cell3v = function(P){
var K = 0.142857142857 // 1/7
var Ko = 0.428571428571 // 1/2-K/2
var K2 = 0.020408163265306 // 1/(7*7)
var Kz = 0.166666666667 // 1/6
var Kzo = 0.416666666667 // 1/2-1/6*2
var ji = 0.8 // smaller jitter gives less errors in F2
var Pi = mod(floor(P), 289.0)
var Pf = fract(P)
var Pfx = Pf.x + vec4(0.0, -1.0, 0.0, -1.0)
var Pfy = Pf.y + vec4(0.0, 0.0, -1.0, -1.0)
var p = permute4(Pi.x + vec4(0.0, 1.0, 0.0, 1.0))
p = permute4(p + Pi.y + vec4(0.0, 0.0, 1.0, 1.0))
var p1 = permute4(p + Pi.z) // z+0
var p2 = permute4(p + Pi.z + vec4(1.0)) // z+1
var ox1 = fract(p1*K) - Ko
var oy1 = mod(floor(p1*K), 7.0)*K - Ko
var oz1 = floor(p1*K2)*Kz - Kzo // p1 < 289 guaranteed
var ox2 = fract(p2*K) - Ko
var oy2 = mod(floor(p2*K), 7.0)*K - Ko
var oz2 = floor(p2*K2)*Kz - Kzo
var dx1 = Pfx + ji*ox1
var dy1 = Pfy + ji*oy1
var dz1 = Pf.z + ji*oz1
var dx2 = Pfx + ji*ox2
var dy2 = Pfy + ji*oy2
var dz2 = Pf.z - 1.0 + ji*oz2
var d1 = dx1 * dx1 + dy1 * dy1 + dz1 * dz1 // z+0
var d2 = dx2 * dx2 + dy2 * dy2 + dz2 * dz2 // z+1
var d = min(d1,d2) // F1 is now in d
d2 = max(d1,d2) // Make sure we keep all candidates for F2
d.xy = (d.x < d.y) ? d.xy : d.yx // Swap smallest to d.x
d.xz = (d.x < d.z) ? d.xz : d.zx
d.xw = (d.x < d.w) ? d.xw : d.wx // F1 is now in d.x
d.yzw = min(d.yzw, d2.yzw) // F2 now not in d2.yzw
d.y = min(d.y, d.z) // nor in d.z
d.y = min(d.y, d.w) // nor in d.w
d.y = min(d.y, d2.x) // F2 is now in d.y
return sqrt(d.xy) // F1 and F2
},
exports.cell3w = function(P){
var K = 0.142857142857
var Ko = 0.428571428571 // 1/2-K/2
var K2 = 0.020408163265306// 1/(7*7)
var Kz = 0.166666666667// 1/6
var Kzo = 0.416666666667// 1/2-1/6*2
var ji = 1.0// smaller jitter gives more regular pattern
var Pi = mod(floor(P), 289.0)
var Pf = fract(P) - 0.5
var Pfx = Pf.x + vec3(1.0, 0.0, -1.0)
var Pfy = Pf.y + vec3(1.0, 0.0, -1.0)
var Pfz = Pf.z + vec3(1.0, 0.0, -1.0)
var p = permute3(Pi.x + vec3(-1.0, 0.0, 1.0))
var p1 = permute3(p + Pi.y - 1.0)
var p2 = permute3(p + Pi.y)
var p3 = permute3(p + Pi.y + 1.0)
var p11 = permute3(p1 + Pi.z - 1.0)
var p12 = permute3(p1 + Pi.z)
var p13 = permute3(p1 + Pi.z + 1.0)
var p21 = permute3(p2 + Pi.z - 1.0)
var p22 = permute3(p2 + Pi.z)
var p23 = permute3(p2 + Pi.z + 1.0)
var p31 = permute3(p3 + Pi.z - 1.0)
var p32 = permute3(p3 + Pi.z)
var p33 = permute3(p3 + Pi.z + 1.0)
var ox11 = fract(p11*K) - Ko
var oy11 = mod(floor(p11*K), 7.0)*K - Ko
var oz11 = floor(p11*K2)*Kz - Kzo // p11 < 289 guaranteed
var ox12 = fract(p12*K) - Ko
var oy12 = mod(floor(p12*K), 7.0)*K - Ko
var oz12 = floor(p12*K2)*Kz - Kzo
var ox13 = fract(p13*K) - Ko
var oy13 = mod(floor(p13*K), 7.0)*K - Ko
var oz13 = floor(p13*K2)*Kz - Kzo
var ox21 = fract(p21*K) - Ko
var oy21 = mod(floor(p21*K), 7.0)*K - Ko
var oz21 = floor(p21*K2)*Kz - Kzo
var ox22 = fract(p22*K) - Ko
var oy22 = mod(floor(p22*K), 7.0)*K - Ko
var oz22 = floor(p22*K2)*Kz - Kzo
var ox23 = fract(p23*K) - Ko
var oy23 = mod(floor(p23*K), 7.0)*K - Ko
var oz23 = floor(p23*K2)*Kz - Kzo
var ox31 = fract(p31*K) - Ko
var oy31 = mod(floor(p31*K), 7.0)*K - Ko
var oz31 = floor(p31*K2)*Kz - Kzo
var ox32 = fract(p32*K) - Ko
var oy32 = mod(floor(p32*K), 7.0)*K - Ko
var oz32 = floor(p32*K2)*Kz - Kzo
var ox33 = fract(p33*K) - Ko
var oy33 = mod(floor(p33*K), 7.0)*K - Ko
var oz33 = floor(p33*K2)*Kz - Kzo
var dx11 = Pfx + ji*ox11
var dy11 = Pfy.x + ji*oy11
var dz11 = Pfz.x + ji*oz11
var dx12 = Pfx + ji*ox12
var dy12 = Pfy.x + ji*oy12
var dz12 = Pfz.y + ji*oz12
var dx13 = Pfx + ji*ox13
var dy13 = Pfy.x + ji*oy13
var dz13 = Pfz.z + ji*oz13
var dx21 = Pfx + ji*ox21
var dy21 = Pfy.y + ji*oy21
var dz21 = Pfz.x + ji*oz21
var dx22 = Pfx + ji*ox22
var dy22 = Pfy.y + ji*oy22
var dz22 = Pfz.y + ji*oz22
var dx23 = Pfx + ji*ox23
var dy23 = Pfy.y + ji*oy23
var dz23 = Pfz.z + ji*oz23
var dx31 = Pfx + ji*ox31
var dy31 = Pfy.z + ji*oy31
var dz31 = Pfz.x + ji*oz31
var dx32 = Pfx + ji*ox32
var dy32 = Pfy.z + ji*oy32
var dz32 = Pfz.y + ji*oz32
var dx33 = Pfx + ji*ox33
var dy33 = Pfy.z + ji*oy33
var dz33 = Pfz.z + ji*oz33
var d11 = dx11 * dx11 + dy11 * dy11 + dz11 * dz11
var d12 = dx12 * dx12 + dy12 * dy12 + dz12 * dz12
var d13 = dx13 * dx13 + dy13 * dy13 + dz13 * dz13
var d21 = dx21 * dx21 + dy21 * dy21 + dz21 * dz21
var d22 = dx22 * dx22 + dy22 * dy22 + dz22 * dz22
var d23 = dx23 * dx23 + dy23 * dy23 + dz23 * dz23
var d31 = dx31 * dx31 + dy31 * dy31 + dz31 * dz31
var d32 = dx32 * dx32 + dy32 * dy32 + dz32 * dz32
var d33 = dx33 * dx33 + dy33 * dy33 + dz33 * dz33
var d1a = min(d11, d12)
d12 = max(d11, d12)
d11 = min(d1a, d13) // Smallest now not in d12 or d13
d13 = max(d1a, d13)
d12 = min(d12, d13) // 2nd smallest now not in d13
var d2a = min(d21, d22)
d22 = max(d21, d22)
d21 = min(d2a, d23) // Smallest now not in d22 or d23
d23 = max(d2a, d23)
d22 = min(d22, d23) // 2nd smallest now not in d23
var d3a = min(d31, d32)
d32 = max(d31, d32)
d31 = min(d3a, d33) // Smallest now not in d32 or d33
d33 = max(d3a, d33)
d32 = min(d32, d33) // 2nd smallest now not in d33
var da = min(d11, d21)
d21 = max(d11, d21)
d11 = min(da, d31) // Smallest now in d11
d31 = max(da, d31) // 2nd smallest now not in d31
d11.xy = (d11.x < d11.y) ? d11.xy : d11.yx
d11.xz = (d11.x < d11.z) ? d11.xz : d11.zx // d11.x now smallest
d12 = min(d12, d21) // 2nd smallest now not in d21
d12 = min(d12, d22) // nor in d22
d12 = min(d12, d31) // nor in d31
d12 = min(d12, d32) // nor in d32
d11.yz = min(d11.yz, d12.xy) // nor in d12.yz
d11.y = min(d11.y, d12.z) // Only two more to go
d11.y = min(d11.y, d11.z) // Done! (Phew!)
return sqrt(d11.xy) // F1, F2
}
}) |
var $ = require('jquery');
var keymaster = require('keymaster');
var ChartEditor = require('./component-chart-editor.js');
var DbInfo = require('./component-db-info.js');
var AceSqlEditor = require('./component-ace-sql-editor.js');
var DataGrid = require('./component-data-grid.js');
var QueryEditor = function () {
var chartEditor = new ChartEditor();
var dbInfo = new DbInfo();
var aceSqlEditor = new AceSqlEditor("ace-editor");
var dataGrid = new DataGrid();
function runQuery () {
$('#server-run-time').html('');
$('#rowcount').html('');
dataGrid.emptyDataGrid();
var data = {
queryText: aceSqlEditor.getSelectedOrAllText(),
connectionId: $('#connection').val(),
cacheKey: $('#cache-key').val(),
queryName: getQueryName()
};
dataGrid.startRunningTimer();
$.ajax({
type: "POST",
url: "/run-query",
data: data
}).done(function (data) {
chartEditor.setData(data);
// TODO - if vis tab is active, render chart
dataGrid.stopRunningTimer();
$('#server-run-time').html(data.serverMs/1000 + " sec.");
if (data.success) {
$('.hide-while-running').show();
if (data.incomplete) {
$('.incomplete-notification').removeClass("hidden");
} else {
$('.incomplete-notification').addClass("hidden");
}
dataGrid.renderGridData(data);
} else {
dataGrid.renderError(data.error);
}
}).fail(function () {
dataGrid.stopRunningTimer();
dataGrid.renderError("Something is broken :(");
});
}
function getQueryName () {
return $('#header-query-name').val();
}
function getQueryTags () {
return $.map($('#tags').val().split(','), $.trim);
}
function saveQuery () {
var $queryId = $('#query-id');
var query = {
name: getQueryName(),
queryText: aceSqlEditor.getEditorText(),
tags: getQueryTags(),
connectionId: dbInfo.getConnectionId(),
chartConfiguration: chartEditor.getChartConfiguration()
};
$('#btn-save-result').text('saving...').show();
$.ajax({
type: "POST",
url: "/queries/" + $queryId.val(),
data: query
}).done(function (data) {
if (data.success) {
window.history.replaceState({}, "query " + data.query._id, "/queries/" + data.query._id);
$queryId.val(data.query._id);
$('#btn-save-result').removeClass('label-info').addClass('label-success').text('Success');
setTimeout(function () {
$('#btn-save-result').fadeOut(400, function () {
$('#btn-save-result').removeClass('label-success').addClass('label-info').text('');
});
}, 1000);
} else {
$('#btn-save-result').removeClass('label-info').addClass('label-danger').text('Failed');
}
}).fail(function () {
alert('ajax fail');
});
}
$('#btn-save').click(function (event) {
event.preventDefault();
event.stopPropagation();
saveQuery();
});
$('#btn-run-query').click(function (event) {
event.preventDefault();
event.stopPropagation();
runQuery();
});
/* (re-)render the chart when the viz tab is pressed,
TODO: only do this if necessary
==============================================================================*/
$('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
// if shown tab was the chart tab, rerender the chart
// e.target is the activated tab
if (e.target.getAttribute("href") == "#tab-content-visualize") {
chartEditor.rerenderChart();
} else if (e.target.getAttribute("href") == "#tab-content-sql") {
dataGrid.resize();
}
});
/* get query again, because not all the data is in the HTML
TODO: do most the workflow this way?
==============================================================================*/
var $queryId = $('#query-id');
$.ajax({
type: "GET",
url: "/queries/" + $queryId.val() + "?format=json"
}).done(function (data) {
console.log(data);
chartEditor.loadChartConfiguration(data.chartConfiguration);
}).fail(function () {
alert('Failed to get additional Query info');
});
/* Tags Typeahead
==============================================================================*/
var Bloodhound = require('Bloodhound');
var bloodhoundTags = new Bloodhound({
datumTokenizer: Bloodhound.tokenizers.obj.whitespace('name'),
queryTokenizer: Bloodhound.tokenizers.whitespace,
prefetch: {
url: '/tags', // array of tagnames
ttl: 0,
filter: function(list) {
return $.map(list, function(tag) {
return { name: tag }; });
}
}
});
bloodhoundTags.initialize();
$('#tags').tagsinput({
typeaheadjs: {
//name: 'tags',
displayKey: 'name',
valueKey: 'name',
source: bloodhoundTags.ttAdapter()
}
});
/* Shortcuts
==============================================================================*/
// keymaster doesn't fire on input/textarea events by default
// since we are only using command/ctrl shortcuts,
// we want the event to fire all the time for any element
keymaster.filter = function (event) {
return true;
};
keymaster('ctrl+s, command+s', function() {
saveQuery();
return false;
});
keymaster('ctrl+r, command+r, ctrl+e, command+e', function() {
runQuery();
return false;
});
};
module.exports = function () {
if ($('#ace-editor').length) {
new QueryEditor();
}
}; |
// # 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...
const should = require('should');
const sinon = require('sinon');
const supertest = require('supertest');
const moment = require('moment');
const cheerio = require('cheerio');
const _ = require('lodash');
const testUtils = require('../../utils');
const configUtils = require('../../utils/configUtils');
const urlUtils = require('../../utils/urlUtils');
const config = require('../../../core/shared/config');
const settingsCache = require('../../../core/server/services/settings/cache');
const origCache = _.cloneDeep(settingsCache);
const ghost = testUtils.startGhost;
let request;
describe('Frontend Routing', function () {
function doEnd(done) {
return function (err, res) {
if (err) {
return done(err);
}
should.not.exist(res.headers['x-cache-invalidate']);
should.not.exist(res.headers['X-CSRF-Token']);
should.not.exist(res.headers['set-cookie']);
should.exist(res.headers.date);
done();
};
}
function addPosts(done) {
testUtils.clearData().then(function () {
return testUtils.initData();
}).then(function () {
return testUtils.fixtures.insertPostsAndTags();
}).then(function () {
done();
});
}
afterEach(function () {
sinon.restore();
});
before(function () {
return ghost()
.then(function () {
request = supertest.agent(config.get('url'));
});
});
describe('Test with Initial Fixtures', function () {
describe('Error', function () {
it('should 404 for unknown post with invalid characters', function (done) {
request.get('/$pec+acular~/')
.expect('Cache-Control', testUtils.cacheRules.private)
.expect(404)
.expect(/Page not found/)
.end(doEnd(done));
});
it('should 404 for unknown frontend route', function (done) {
request.get('/spectacular/marvellous/')
.set('Accept', 'application/json')
.expect('Cache-Control', testUtils.cacheRules.private)
.expect(404)
.expect(/Page not found/)
.end(doEnd(done));
});
it('should 404 for encoded char not 301 from uncapitalise', function (done) {
request.get('/|/')
.expect('Cache-Control', testUtils.cacheRules.private)
.expect(404)
.expect(/Page not found/)
.end(doEnd(done));
});
});
describe('Default Redirects (clean URLS)', function () {
it('Single post should redirect without slash', function (done) {
request.get('/welcome')
.expect('Location', '/welcome/')
.expect('Cache-Control', testUtils.cacheRules.year)
.expect(301)
.end(doEnd(done));
});
it('Single post should redirect uppercase', function (done) {
request.get('/Welcome/')
.expect('Location', '/welcome/')
.expect('Cache-Control', testUtils.cacheRules.year)
.expect(301)
.end(doEnd(done));
});
it('Single post should sanitize double slashes when redirecting uppercase', function (done) {
request.get('///Google.com/')
.expect('Location', '/google.com/')
.expect('Cache-Control', testUtils.cacheRules.year)
.expect(301)
.end(doEnd(done));
});
it('AMP post should redirect without slash', function (done) {
request.get('/welcome/amp')
.expect('Location', '/welcome/amp/')
.expect('Cache-Control', testUtils.cacheRules.year)
.expect(301)
.end(doEnd(done));
});
it('AMP post should redirect uppercase', function (done) {
request.get('/Welcome/AMP/')
.expect('Location', '/welcome/amp/')
.expect('Cache-Control', testUtils.cacheRules.year)
.expect(301)
.end(doEnd(done));
});
});
});
describe('Test with added posts', function () {
before(addPosts);
describe('Static page', function () {
it('should respond with html', function (done) {
request.get('/static-page-test/')
.expect('Content-Type', /html/)
.expect('Cache-Control', testUtils.cacheRules.public)
.expect(200)
.end(function (err, res) {
const $ = cheerio.load(res.text);
should.not.exist(res.headers['x-cache-invalidate']);
should.not.exist(res.headers['X-CSRF-Token']);
should.not.exist(res.headers['set-cookie']);
should.exist(res.headers.date);
$('title').text().should.equal('This is a static page');
$('body.page-template').length.should.equal(1);
$('article.post').length.should.equal(1);
doEnd(done)(err, res);
});
});
it('should redirect without slash', function (done) {
request.get('/static-page-test')
.expect('Location', '/static-page-test/')
.expect('Cache-Control', testUtils.cacheRules.year)
.expect(301)
.end(doEnd(done));
});
describe('edit', function () {
it('should redirect without slash', function (done) {
request.get('/static-page-test/edit')
.expect('Location', '/static-page-test/edit/')
.expect('Cache-Control', testUtils.cacheRules.year)
.expect(301)
.end(doEnd(done));
});
it('should redirect to editor', function (done) {
request.get('/static-page-test/edit/')
.expect('Location', /ghost\/#\/editor\/\w+/)
.expect('Cache-Control', testUtils.cacheRules.public)
.expect(302)
.end(doEnd(done));
});
it('should 404 for non-edit parameter', function (done) {
request.get('/static-page-test/notedit/')
.expect('Cache-Control', testUtils.cacheRules.private)
.expect(404)
.expect(/Page not found/)
.end(doEnd(done));
});
});
describe('edit with admin redirects disabled', function () {
before(function (done) {
configUtils.set('admin:redirects', false);
ghost({forceStart: true})
.then(function () {
request = supertest.agent(config.get('url'));
addPosts(done);
});
});
after(function (done) {
configUtils.restore();
ghost({forceStart: true})
.then(function () {
request = supertest.agent(config.get('url'));
addPosts(done);
});
});
it('should redirect without slash', function (done) {
request.get('/static-page-test/edit')
.expect('Location', '/static-page-test/edit/')
.expect('Cache-Control', testUtils.cacheRules.year)
.expect(301)
.end(doEnd(done));
});
it('should not redirect to editor', function (done) {
request.get('/static-page-test/edit/')
.expect(404)
.expect('Cache-Control', testUtils.cacheRules.private)
.end(doEnd(done));
});
});
describe('amp', function () {
it('should 404 for amp parameter', function (done) {
// NOTE: only post pages are supported so the router doesn't have a way to distinguish if
// the request was done after AMP 'Page' or 'Post'
request.get('/static-page-test/amp/')
.expect('Cache-Control', testUtils.cacheRules.private)
.expect(404)
.expect(/Post not found/)
.end(doEnd(done));
});
});
});
describe('Post preview', function () {
it('should display draft posts accessed via uuid', function (done) {
request.get('/p/d52c42ae-2755-455c-80ec-70b2ec55c903/')
.expect('Content-Type', /html/)
.expect(200)
.end(function (err, res) {
if (err) {
return done(err);
}
const $ = cheerio.load(res.text);
should.not.exist(res.headers['x-cache-invalidate']);
should.not.exist(res.headers['X-CSRF-Token']);
should.not.exist(res.headers['set-cookie']);
should.exist(res.headers.date);
$('title').text().should.equal('Not finished yet');
// @TODO: use theme from fixtures and don't rely on content/themes/casper
// $('.content .post').length.should.equal(1);
// $('.poweredby').text().should.equal('Proudly published with Ghost');
// $('body.post-template').length.should.equal(1);
// $('article.post').length.should.equal(1);
done();
});
});
it('should redirect published posts to their live url', function (done) {
request.get('/p/2ac6b4f6-e1f3-406c-9247-c94a0496d39d/')
.expect(301)
.expect('Location', '/short-and-sweet/')
.expect('Cache-Control', testUtils.cacheRules.year)
.end(doEnd(done));
});
it('404s unknown uuids', function (done) {
request.get('/p/aac6b4f6-e1f3-406c-9247-c94a0496d39f/')
.expect(404)
.end(doEnd(done));
});
});
describe('Post with Ghost in the url', function () {
// All of Ghost's admin depends on the /ghost/ in the url to work properly
// Badly formed regexs can cause breakage if a post slug starts with the 5 letters ghost
it('should retrieve a blog post with ghost at the start of the url', function (done) {
request.get('/ghostly-kitchen-sink/')
.expect('Cache-Control', testUtils.cacheRules.public)
.expect(200)
.end(doEnd(done));
});
});
});
describe('Subdirectory (no slash)', function () {
let ghostServer;
before(function () {
configUtils.set('url', 'http://localhost/blog');
urlUtils.stubUrlUtilsFromConfig();
return ghost({forceStart: true, subdir: true})
.then(function (_ghostServer) {
ghostServer = _ghostServer;
request = supertest.agent(config.get('server:host') + ':' + config.get('server:port'));
});
});
after(function () {
configUtils.restore();
urlUtils.restore();
});
it('http://localhost should 404', function (done) {
request.get('/')
.expect(404)
.end(doEnd(done));
});
it('http://localhost/ should 404', function (done) {
request.get('/')
.expect(404)
.end(doEnd(done));
});
it('http://localhost/blog should 301 to http://localhost/blog/', function (done) {
request.get('/blog')
.expect(301)
.expect('Location', '/blog/')
.end(doEnd(done));
});
it('http://localhost/blog/ should 200', function (done) {
request.get('/blog/')
.expect(200)
.end(doEnd(done));
});
it('http://localhost/blog/welcome should 301 to http://localhost/blog/welcome/', function (done) {
request.get('/blog/welcome')
.expect(301)
.expect('Location', '/blog/welcome/')
.expect('Cache-Control', testUtils.cacheRules.year)
.end(doEnd(done));
});
it('http://localhost/blog/welcome/ should 200', function (done) {
request.get('/blog/welcome/')
.expect(200)
.end(doEnd(done));
});
it('/blog/tag/getting-started should 301 to /blog/tag/getting-started/', function (done) {
request.get('/blog/tag/getting-started')
.expect(301)
.expect('Location', '/blog/tag/getting-started/')
.expect('Cache-Control', testUtils.cacheRules.year)
.end(doEnd(done));
});
it('/blog/tag/getting-started/ should 200', function (done) {
request.get('/blog/tag/getting-started/')
.expect(200)
.end(doEnd(done));
});
it('/blog/welcome/amp/ should 200', function (done) {
request.get('/blog/welcome/amp/')
.expect(200)
.end(doEnd(done));
});
});
describe('Subdirectory (with slash)', function () {
let ghostServer;
before(function () {
configUtils.set('url', 'http://localhost/blog/');
urlUtils.stubUrlUtilsFromConfig();
return ghost({forceStart: true, subdir: true})
.then(function (_ghostServer) {
ghostServer = _ghostServer;
request = supertest.agent(config.get('server:host') + ':' + config.get('server:port'));
});
});
after(function () {
configUtils.restore();
urlUtils.restore();
});
it('http://localhost should 404', function (done) {
request.get('/')
.expect(404)
.end(doEnd(done));
});
it('http://localhost/ should 404', function (done) {
request.get('/')
.expect(404)
.end(doEnd(done));
});
it('/blog should 301 to /blog/', function (done) {
request.get('/blog')
.expect(301)
.expect('Location', '/blog/')
.end(doEnd(done));
});
it('/blog/ should 200', function (done) {
request.get('/blog/')
.expect(200)
.end(doEnd(done));
});
it('/blog/welcome should 301 to /blog/welcome/', function (done) {
request.get('/blog/welcome')
.expect(301)
.expect('Location', '/blog/welcome/')
.expect('Cache-Control', testUtils.cacheRules.year)
.end(doEnd(done));
});
it('/blog/welcome/ should 200', function (done) {
request.get('/blog/welcome/')
.expect(200)
.end(doEnd(done));
});
it('/blog/tag/getting-started should 301 to /blog/tag/getting-started/', function (done) {
request.get('/blog/tag/getting-started')
.expect(301)
.expect('Location', '/blog/tag/getting-started/')
.expect('Cache-Control', testUtils.cacheRules.year)
.end(doEnd(done));
});
it('/blog/tag/getting-started/ should 200', function (done) {
request.get('/blog/tag/getting-started/')
.expect(200)
.end(doEnd(done));
});
it('/blog/welcome/amp/ should 200', function (done) {
request.get('/blog/welcome/amp/')
.expect(200)
.end(doEnd(done));
});
it('should uncapitalise correctly with 301 to subdir', function (done) {
request.get('/blog/AAA/')
.expect('Location', '/blog/aaa/')
.expect('Cache-Control', testUtils.cacheRules.year)
.expect(301)
.end(doEnd(done));
});
});
// we'll use X-Forwarded-Proto: https to simulate an 'https://' request behind a proxy
describe('HTTPS', function () {
let ghostServer;
before(function () {
configUtils.set('url', 'http://localhost:2370/');
urlUtils.stubUrlUtilsFromConfig();
return ghost({forceStart: true})
.then(function (_ghostServer) {
ghostServer = _ghostServer;
request = supertest.agent(config.get('server:host') + ':' + config.get('server:port'));
});
});
after(function () {
configUtils.restore();
urlUtils.restore();
});
it('should set links to url over non-HTTPS', function (done) {
request.get('/')
.expect(200)
.expect(/<link rel="canonical" href="http:\/\/localhost:2370\/" \/\>/)
.expect(/<a href="http:\/\/localhost:2370">Ghost<\/a\>/)
.end(doEnd(done));
});
it('should set links over HTTPS besides canonical', function (done) {
request.get('/')
.set('X-Forwarded-Proto', 'https')
.expect(200)
.expect(/<link rel="canonical" href="http:\/\/localhost:2370\/" \/\>/)
.expect(/<a href="https:\/\/localhost:2370">Ghost<\/a\>/)
.end(doEnd(done));
});
});
// TODO: convert to unit tests
describe('Redirects (use redirects.json from test/utils/fixtures/data)', function () {
let ghostServer;
before(function () {
configUtils.set('url', 'http://localhost:2370/');
urlUtils.stubUrlUtilsFromConfig();
return ghost({forceStart: true})
.then(function (_ghostServer) {
ghostServer = _ghostServer;
request = supertest.agent(config.get('server:host') + ':' + config.get('server:port'));
});
});
after(function () {
configUtils.restore();
urlUtils.restore();
});
describe('1 case', function () {
it('with trailing slash', function (done) {
request.get('/post/10/a-nice-blog-post')
.expect(302)
.expect('Cache-Control', testUtils.cacheRules.public)
.end(function (err, res) {
res.headers.location.should.eql('/a-nice-blog-post');
doEnd(done)(err, res);
});
});
it('without trailing slash', function (done) {
request.get('/post/10/a-nice-blog-post/')
.expect(302)
.expect('Cache-Control', testUtils.cacheRules.public)
.end(function (err, res) {
res.headers.location.should.eql('/a-nice-blog-post');
doEnd(done)(err, res);
});
});
it('with query params', function (done) {
request.get('/topic?something=good')
.expect(302)
.expect('Cache-Control', testUtils.cacheRules.public)
.end(function (err, res) {
res.headers.location.should.eql('/?something=good');
doEnd(done)(err, res);
});
});
it('with query params', function (done) {
request.get('/post/10/a-nice-blog-post?a=b')
.expect(302)
.expect('Cache-Control', testUtils.cacheRules.public)
.end(function (err, res) {
res.headers.location.should.eql('/a-nice-blog-post?a=b');
doEnd(done)(err, res);
});
});
it('with case insensitive', function (done) {
request.get('/CaSe-InSeNsItIvE')
.expect(302)
.expect('Cache-Control', testUtils.cacheRules.public)
.end(function (err, res) {
res.headers.location.should.eql('/redirected-insensitive');
doEnd(done)(err, res);
});
});
it('with case sensitive', function (done) {
request.get('/Case-Sensitive')
.expect(302)
.expect('Cache-Control', testUtils.cacheRules.public)
.end(function (err, res) {
res.headers.location.should.eql('/redirected-sensitive');
doEnd(done)(err, res);
});
});
it('defaults to case sensitive', function (done) {
request.get('/Default-Sensitive')
.expect(302)
.expect('Cache-Control', testUtils.cacheRules.public)
.end(function (err, res) {
res.headers.location.should.eql('/redirected-default');
doEnd(done)(err, res);
});
});
it('should not redirect with case sensitive', function (done) {
request.get('/casE-sensitivE')
.end(function (err, res) {
res.headers.location.should.not.eql('/redirected-sensitive');
res.statusCode.should.not.eql(302);
doEnd(done)(err, res);
});
});
it('should not redirect with default case sensitive', function (done) {
request.get('/defaulT-sensitivE')
.end(function (err, res) {
res.headers.location.should.not.eql('/redirected-default');
res.statusCode.should.not.eql(302);
doEnd(done)(err, res);
});
});
});
describe('2 case', function () {
it('with trailing slash', function (done) {
request.get('/my-old-blog-post/')
.expect(301)
.expect('Cache-Control', testUtils.cacheRules.year)
.end(function (err, res) {
res.headers.location.should.eql('/revamped-url/');
doEnd(done)(err, res);
});
});
it('without trailing slash', function (done) {
request.get('/my-old-blog-post')
.expect(301)
.expect('Cache-Control', testUtils.cacheRules.year)
.end(function (err, res) {
res.headers.location.should.eql('/revamped-url/');
doEnd(done)(err, res);
});
});
});
describe('3 case', function () {
it('with trailing slash', function (done) {
request.get('/what/')
.expect(302)
.expect('Cache-Control', testUtils.cacheRules.public)
.end(function (err, res) {
res.headers.location.should.eql('/what-does-god-say');
doEnd(done)(err, res);
});
});
it('without trailing slash', function (done) {
request.get('/what')
.expect(302)
.expect('Cache-Control', testUtils.cacheRules.public)
.end(function (err, res) {
res.headers.location.should.eql('/what-does-god-say');
doEnd(done)(err, res);
});
});
});
describe('4 case', function () {
it('with trailing slash', function (done) {
request.get('/search/label/&&&/')
.expect(302)
.expect('Cache-Control', testUtils.cacheRules.public)
.end(function (err, res) {
res.headers.location.should.eql('/tag/&&&/');
doEnd(done)(err, res);
});
});
it('without trailing slash', function (done) {
request.get('/search/label/&&&/')
.expect(302)
.expect('Cache-Control', testUtils.cacheRules.public)
.end(function (err, res) {
res.headers.location.should.eql('/tag/&&&/');
doEnd(done)(err, res);
});
});
});
describe('5 case', function () {
it('with trailing slash', function (done) {
request.get('/topic/')
.expect(302)
.expect('Cache-Control', testUtils.cacheRules.public)
.end(function (err, res) {
res.headers.location.should.eql('/');
doEnd(done)(err, res);
});
});
it('without trailing slash', function (done) {
request.get('/topic')
.expect(302)
.expect('Cache-Control', testUtils.cacheRules.public)
.end(function (err, res) {
res.headers.location.should.eql('/');
doEnd(done)(err, res);
});
});
});
describe('6 case', function () {
it('with trailing slash', function (done) {
request.get('/resources/download/')
.expect(302)
.expect('Cache-Control', testUtils.cacheRules.public)
.end(function (err, res) {
res.headers.location.should.eql('/shubal-stearns');
doEnd(done)(err, res);
});
});
it('without trailing slash', function (done) {
request.get('/resources/download')
.expect(302)
.expect('Cache-Control', testUtils.cacheRules.public)
.end(function (err, res) {
res.headers.location.should.eql('/shubal-stearns');
doEnd(done)(err, res);
});
});
});
describe('7 case', function () {
it('with trailing slash', function (done) {
request.get('/2016/11/welcome.html')
.expect(302)
.expect('Cache-Control', testUtils.cacheRules.public)
.end(function (err, res) {
res.headers.location.should.eql('/welcome');
doEnd(done)(err, res);
});
});
});
describe('last case', function () {
it('default', function (done) {
request.get('/prefix/')
.expect(302)
.expect('Cache-Control', testUtils.cacheRules.public)
.end(function (err, res) {
res.headers.location.should.eql('/blog/');
doEnd(done)(err, res);
});
});
it('with a custom path', function (done) {
request.get('/prefix/expect-redirect')
.expect(302)
.expect('Cache-Control', testUtils.cacheRules.public)
.end(function (err, res) {
res.headers.location.should.eql('/blog/expect-redirect');
doEnd(done)(err, res);
});
});
});
describe('external url redirect', function () {
it('with trailing slash', function (done) {
request.get('/external-url/')
.expect(302)
.expect('Cache-Control', testUtils.cacheRules.public)
.end(function (err, res) {
res.headers.location.should.eql('https://ghost.org/');
doEnd(done)(err, res);
});
});
it('without trailing slash', function (done) {
request.get('/external-url')
.expect(302)
.expect('Cache-Control', testUtils.cacheRules.public)
.end(function (err, res) {
res.headers.location.should.eql('https://ghost.org/');
doEnd(done)(err, res);
});
});
it('with capturing group', function (done) {
request.get('/external-url/docs')
.expect(302)
.expect('Cache-Control', testUtils.cacheRules.public)
.end(function (err, res) {
res.headers.location.should.eql('https://ghost.org/docs');
doEnd(done)(err, res);
});
});
});
});
describe('Subdirectory redirects (use redirects.json from test/utils/fixtures/data)', function () {
var ghostServer;
before(function () {
configUtils.set('url', 'http://localhost:2370/blog/');
urlUtils.stubUrlUtilsFromConfig();
return ghost({forceStart: true, subdir: true})
.then(function (_ghostServer) {
ghostServer = _ghostServer;
request = supertest.agent(config.get('server:host') + ':' + config.get('server:port'));
});
});
after(function () {
configUtils.restore();
urlUtils.restore();
});
describe('internal url redirect', function () {
it('should include the subdirectory', function (done) {
request.get('/blog/my-old-blog-post/')
.expect(301)
.expect('Cache-Control', testUtils.cacheRules.year)
.end(function (err, res) {
res.headers.location.should.eql('/blog/revamped-url/');
doEnd(done)(err, res);
});
});
it('should work with regex "from" redirects', function (done) {
request.get('/blog/capture1/whatever')
.expect(302)
.expect('Cache-Control', testUtils.cacheRules.public)
.end(function (err, res) {
res.headers.location.should.eql('/blog/whatever');
doEnd(done)(err, res);
});
});
});
describe('external url redirect', function () {
it('should not include the subdirectory', function (done) {
request.get('/blog/external-url/docs')
.expect(302)
.expect('Cache-Control', testUtils.cacheRules.public)
.end(function (err, res) {
res.headers.location.should.eql('https://ghost.org/docs');
doEnd(done)(err, res);
});
});
});
});
});
|
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _createSvgIcon = _interopRequireDefault(require("./utils/createSvgIcon"));
var _jsxRuntime = require("react/jsx-runtime");
var _default = (0, _createSvgIcon.default)( /*#__PURE__*/(0, _jsxRuntime.jsx)("path", {
d: "M21 5H3c-1.1 0-2 .9-2 2v10c0 1.1.9 2 2 2h18c1.1 0 2-.9 2-2V7c0-1.1-.9-2-2-2zm-2 12H5V7h14v10zm-9-1h4c.55 0 1-.45 1-1v-3c0-.55-.45-1-1-1v-1c0-1.11-.9-2-2-2-1.11 0-2 .9-2 2v1c-.55 0-1 .45-1 1v3c0 .55.45 1 1 1zm.8-6c0-.66.54-1.2 1.2-1.2s1.2.54 1.2 1.2v1h-2.4v-1z"
}), 'ScreenLockLandscapeOutlined');
exports.default = _default; |
const BaseStep = require('../step');
const EntryProxy = require('../../entry-proxy');
const analyze = require('../../helpers/analytics/analytics')('gst');
// TODO pull below out to (variation) helper
function convertVariationalPath(variations, from, toVariationId) {
const toDir = variations.find(variation => variation.id === toVariationId).dir;
const pattern = new RegExp(`(${variations.map(variation => variation.dir).join('|')})`);
return from.replace(pattern, toDir);
}
function isNodeModule(id) {
return id.indexOf('node_modules') >= 0;
}
class GraphSourceTransform extends BaseStep {
/**
* @param {MendelRegistry} tool.registry
* @param {DepsManager} tool.depsResolver
*/
constructor({registry, cache}, options) {
super();
this._cache = cache;
this._registry = registry;
this._baseVariationId = options.baseConfig.id;
this._variations = options.variationConfig.variations;
this._gsts = [];
this._transforms = options.transforms;
options.types.forEach(type => {
const gsts = type.transforms.filter((transformId) => {
const transform = this._transforms.find(({id}) => id === transformId);
return transform && transform.mode === 'gst';
});
this._gsts = this._gsts.concat(gsts);
});
this._curGstIndex = 0;
this._processed = new Set();
this._virtual = new Set();
this.clear();
this._cache.on('entryRemoved', () => this.clear());
}
clear() {
this._curGstIndex = 0;
this._processed.clear();
this._virtual.forEach(entryId => this._registry.removeEntry(entryId));
this._virtual.clear();
this._canceled = true;
}
addTransform({id, source='', map='', deps={}}) {
// This will add source to the "rawSource" so it does not have to
// go through fs-reader (which should fail as it can be a virtual entry)
this._registry.addTransformedSource({id, source, deps, map});
}
getContext() {
return {
addVirtualEntry: ({source, id, map}) => {
this._virtual.add(id);
// TODO make sure virtual entries can be cleaned up with changes in source entry
this.addTransform({id, source, map});
},
removeEntry: (entry) => {
this._registry.removeEntry(entry.id);
},
};
}
gstDone(entry) {
this._processed.add(entry.id);
if (this._processed.size >= this._cache.size()) {
this._processed.clear();
if (++this._curGstIndex >= this._gsts.length) {
this._cache.entries().forEach(({id}) => {
this.emit('done', {entryId: id});
});
} else {
this._cache.entries().forEach(entry => this.performHelper(entry));
}
}
}
// this is conforming to the steps API
perform(entry) {
this._canceled = false;
if (this._gsts.length <= this._curGstIndex || isNodeModule(entry.id))
return this.gstDone(entry);
this.performHelper(entry);
}
explorePermutation(graph, onPermutation) {
const configVariations = new Set();
this._variations.forEach(variation => configVariations.add(variation.id));
// graph has array of arrays. First, make a pass and gather all variation info
const variations = new Set();
graph.forEach(nodes => {
nodes.forEach(node => {
variations.add(node.variation);
});
});
Array.from(variations.keys())
// Filter out undeclared (in config) variations
.filter(varKey => configVariations.has(varKey))
// We do not yet support multi-variation.
.forEach(variation => {
const chain = graph.map((nodes) => {
return nodes.find(node => node.variation === variation) ||
nodes.find(node => {
return node.variation === this._baseVariationId ||
node.variation === false;
});
});
// In case a new entry is introduced in variations without one
// in the base folder, the main file won't exist.
// In that case, we should not explore the permutation.
if (!chain[0]) return;
onPermutation(chain, variation);
});
}
performHelper(entry) {
const proxy = EntryProxy.getFromEntry(entry);
const currentGstConfig = this._transforms.find(({id}) => id === this._gsts[this._curGstIndex]);
const currentGst = require(currentGstConfig.plugin);
// If no GST is planned for this type, abort.
// If plugin doesn't want to deal with it, abort.
if (this._processed.has(entry.id) || this._virtual.has(entry.id) || !currentGst.predicate(proxy)) {
return this.gstDone(entry);
}
const graph = this._registry.getDependencyGraph(entry.normalizedId, (depEntry) => {
// In fs-change case, we can start over from the ist and
// "deps" can be wrong. We want the ist version in such case.
const dependecyMap = this._curGstIndex === 0 ?
depEntry.istDeps : depEntry.deps;
return Object.keys(dependecyMap).map(literal => {
// FIXME GST can be difference for main and browser.
// The difference can lead to different SHA if done poorly.
// Currently, we just apply main version but browser version
// may be needed. Address this.
return dependecyMap[literal].main;
});
});
this.explorePermutation(graph, (chain, variation) => {
const [main] = chain;
// We need to create proxy for limiting API surface for plugin writers.
const context = this.getContext();
const chainProxy = chain
.filter(Boolean)
.map(dep => EntryProxy.getFromEntry(dep));
const [proxiedMain] = chainProxy;
proxiedMain.filename = convertVariationalPath(
this._variations,
main.id,
variation
);
Promise.resolve()
.then(analyze.tic.bind(analyze, currentGstConfig.id))
.then(() => {
return currentGst.transform(
chainProxy,
currentGstConfig,
context
);
})
.then(analyze.toc.bind(analyze, currentGstConfig.id))
.then(result => {
if (this._canceled) return;
if (result && result.source) {
if (main.variation === variation) {
this.addTransform({
id: proxiedMain.filename,
source: result.source,
map: result.map,
deps: result.deps,
});
} else {
context.addVirtualEntry({
id: proxiedMain.filename,
originatingEntry: entry,
source: result.source,
deps: result.deps,
});
}
}
this.gstDone(main);
})
.catch(error => {
error.message = `Errored while transforming ${main.id}:\n` + error.message;
this.emit('error', {error, id: main.id});
});
});
}
}
module.exports = GraphSourceTransform;
|
'use strict';
// MODULES //
var tape = require( 'tape' );
var pow = require( 'math-power' );
var MAX_INT16 = require( './../lib' );
// TESTS //
tape( 'the main export is a number', function test( t ) {
t.ok( true, __filename );
t.equal( typeof MAX_INT16, 'number', 'main export is a number' );
t.end();
});
tape( 'the value equals 2**15 - 1', function test( t ) {
t.equal( MAX_INT16, pow(2,15) - 1, 'equals 2**15 - 1' );
t.end();
});
|
/*!
* iScroll v4.1.8 ~ Copyright (c) 2011 Matteo Spinelli, http://cubiq.org
* Released under MIT license, http://cubiq.org/license
*/
(function(){
var m = Math,
vendor = (/webkit/i).test(navigator.appVersion) ? 'webkit' :
(/firefox/i).test(navigator.userAgent) ? 'Moz' :
'opera' in window ? 'O' : '',
// Browser capabilities
has3d = 'WebKitCSSMatrix' in window && 'm11' in new WebKitCSSMatrix(),
hasTouch = 'ontouchstart' in window,
hasTransform = vendor + 'Transform' in document.documentElement.style,
isAndroid = (/android/gi).test(navigator.appVersion),
isIDevice = (/iphone|ipad/gi).test(navigator.appVersion),
isPlaybook = (/playbook/gi).test(navigator.appVersion),
hasTransitionEnd = isIDevice || isPlaybook,
nextFrame = (function() {
return window.requestAnimationFrame
|| window.webkitRequestAnimationFrame
|| window.mozRequestAnimationFrame
|| window.oRequestAnimationFrame
|| window.msRequestAnimationFrame
|| function(callback) { return setTimeout(callback, 1); }
})(),
cancelFrame = (function () {
return window.cancelRequestAnimationFrame
|| window.webkitCancelRequestAnimationFrame
|| window.mozCancelRequestAnimationFrame
|| window.oCancelRequestAnimationFrame
|| window.msCancelRequestAnimationFrame
|| clearTimeout
})(),
// Events
RESIZE_EV = 'onorientationchange' in window ? 'orientationchange' : 'resize',
START_EV = hasTouch ? 'touchstart' : 'mousedown',
MOVE_EV = hasTouch ? 'touchmove' : 'mousemove',
END_EV = hasTouch ? 'touchend' : 'mouseup',
CANCEL_EV = hasTouch ? 'touchcancel' : 'mouseup',
WHEEL_EV = vendor == 'Moz' ? 'DOMMouseScroll' : 'mousewheel',
// Helpers
trnOpen = 'translate' + (has3d ? '3d(' : '('),
trnClose = has3d ? ',0)' : ')',
// Constructor
iScroll = function (el, options) {
var that = this,
doc = document,
i;
that.wrapper = typeof el == 'object' ? el : doc.getElementById(el);
that.wrapper.style.overflow = 'hidden';
that.scroller = that.wrapper.children[0];
// Default options
that.options = {
hScroll: true,
vScroll: true,
bounce: true,
bounceLock: false,
momentum: true,
lockDirection: true,
useTransform: true,
useTransition: false,
topOffset: 0,
checkDOMChanges: false, // Experimental
// Scrollbar
hScrollbar: true,
vScrollbar: true,
fixedScrollbar: isAndroid,
hideScrollbar: isIDevice,
fadeScrollbar: isIDevice && has3d,
scrollbarClass: '',
// Zoom
zoom: false,
zoomMin: 1,
zoomMax: 4,
doubleTapZoom: 2,
wheelAction: 'scroll',
// Snap
snap: false,
snapThreshold: 1,
// Events
onRefresh: null,
onBeforeScrollStart: function (e) { e.preventDefault(); },
onScrollStart: null,
onBeforeScrollMove: null,
onScrollMove: null,
onBeforeScrollEnd: null,
onScrollEnd: null,
onTouchEnd: null,
onDestroy: null,
onZoomStart: null,
onZoom: null,
onZoomEnd: null,
// Added by Lissa
scrollOffsetLeft: 0,
scrollOffsetTop: 0
};
// User defined options
for (i in options) that.options[i] = options[i];
// Normalize options
that.options.useTransform = hasTransform ? that.options.useTransform : false;
that.options.hScrollbar = that.options.hScroll && that.options.hScrollbar;
that.options.vScrollbar = that.options.vScroll && that.options.vScrollbar;
that.options.zoom = that.options.useTransform && that.options.zoom;
that.options.useTransition = hasTransitionEnd && that.options.useTransition;
// Set some default styles
that.scroller.style[vendor + 'TransitionProperty'] = that.options.useTransform ? '-' + vendor.toLowerCase() + '-transform' : 'top left';
that.scroller.style[vendor + 'TransitionDuration'] = '0';
that.scroller.style[vendor + 'TransformOrigin'] = '0 0';
if (that.options.useTransition) that.scroller.style[vendor + 'TransitionTimingFunction'] = 'cubic-bezier(0.33,0.66,0.66,1)';
if (that.options.useTransform) that.scroller.style[vendor + 'Transform'] = trnOpen + '0,0' + trnClose;
else that.scroller.style.cssText += ';position:absolute;top:0;left:0';
if (that.options.useTransition) that.options.fixedScrollbar = true;
that.refresh();
that._bind(RESIZE_EV, window);
that._bind(START_EV);
if (!hasTouch) {
that._bind('mouseout', that.wrapper);
that._bind(WHEEL_EV);
}
if (that.options.checkDOMChanges) that.checkDOMTime = setInterval(function () {
that._checkDOMChanges();
}, 500);
};
// Prototype
iScroll.prototype = {
enabled: true,
x: 0,
y: 0,
steps: [],
scale: 1,
currPageX: 0, currPageY: 0,
pagesX: [], pagesY: [],
aniTime: null,
wheelZoomCount: 0,
handleEvent: function (e) {
var that = this;
switch(e.type) {
case START_EV:
if (!hasTouch && e.button !== 0) return;
that._start(e);
break;
case MOVE_EV: that._move(e); break;
case END_EV:
case CANCEL_EV: that._end(e); break;
case RESIZE_EV: that._resize(); break;
case WHEEL_EV: that._wheel(e); break;
case 'mouseout': that._mouseout(e); break;
case 'webkitTransitionEnd': that._transitionEnd(e); break;
}
},
_checkDOMChanges: function () {
if (this.moved || this.zoomed || this.animating ||
(this.scrollerW == this.scroller.offsetWidth * this.scale && this.scrollerH == this.scroller.offsetHeight * this.scale)) return;
this.refresh();
},
_scrollbar: function (dir) {
var that = this,
doc = document,
bar;
if (!that[dir + 'Scrollbar']) {
if (that[dir + 'ScrollbarWrapper']) {
if (hasTransform) that[dir + 'ScrollbarIndicator'].style[vendor + 'Transform'] = '';
that[dir + 'ScrollbarWrapper'].parentNode.removeChild(that[dir + 'ScrollbarWrapper']);
that[dir + 'ScrollbarWrapper'] = null;
that[dir + 'ScrollbarIndicator'] = null;
}
return;
}
if (!that[dir + 'ScrollbarWrapper']) {
// Create the scrollbar wrapper
bar = doc.createElement('div');
if (that.options.scrollbarClass) bar.className = that.options.scrollbarClass + dir.toUpperCase();
else bar.style.cssText = 'position:absolute;z-index:100;' + (dir == 'h' ? 'height:7px;bottom:1px;left:2px;right:' + (that.vScrollbar ? '7' : '2') + 'px' : 'width:7px;bottom:' + (that.hScrollbar ? '7' : '2') + 'px;top:2px;right:1px');
bar.style.cssText += ';pointer-events:none;-' + vendor + '-transition-property:opacity;-' + vendor + '-transition-duration:' + (that.options.fadeScrollbar ? '350ms' : '0') + ';overflow:hidden;opacity:' + (that.options.hideScrollbar ? '0' : '1');
that.wrapper.appendChild(bar);
that[dir + 'ScrollbarWrapper'] = bar;
// Create the scrollbar indicator
bar = doc.createElement('div');
if (!that.options.scrollbarClass) {
bar.style.cssText = 'position:absolute;z-index:100;background:rgba(0,0,0,0.5);border:1px solid rgba(255,255,255,0.9);-' + vendor + '-background-clip:padding-box;-' + vendor + '-box-sizing:border-box;' + (dir == 'h' ? 'height:100%' : 'width:100%') + ';-' + vendor + '-border-radius:3px;border-radius:3px';
}
bar.style.cssText += ';pointer-events:none;-' + vendor + '-transition-property:-' + vendor + '-transform;-' + vendor + '-transition-timing-function:cubic-bezier(0.33,0.66,0.66,1);-' + vendor + '-transition-duration:0;-' + vendor + '-transform:' + trnOpen + '0,0' + trnClose;
if (that.options.useTransition) bar.style.cssText += ';-' + vendor + '-transition-timing-function:cubic-bezier(0.33,0.66,0.66,1)';
that[dir + 'ScrollbarWrapper'].appendChild(bar);
that[dir + 'ScrollbarIndicator'] = bar;
}
if (dir == 'h') {
that.hScrollbarSize = that.hScrollbarWrapper.clientWidth;
that.hScrollbarIndicatorSize = m.max(m.round(that.hScrollbarSize * that.hScrollbarSize / that.scrollerW), 8);
that.hScrollbarIndicator.style.width = that.hScrollbarIndicatorSize + 'px';
that.hScrollbarMaxScroll = that.hScrollbarSize - that.hScrollbarIndicatorSize;
that.hScrollbarProp = that.hScrollbarMaxScroll / that.maxScrollX;
} else {
that.vScrollbarSize = that.vScrollbarWrapper.clientHeight;
that.vScrollbarIndicatorSize = m.max(m.round(that.vScrollbarSize * that.vScrollbarSize / that.scrollerH), 8);
that.vScrollbarIndicator.style.height = that.vScrollbarIndicatorSize + 'px';
that.vScrollbarMaxScroll = that.vScrollbarSize - that.vScrollbarIndicatorSize;
that.vScrollbarProp = that.vScrollbarMaxScroll / that.maxScrollY;
}
// Reset position
that._scrollbarPos(dir, true);
},
_resize: function () {
var that = this;
setTimeout(function () { that.refresh(); }, isAndroid ? 200 : 0);
},
_pos: function (x, y) {
x = this.hScroll ? x : 0;
y = this.vScroll ? y : 0;
if (this.options.useTransform) {
this.scroller.style[vendor + 'Transform'] = trnOpen + x + 'px,' + y + 'px' + trnClose + ' scale(' + this.scale + ')';
} else {
x = m.round(x);
y = m.round(y);
this.scroller.style.left = x + 'px';
this.scroller.style.top = y + 'px';
}
this.x = x;
this.y = y;
this._scrollbarPos('h');
this._scrollbarPos('v');
},
_scrollbarPos: function (dir, hidden) {
var that = this,
pos = dir == 'h' ? that.x : that.y,
size;
if (!that[dir + 'Scrollbar']) return;
pos = that[dir + 'ScrollbarProp'] * pos;
if (pos < 0) {
if (!that.options.fixedScrollbar) {
size = that[dir + 'ScrollbarIndicatorSize'] + m.round(pos * 3);
if (size < 8) size = 8;
that[dir + 'ScrollbarIndicator'].style[dir == 'h' ? 'width' : 'height'] = size + 'px';
}
pos = 0;
} else if (pos > that[dir + 'ScrollbarMaxScroll']) {
if (!that.options.fixedScrollbar) {
size = that[dir + 'ScrollbarIndicatorSize'] - m.round((pos - that[dir + 'ScrollbarMaxScroll']) * 3);
if (size < 8) size = 8;
that[dir + 'ScrollbarIndicator'].style[dir == 'h' ? 'width' : 'height'] = size + 'px';
pos = that[dir + 'ScrollbarMaxScroll'] + (that[dir + 'ScrollbarIndicatorSize'] - size);
} else {
pos = that[dir + 'ScrollbarMaxScroll'];
}
}
that[dir + 'ScrollbarWrapper'].style[vendor + 'TransitionDelay'] = '0';
that[dir + 'ScrollbarWrapper'].style.opacity = hidden && that.options.hideScrollbar ? '0' : '1';
that[dir + 'ScrollbarIndicator'].style[vendor + 'Transform'] = trnOpen + (dir == 'h' ? pos + 'px,0' : '0,' + pos + 'px') + trnClose;
},
_start: function (e) {
var that = this,
point = hasTouch ? e.touches[0] : e,
matrix, x, y,
c1, c2;
if (!that.enabled) return;
if (that.options.onBeforeScrollStart) that.options.onBeforeScrollStart.call(that, e);
if (that.options.useTransition || that.options.zoom) that._transitionTime(0);
that.moved = false;
that.animating = false;
that.zoomed = false;
that.distX = 0;
that.distY = 0;
that.absDistX = 0;
that.absDistY = 0;
that.dirX = 0;
that.dirY = 0;
// Gesture start
if (that.options.zoom && hasTouch && e.touches.length > 1) {
c1 = m.abs(e.touches[0].pageX-e.touches[1].pageX);
c2 = m.abs(e.touches[0].pageY-e.touches[1].pageY);
that.touchesDistStart = m.sqrt(c1 * c1 + c2 * c2);
that.originX = m.abs(e.touches[0].pageX + e.touches[1].pageX - that.wrapperOffsetLeft * 2) / 2 - that.x;
that.originY = m.abs(e.touches[0].pageY + e.touches[1].pageY - that.wrapperOffsetTop * 2) / 2 - that.y;
if (that.options.onZoomStart) that.options.onZoomStart.call(that, e);
}
if (that.options.momentum) {
if (that.options.useTransform) {
// Very lame general purpose alternative to CSSMatrix
matrix = getComputedStyle(that.scroller, null)[vendor + 'Transform'].replace(/[^0-9-.,]/g, '').split(',');
x = matrix[4] * 1;
y = matrix[5] * 1;
} else {
x = getComputedStyle(that.scroller, null).left.replace(/[^0-9-]/g, '') * 1;
y = getComputedStyle(that.scroller, null).top.replace(/[^0-9-]/g, '') * 1;
}
if (x != that.x || y != that.y) {
if (that.options.useTransition) that._unbind('webkitTransitionEnd');
else cancelFrame(that.aniTime);
that.steps = [];
that._pos(x, y);
}
}
that.absStartX = that.x; // Needed by snap threshold
that.absStartY = that.y;
that.startX = that.x;
that.startY = that.y;
that.pointX = point.pageX;
that.pointY = point.pageY;
that.startTime = e.timeStamp || (new Date()).getTime();
if (that.options.onScrollStart) that.options.onScrollStart.call(that, e);
that._bind(MOVE_EV);
that._bind(END_EV);
that._bind(CANCEL_EV);
},
_move: function (e) {
var that = this,
point = hasTouch ? e.touches[0] : e,
deltaX = point.pageX - that.pointX,
deltaY = point.pageY - that.pointY,
newX = that.x + deltaX,
newY = that.y + deltaY,
c1, c2, scale,
timestamp = e.timeStamp || (new Date()).getTime();
if (that.options.onBeforeScrollMove) that.options.onBeforeScrollMove.call(that, e);
// Zoom
if (that.options.zoom && hasTouch && e.touches.length > 1) {
c1 = m.abs(e.touches[0].pageX - e.touches[1].pageX);
c2 = m.abs(e.touches[0].pageY - e.touches[1].pageY);
that.touchesDist = m.sqrt(c1*c1+c2*c2);
that.zoomed = true;
scale = 1 / that.touchesDistStart * that.touchesDist * this.scale;
if (scale < that.options.zoomMin) scale = 0.5 * that.options.zoomMin * Math.pow(2.0, scale / that.options.zoomMin);
else if (scale > that.options.zoomMax) scale = 2.0 * that.options.zoomMax * Math.pow(0.5, that.options.zoomMax / scale);
that.lastScale = scale / this.scale;
newX = this.originX - this.originX * that.lastScale + this.x,
newY = this.originY - this.originY * that.lastScale + this.y;
this.scroller.style[vendor + 'Transform'] = trnOpen + newX + 'px,' + newY + 'px' + trnClose + ' scale(' + scale + ')';
if (that.options.onZoom) that.options.onZoom.call(that, e);
return;
}
that.pointX = point.pageX;
that.pointY = point.pageY;
// Slow down if outside of the boundaries
if (newX > 0 || newX < that.maxScrollX) {
newX = that.options.bounce ? that.x + (deltaX / 2) : newX >= 0 || that.maxScrollX >= 0 ? 0 : that.maxScrollX;
}
if (newY > that.minScrollY || newY < that.maxScrollY) {
newY = that.options.bounce ? that.y + (deltaY / 2) : newY >= that.minScrollY || that.maxScrollY >= 0 ? that.minScrollY : that.maxScrollY;
}
if (that.absDistX < 6 && that.absDistY < 6) {
that.distX += deltaX;
that.distY += deltaY;
that.absDistX = m.abs(that.distX);
that.absDistY = m.abs(that.distY);
return;
}
// Lock direction
if (that.options.lockDirection) {
if (that.absDistX > that.absDistY + 5) {
newY = that.y;
deltaY = 0;
} else if (that.absDistY > that.absDistX + 5) {
newX = that.x;
deltaX = 0;
}
}
that.moved = true;
that._pos(newX, newY);
that.dirX = deltaX > 0 ? -1 : deltaX < 0 ? 1 : 0;
that.dirY = deltaY > 0 ? -1 : deltaY < 0 ? 1 : 0;
if (timestamp - that.startTime > 300) {
that.startTime = timestamp;
that.startX = that.x;
that.startY = that.y;
}
if (that.options.onScrollMove) that.options.onScrollMove.call(that, e);
},
_end: function (e) {
if (hasTouch && e.touches.length != 0) return;
var that = this,
point = hasTouch ? e.changedTouches[0] : e,
target, ev,
momentumX = { dist:0, time:0 },
momentumY = { dist:0, time:0 },
duration = (e.timeStamp || (new Date()).getTime()) - that.startTime,
newPosX = that.x,
newPosY = that.y,
distX, distY,
newDuration,
snap,
scale;
that._unbind(MOVE_EV);
that._unbind(END_EV);
that._unbind(CANCEL_EV);
if (that.options.onBeforeScrollEnd) that.options.onBeforeScrollEnd.call(that, e);
if (that.zoomed) {
scale = that.scale * that.lastScale;
scale = Math.max(that.options.zoomMin, scale);
scale = Math.min(that.options.zoomMax, scale);
that.lastScale = scale / that.scale;
that.scale = scale;
that.x = that.originX - that.originX * that.lastScale + that.x;
that.y = that.originY - that.originY * that.lastScale + that.y;
that.scroller.style[vendor + 'TransitionDuration'] = '200ms';
that.scroller.style[vendor + 'Transform'] = trnOpen + that.x + 'px,' + that.y + 'px' + trnClose + ' scale(' + that.scale + ')';
that.zoomed = false;
that.refresh();
if (that.options.onZoomEnd) that.options.onZoomEnd.call(that, e);
return;
}
if (!that.moved) {
if (hasTouch) {
if (that.doubleTapTimer && that.options.zoom) {
// Double tapped
clearTimeout(that.doubleTapTimer);
that.doubleTapTimer = null;
if (that.options.onZoomStart) that.options.onZoomStart.call(that, e);
that.zoom(that.pointX, that.pointY, that.scale == 1 ? that.options.doubleTapZoom : 1);
if (that.options.onZoomEnd) {
setTimeout(function() {
that.options.onZoomEnd.call(that, e);
}, 200); // 200 is default zoom duration
}
} else {
that.doubleTapTimer = setTimeout(function () {
that.doubleTapTimer = null;
// Find the last touched element
target = point.target;
while (target.nodeType != 1) target = target.parentNode;
if (target.tagName != 'SELECT' && target.tagName != 'INPUT' && target.tagName != 'TEXTAREA') {
ev = document.createEvent('MouseEvents');
ev.initMouseEvent('click', true, true, e.view, 1,
point.screenX, point.screenY, point.clientX, point.clientY,
e.ctrlKey, e.altKey, e.shiftKey, e.metaKey,
0, null);
ev._fake = true;
target.dispatchEvent(ev);
}
}, that.options.zoom ? 250 : 0);
}
}
that._resetPos(200);
if (that.options.onTouchEnd) that.options.onTouchEnd.call(that, e);
return;
}
if (duration < 300 && that.options.momentum) {
momentumX = newPosX ? that._momentum(newPosX - that.startX, duration, -that.x, that.scrollerW - that.wrapperW + that.x, that.options.bounce ? that.wrapperW : 0) : momentumX;
momentumY = newPosY ? that._momentum(newPosY - that.startY, duration, -that.y, (that.maxScrollY < 0 ? that.scrollerH - that.wrapperH + that.y - that.minScrollY : 0), that.options.bounce ? that.wrapperH : 0) : momentumY;
newPosX = that.x + momentumX.dist;
newPosY = that.y + momentumY.dist;
if ((that.x > 0 && newPosX > 0) || (that.x < that.maxScrollX && newPosX < that.maxScrollX)) momentumX = { dist:0, time:0 };
if ((that.y > that.minScrollY && newPosY > that.minScrollY) || (that.y < that.maxScrollY && newPosY < that.maxScrollY)) momentumY = { dist:0, time:0 };
}
if (momentumX.dist || momentumY.dist) {
newDuration = m.max(m.max(momentumX.time, momentumY.time), 10);
// Do we need to snap?
if (that.options.snap) {
distX = newPosX - that.absStartX;
distY = newPosY - that.absStartY;
if (m.abs(distX) < that.options.snapThreshold && m.abs(distY) < that.options.snapThreshold) { that.scrollTo(that.absStartX, that.absStartY, 200); }
else {
snap = that._snap(newPosX, newPosY);
newPosX = snap.x;
newPosY = snap.y;
newDuration = m.max(snap.time, newDuration);
}
}
that.scrollTo(newPosX, newPosY, newDuration);
if (that.options.onTouchEnd) that.options.onTouchEnd.call(that, e);
return;
}
// Do we need to snap?
if (that.options.snap) {
distX = newPosX - that.absStartX;
distY = newPosY - that.absStartY;
if (m.abs(distX) < that.options.snapThreshold && m.abs(distY) < that.options.snapThreshold) that.scrollTo(that.absStartX, that.absStartY, 200);
else {
snap = that._snap(that.x, that.y);
if (snap.x != that.x || snap.y != that.y) that.scrollTo(snap.x, snap.y, snap.time);
}
if (that.options.onTouchEnd) that.options.onTouchEnd.call(that, e);
return;
}
that._resetPos(200);
if (that.options.onTouchEnd) that.options.onTouchEnd.call(that, e);
},
_resetPos: function (time) {
var that = this,
resetX = that.x >= 0 ? 0 : that.x < that.maxScrollX ? that.maxScrollX : that.x,
resetY = that.y >= that.minScrollY || that.maxScrollY > 0 ? that.minScrollY : that.y < that.maxScrollY ? that.maxScrollY : that.y;
if (resetX == that.x && resetY == that.y) {
if (that.moved) {
that.moved = false;
if (that.options.onScrollEnd) that.options.onScrollEnd.call(that); // Execute custom code on scroll end
}
/*
if (that.hScrollbar && that.options.hideScrollbar) {
if (vendor == 'webkit') that.hScrollbarWrapper.style[vendor + 'TransitionDelay'] = '300ms';
that.hScrollbarWrapper.style.opacity = '0';
}
if (that.vScrollbar && that.options.hideScrollbar) {
if (vendor == 'webkit') that.vScrollbarWrapper.style[vendor + 'TransitionDelay'] = '300ms';
that.vScrollbarWrapper.style.opacity = '0';
}
*/
return;
}
that.scrollTo(resetX, resetY, time || 0);
},
_wheel: function (e) {
var that = this,
wheelDeltaX, wheelDeltaY,
deltaX, deltaY,
deltaScale;
if ('wheelDeltaX' in e) {
wheelDeltaX = e.wheelDeltaX / 12;
wheelDeltaY = e.wheelDeltaY / 12;
} else if ('detail' in e) {
wheelDeltaX = wheelDeltaY = -e.detail * 3;
} else {
wheelDeltaX = wheelDeltaY = -e.wheelDelta;
}
if (that.options.wheelAction == 'zoom') {
deltaScale = that.scale * Math.pow(2, 1/3 * (wheelDeltaY ? wheelDeltaY / Math.abs(wheelDeltaY) : 0));
if (deltaScale < that.options.zoomMin) deltaScale = that.options.zoomMin;
if (deltaScale > that.options.zoomMax) deltaScale = that.options.zoomMax;
if (deltaScale != that.scale) {
if (!that.wheelZoomCount && that.options.onZoomStart) that.options.onZoomStart.call(that, e);
that.wheelZoomCount++;
that.zoom(e.pageX, e.pageY, deltaScale, 400);
setTimeout(function() {
that.wheelZoomCount--;
if (!that.wheelZoomCount && that.options.onZoomEnd) that.options.onZoomEnd.call(that, e);
}, 400);
}
return;
}
deltaX = that.x + wheelDeltaX;
deltaY = that.y + wheelDeltaY;
if (deltaX > 0) deltaX = 0;
else if (deltaX < that.maxScrollX) deltaX = that.maxScrollX;
if (deltaY > that.minScrollY) deltaY = that.minScrollY;
else if (deltaY < that.maxScrollY) deltaY = that.maxScrollY;
that.scrollTo(deltaX, deltaY, 0);
},
_mouseout: function (e) {
var t = e.relatedTarget;
if (!t) {
this._end(e);
return;
}
while (t = t.parentNode) if (t == this.wrapper) return;
this._end(e);
},
_transitionEnd: function (e) {
var that = this;
if (e.target != that.scroller) return;
that._unbind('webkitTransitionEnd');
that._startAni();
},
/**
*
* Utilities
*
*/
_startAni: function () {
var that = this,
startX = that.x, startY = that.y,
startTime = (new Date).getTime(),
step, easeOut;
if (that.animating) return;
if (!that.steps.length) {
that._resetPos(400);
return;
}
step = that.steps.shift();
if (step.x == startX && step.y == startY) step.time = 0;
that.animating = true;
that.moved = true;
if (that.options.useTransition) {
that._transitionTime(step.time);
that._pos(step.x, step.y);
that.animating = false;
if (step.time) that._bind('webkitTransitionEnd');
else that._resetPos(0);
return;
}
(function animate () {
var now = (new Date).getTime(),
newX, newY;
if (now >= startTime + step.time) {
that._pos(step.x, step.y);
that.animating = false;
if (that.options.onAnimationEnd) that.options.onAnimationEnd.call(that); // Execute custom code on animation end
that._startAni();
return;
}
now = (now - startTime) / step.time - 1;
easeOut = m.sqrt(1 - now * now);
newX = (step.x - startX) * easeOut + startX;
newY = (step.y - startY) * easeOut + startY;
that._pos(newX, newY);
if (that.animating) that.aniTime = nextFrame(animate);
})();
},
_transitionTime: function (time) {
time += 'ms';
this.scroller.style[vendor + 'TransitionDuration'] = time;
if (this.hScrollbar) this.hScrollbarIndicator.style[vendor + 'TransitionDuration'] = time;
if (this.vScrollbar) this.vScrollbarIndicator.style[vendor + 'TransitionDuration'] = time;
},
_momentum: function (dist, time, maxDistUpper, maxDistLower, size) {
var deceleration = 0.0006,
speed = m.abs(dist) / time,
newDist = (speed * speed) / (2 * deceleration),
newTime = 0, outsideDist = 0;
// Proportinally reduce speed if we are outside of the boundaries
if (dist > 0 && newDist > maxDistUpper) {
outsideDist = size / (6 / (newDist / speed * deceleration));
maxDistUpper = maxDistUpper + outsideDist;
speed = speed * maxDistUpper / newDist;
newDist = maxDistUpper;
} else if (dist < 0 && newDist > maxDistLower) {
outsideDist = size / (6 / (newDist / speed * deceleration));
maxDistLower = maxDistLower + outsideDist;
speed = speed * maxDistLower / newDist;
newDist = maxDistLower;
}
newDist = newDist * (dist < 0 ? -1 : 1);
newTime = speed / deceleration;
return { dist: newDist, time: m.round(newTime) };
},
_offset: function (el) {
var left = -el.offsetLeft,
top = -el.offsetTop;
while (el = el.offsetParent) {
left -= el.offsetLeft;
top -= el.offsetTop;
}
if (el != this.wrapper) {
left *= this.scale;
top *= this.scale;
}
return { left: left, top: top };
},
_snap: function (x, y) {
var that = this,
i, l,
page, time,
sizeX, sizeY;
// Check page X
page = that.pagesX.length - 1;
for (i=0, l=that.pagesX.length; i<l; i++) {
if (x >= that.pagesX[i]) {
page = i;
break;
}
}
if (page == that.currPageX && page > 0 && that.dirX < 0) page--;
x = that.pagesX[page];
sizeX = m.abs(x - that.pagesX[that.currPageX]);
sizeX = sizeX ? m.abs(that.x - x) / sizeX * 500 : 0;
that.currPageX = page;
// Check page Y
page = that.pagesY.length-1;
for (i=0; i<page; i++) {
if (y >= that.pagesY[i]) {
page = i;
break;
}
}
if (page == that.currPageY && page > 0 && that.dirY < 0) page--;
y = that.pagesY[page];
sizeY = m.abs(y - that.pagesY[that.currPageY]);
sizeY = sizeY ? m.abs(that.y - y) / sizeY * 500 : 0;
that.currPageY = page;
// Snap with constant speed (proportional duration)
time = m.round(m.max(sizeX, sizeY)) || 200;
return { x: x, y: y, time: time };
},
_bind: function (type, el, bubble) {
(el || this.scroller).addEventListener(type, this, !!bubble);
},
_unbind: function (type, el, bubble) {
(el || this.scroller).removeEventListener(type, this, !!bubble);
},
/**
*
* Public methods
*
*/
destroy: function () {
var that = this;
that.scroller.style[vendor + 'Transform'] = '';
// Remove the scrollbars
that.hScrollbar = false;
that.vScrollbar = false;
that._scrollbar('h');
that._scrollbar('v');
// Remove the event listeners
that._unbind(RESIZE_EV, window);
that._unbind(START_EV);
that._unbind(MOVE_EV);
that._unbind(END_EV);
that._unbind(CANCEL_EV);
if (that.options.hasTouch) {
that._unbind('mouseout', that.wrapper);
that._unbind(WHEEL_EV);
}
if (that.options.useTransition) that._unbind('webkitTransitionEnd');
if (that.options.checkDOMChanges) clearInterval(that.checkDOMTime);
if (that.options.onDestroy) that.options.onDestroy.call(that);
},
refresh: function () {
var that = this,
offset,
i, l,
els,
pos = 0,
page = 0;
if (that.scale < that.options.zoomMin) that.scale = that.options.zoomMin;
that.wrapperW = that.wrapper.clientWidth || 1;
that.wrapperH = that.wrapper.clientHeight || 1;
that.minScrollY = -that.options.topOffset || 0;
that.scrollerW = m.round(that.scroller.offsetWidth * that.scale);
that.scrollerH = m.round((that.scroller.offsetHeight + that.minScrollY) * that.scale);
that.maxScrollX = that.wrapperW - that.scrollerW;
that.maxScrollY = that.wrapperH - that.scrollerH + that.minScrollY;
that.dirX = 0;
that.dirY = 0;
if (that.options.onRefresh) that.options.onRefresh.call(that);
that.hScroll = that.options.hScroll && that.maxScrollX < 0;
that.vScroll = that.options.vScroll && (!that.options.bounceLock && !that.hScroll || that.scrollerH > that.wrapperH);
that.hScrollbar = that.hScroll && that.options.hScrollbar;
that.vScrollbar = that.vScroll && that.options.vScrollbar && that.scrollerH > that.wrapperH;
offset = that._offset(that.wrapper);
that.wrapperOffsetLeft = -offset.left;
that.wrapperOffsetTop = -offset.top;
// Prepare snap
if (typeof that.options.snap == 'string') {
that.pagesX = [];
that.pagesY = [];
els = that.scroller.querySelectorAll(that.options.snap);
for (i=0, l=els.length; i<l; i++) {
pos = that._offset(els[i]);
pos.left += that.wrapperOffsetLeft;
pos.top += that.wrapperOffsetTop;
that.pagesX[i] = pos.left < that.maxScrollX ? that.maxScrollX : pos.left * that.scale;
that.pagesY[i] = pos.top < that.maxScrollY ? that.maxScrollY : pos.top * that.scale;
}
} else if (that.options.snap) {
that.pagesX = [];
while (pos >= that.maxScrollX) {
that.pagesX[page] = pos;
pos = pos - that.wrapperW;
page++;
}
if (that.maxScrollX%that.wrapperW) that.pagesX[that.pagesX.length] = that.maxScrollX - that.pagesX[that.pagesX.length-1] + that.pagesX[that.pagesX.length-1];
pos = 0;
page = 0;
that.pagesY = [];
while (pos >= that.maxScrollY) {
that.pagesY[page] = pos;
pos = pos - that.wrapperH;
page++;
}
if (that.maxScrollY%that.wrapperH) that.pagesY[that.pagesY.length] = that.maxScrollY - that.pagesY[that.pagesY.length-1] + that.pagesY[that.pagesY.length-1];
}
// Prepare the scrollbars
that._scrollbar('h');
that._scrollbar('v');
if (!that.zoomed) {
that.scroller.style[vendor + 'TransitionDuration'] = '0';
that._resetPos(200);
}
},
scrollTo: function (x, y, time, relative) {
var that = this,
step = x,
i, l;
that.stop();
if (!step.length) step = [{ x: x, y: y, time: time, relative: relative }];
for (i=0, l=step.length; i<l; i++) {
if (step[i].relative) { step[i].x = that.x - step[i].x; step[i].y = that.y - step[i].y; }
that.steps.push({ x: step[i].x, y: step[i].y, time: step[i].time || 0 });
}
that._startAni();
},
scrollToElement: function (el, time) {
var that = this, pos;
el = el.nodeType ? el : that.scroller.querySelector(el);
if (!el) return;
pos = that._offset(el);
pos.left += that.wrapperOffsetLeft;
pos.top += that.wrapperOffsetTop;
pos.left = pos.left > 0 ? 0 : pos.left < that.maxScrollX ? that.maxScrollX : pos.left;
pos.top = pos.top > that.minScrollY ? that.minScrollY : pos.top < that.maxScrollY ? that.maxScrollY : pos.top;
time = time === undefined ? m.max(m.abs(pos.left)*2, m.abs(pos.top)*2) : time;
// Added for scroll offset by Lissa
pos.left -= that.options.scrollOffsetLeft;
pos.top -= that.options.scrollOffsetTop;
that.scrollTo(pos.left, pos.top, time);
},
scrollToPage: function (pageX, pageY, time) {
var that = this, x, y;
if (that.options.snap) {
pageX = pageX == 'next' ? that.currPageX+1 : pageX == 'prev' ? that.currPageX-1 : pageX;
pageY = pageY == 'next' ? that.currPageY+1 : pageY == 'prev' ? that.currPageY-1 : pageY;
pageX = pageX < 0 ? 0 : pageX > that.pagesX.length-1 ? that.pagesX.length-1 : pageX;
pageY = pageY < 0 ? 0 : pageY > that.pagesY.length-1 ? that.pagesY.length-1 : pageY;
that.currPageX = pageX;
that.currPageY = pageY;
x = that.pagesX[pageX];
y = that.pagesY[pageY];
} else {
x = -that.wrapperW * pageX;
y = -that.wrapperH * pageY;
if (x < that.maxScrollX) x = that.maxScrollX;
if (y < that.maxScrollY) y = that.maxScrollY;
}
that.scrollTo(x, y, time || 400);
},
disable: function () {
this.stop();
this._resetPos(0);
this.enabled = false;
// If disabled after touchstart we make sure that there are no left over events
this._unbind(MOVE_EV);
this._unbind(END_EV);
this._unbind(CANCEL_EV);
},
enable: function () {
this.enabled = true;
},
stop: function () {
if (this.options.useTransition) this._unbind('webkitTransitionEnd');
else cancelFrame(this.aniTime);
this.steps = [];
this.moved = false;
this.animating = false;
},
zoom: function (x, y, scale, time) {
var that = this,
relScale = scale / that.scale;
if (!that.options.useTransform) return;
that.zoomed = true;
time = time === undefined ? 200 : time;
x = x - that.wrapperOffsetLeft - that.x;
y = y - that.wrapperOffsetTop - that.y;
that.x = x - x * relScale + that.x;
that.y = y - y * relScale + that.y;
that.scale = scale;
that.refresh();
that.x = that.x > 0 ? 0 : that.x < that.maxScrollX ? that.maxScrollX : that.x;
that.y = that.y > that.minScrollY ? that.minScrollY : that.y < that.maxScrollY ? that.maxScrollY : that.y;
that.scroller.style[vendor + 'TransitionDuration'] = time + 'ms';
that.scroller.style[vendor + 'Transform'] = trnOpen + that.x + 'px,' + that.y + 'px' + trnClose + ' scale(' + scale + ')';
that.zoomed = false;
},
isReady: function () {
return !this.moved && !this.zoomed && !this.animating;
}
};
if (typeof exports !== 'undefined') exports.iScroll = iScroll;
else window.iScroll = iScroll;
})();
|
var path = require('path'),
fs = require('fs'),
Source = require(hexo.lib_dir + '/core/source'),
config_dir = path.dirname(hexo.configfile),
config = hexo.config;
function testver(){
var ver = hexo.env.version.split('.');
var test = true;
if (ver[0] < 2) test = false;
else if (ver[0] == 2 && ver[1] < 5) test = false;
if (test) return;
var hexo_curver = 'hexo'.red + (' V' + hexo.env.version).green;
var theme_curver = 'chenall'.green + ' V2.2'.red;
var error = 'Current version of ' + hexo_curver + ' Does not apply to the theme ' + theme_curver;
error += ',Please use theme ' + 'chenall '.green + 'V1.0'.red + ' or upgrade to' + ' hexo 2.5.0 '.green + 'or latest.';
error +='\n\n\t当前版本 ' + hexo_curver + ' 不适用于主题 ' + theme_curver + '\n请使用' + 'chenall '.green + 'V1.0'.red + ' 版主题或升级hexo到' + ' 2.5.0 '.green + '以上';
error +='\n\nchenall V1.0:\n' + 'svn co https://github.com/chenall/hexo-theme-chenall/tags/V1.0 themes/chenall'.yellow;
error +='\n\nhexo latest(升级):\n\t' + 'npm update hexo'.yellow;
error +='\n\nhexo V2.5.X(安装指定版本):\n\t' + 'npm install [email protected] -g'.yellow;
error += '\n\n\t有什么疑问可以联系我 http://chenall.net';
hexo.log.e(error);
process.exit(1);
}
function checkenv(){
var store = hexo.extend.renderer.store;
var error = '';
if (!store['ejs']) error += '\tnpm install hexo-renderer-ejs\n';
if (!store['md']) error += '\tnpm install hexo-renderer-marked\n';
if (!store['styl']) error +='\tnpm install hexo-renderer-stylus\n';
if (error){
hexo.log.e('\t主题使用环境检测失败\n\n\t缺少必要插件,请使用以下命令安装:\n\n',error);
process.exit(1);
}
}
testver();
checkenv();
if (hexo.hasOwnProperty('env') && hexo.env.hasOwnProperty('debug')) hexo.debug = hexo.env.debug;
hexo.__dump = function(obj){
var cache = [];
return JSON.stringify(obj,function(key, value){
if (typeof value === 'object' && value !== null) {
if (cache.indexOf(value) !== -1) {
// Circular reference found, discard key
return;
}
cache.push(value);
}
return value;
});
}
if (config.CustomDir && typeof(config.CustomDir) == 'object'){
var joinPath = function(){
var str = path.join.apply(this, arguments);
if (str[str.length - 1] !== path.sep) str += path.sep;
return str;
};
var custom = config.CustomDir;
['public_dir','source_dir','scaffold_dir'].forEach(function(p){
if (!custom[p]) return;
if (custom[p] == 'auto'){
hexo.constant(p,joinPath(config_dir,p));
} else {
var test = custom[p].match(/^:config(.*)$/);
if (test){
hexo.constant(p,joinPath(config_dir,test[1]));
} else {
hexo.constant(p,joinPath(config_dir,custom[p]));
}
}
})
hexo.source = new Source();
}
var load_default_usercfg = function(){
var cfg = global.usercfg = {
ajax_widgets: true,
updated: true,
cached_widgets:true
};
cfg.twbs_style = ['primary','success','info','warning','danger'];
var user_cfg = hexo.source_dir + '_' + hexo.config.theme + '.yml';
if (!fs.existsSync(user_cfg)){
user_cfg = hexo.theme_dir + '_config.yml';
cfg.themeconfig = hexo.render.renderSync({path: user_cfg});
hexo.log.i("Theme config file: " + user_cfg.green);
}
cfg.twbs_sty = function(i){return cfg.twbs_style[i%4];}
hexo.log.d('Using theme ' + 'chenall V2.2'.green);
}
hexo.on('ready',load_default_usercfg);
|
const request = require('request-promise');
const oauth = require('./config').auth;
const rootUrl = 'https://api.twitter.com/1.1';
let allItems = [];
/* API methods */
const API = {
/**
* Search for tweets
* @param options {Object} Options object containing:
* - text (Required) : String
* - count (optional) : Number
* - result_type (optional) : String
* - geocode (optional) : String (lat long radius_in_miles)
* - since_id (optional) : Number - start search from this ID
* - max_id (optional) : Number - end search on this ID
*/
search: (options) => {
return new Promise((resolve, reject) => {
const {text, count = 100, result_type = 'popular', since_id = 0, max_id, geocode} = options;
let params =
`?q=${encodeURIComponent(options.text)}` +
`&count=${count}` +
`&result_type=${result_type}` +
`&since_id=${since_id}`;
if (max_id) {
params += `&max_id=${max_id}`;
}
if (geocode) {
params += `&geocode=${encodeURIComponent(geocode)}`;
}
allItems = [];
API.searchByStringParam(params).then((items) => resolve(items)).catch((err) => reject(err));
});
},
/**
* Search w/ params
* @param stringParams {String} Params as string
*/
searchByStringParam: (stringParams) =>
new Promise((resolve, reject) => {
const searchCallback = (res) => {
const result = JSON.parse(res);
if (result && result.statuses) {
result.statuses.forEach(item => allItems.push(item));
console.log('[Search] So far we have', allItems.length, 'items');
// If we have the next_results, search again for the rest (sort of a pagination)
const nextRes = result.search_metadata.next_results;
if (nextRes) {
API.searchByStringParam(nextRes).then((items) => resolve(items));
} else {
resolve(allItems);
}
} else {
resolve(null);
}
};
request.get({url: `${rootUrl}/search/tweets.json${stringParams}`, oauth})
.then(res => searchCallback(res))
.catch(err => reject(err));
})
,
/**
* Retweet a tweet
* @param tweetId {String} identifier for the tweet
*/
retweet: (tweetId) =>
new Promise((resolve, reject) =>
request.post({url: `${rootUrl}/statuses/retweet/${tweetId}.json`, oauth})
.then((res) => resolve(res))
.catch((err) => reject(err))
)
,
/**
* Like (aka favorite) a tweet
* @param tweetId {String} identifier for the tweet
*/
like: (tweetId) =>
new Promise((resolve, reject) =>
request.post({url: `${rootUrl}/favorites/create.json?id=${tweetId}`, oauth})
.then((res) => resolve(res))
.catch((err) => reject(err))
)
,
/**
* Follow a user by username
* @param userId {String} identifier for the user
*/
follow: (userId) =>
new Promise((resolve, reject) =>
request.post({url: `${rootUrl}/friendships/create.json?user_id=${userId}`, oauth})
.then((res) => resolve(res))
.catch((err) => reject(err))
)
,
/**
* Follow a user by username
* @param userName {String} username identifier for the user
*/
followByUsername: (userName) =>
new Promise((resolve, reject) =>
request.post({url: `${rootUrl}/friendships/create.json?screen_name=${userName}`, oauth})
.then((res) => resolve(res))
.catch((err) => reject(err))
)
,
/**
* Block a user
* @param userId {String} ID of the user to block
*/
blockUser: (userId) =>
new Promise((resolve, reject) =>
request.post({url: `${rootUrl}/blocks/create.json?user_id=${userId}`, oauth})
.then((res) => resolve(res))
.catch((err) => reject(err))
)
,
/** Get list of blocked users for the current user */
getBlockedUsers: () =>
new Promise((resolve, reject) =>
request.get({url: `${rootUrl}/blocks/list.json`, oauth})
.then((res) => resolve(JSON.parse(res).users.map((user) => user.id)))
.catch((err) => reject(err))
)
,
/**
* Get a user's tweets
* @param userId {String} identifier for the user
* @param count {Number} max tweets to retrieve
*/
getTweetsForUser: (userId, count) =>
new Promise((resolve, reject) =>
request.get({url: `${rootUrl}/statuses/user_timeline.json?user_id=${userId}&count=${count}`, oauth})
.then((response) => resolve(response))
.catch((err) => reject(err))
)
,
/**
* Delete a tweet
* @param tweetId {String} identifier for the tweet
*/
deleteTweet: (tweetId) =>
new Promise((resolve, reject) =>
request.post({url: `${rootUrl}/statuses/destroy/${tweetId}.json`, oauth})
.then(() => {
console.log('Deleted tweet', tweetId);
resolve();
})
.catch((err) => reject(err))
)
,
/**
* Reply to a tweet
* (The Reply on Twitter is basically a Status Update containing @username, where username is author of the original tweet)
* @param tweet {Object} The full Tweet we want to reply to
*/
replyToTweet: (tweet) =>
new Promise((resolve, reject) => {
try {
const text = encodeURIComponent(`@${tweet.user.screen_name} `);
request.post({
url: `${rootUrl}/statuses/update.json?status=${text}&in_reply_to_status_id=${tweet.id}`,
oauth
})
.then(() => resolve())
.catch(err => reject(err))
} catch (err) {
reject(err);
}
})
};
module.exports = API;
|
//@flow
const {foo, Bar, baz, qux} = require('./jsdoc-exports');
const {
DefaultedStringEnum,
InitializedStringEnum,
NumberEnum,
BooleanEnum,
SymbolEnum,
} = require('./jsdoc-objects');
/** a JSDoc in the same file */
function x() {}
( );
// ^
|
ace.define("ace/mode/tex_highlight_rules",["require","exports","module","ace/lib/oop","ace/lib/lang","ace/mode/text_highlight_rules"], function(require, exports, module) {
"use strict";
var oop = require("../lib/oop");
var lang = require("../lib/lang");
var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules;
var TexHighlightRules = function(textClass) {
if (!textClass)
textClass = "text";
this.$rules = {
"start" : [
{
token : "comment",
regex : "%.*$"
}, {
token : textClass, // non-command
regex : "\\\\[$&%#\\{\\}]"
}, {
token : "keyword", // command
regex : "\\\\(?:documentclass|usepackage|newcounter|setcounter|addtocounter|value|arabic|stepcounter|newenvironment|renewenvironment|ref|vref|eqref|pageref|label|cite[a-zA-Z]*|tag|begin|end|bibitem)\\b",
next : "nospell"
}, {
token : "keyword", // command
regex : "\\\\(?:[a-zA-Z0-9]+|[^a-zA-Z0-9])"
}, {
token : "paren.keyword.operator",
regex : "[[({]"
}, {
token : "paren.keyword.operator",
regex : "[\\])}]"
}, {
token : textClass,
regex : "\\s+"
}
],
"nospell" : [
{
token : "comment",
regex : "%.*$",
next : "start"
}, {
token : "nospell." + textClass, // non-command
regex : "\\\\[$&%#\\{\\}]"
}, {
token : "keyword", // command
regex : "\\\\(?:documentclass|usepackage|newcounter|setcounter|addtocounter|value|arabic|stepcounter|newenvironment|renewenvironment|ref|vref|eqref|pageref|label|cite[a-zA-Z]*|tag|begin|end|bibitem)\\b"
}, {
token : "keyword", // command
regex : "\\\\(?:[a-zA-Z0-9]+|[^a-zA-Z0-9])",
next : "start"
}, {
token : "paren.keyword.operator",
regex : "[[({]"
}, {
token : "paren.keyword.operator",
regex : "[\\])]"
}, {
token : "paren.keyword.operator",
regex : "}",
next : "start"
}, {
token : "nospell." + textClass,
regex : "\\s+"
}, {
token : "nospell." + textClass,
regex : "\\w+"
}
]
};
};
oop.inherits(TexHighlightRules, TextHighlightRules);
exports.TexHighlightRules = TexHighlightRules;
});
ace.define("ace/mode/matching_brace_outdent",["require","exports","module","ace/range"], function(require, exports, module) {
"use strict";
var Range = require("../range").Range;
var MatchingBraceOutdent = function() {};
(function() {
this.checkOutdent = function(line, input) {
if (! /^\s+$/.test(line))
return false;
return /^\s*\}/.test(input);
};
this.autoOutdent = function(doc, row) {
var line = doc.getLine(row);
var match = line.match(/^(\s*\})/);
if (!match) return 0;
var column = match[1].length;
var openBracePos = doc.findMatchingBracket({row: row, column: column});
if (!openBracePos || openBracePos.row == row) return 0;
var indent = this.$getIndent(doc.getLine(openBracePos.row));
doc.replace(new Range(row, 0, row, column-1), indent);
};
this.$getIndent = function(line) {
return line.match(/^\s*/)[0];
};
}).call(MatchingBraceOutdent.prototype);
exports.MatchingBraceOutdent = MatchingBraceOutdent;
});
ace.define("ace/mode/tex",["require","exports","module","ace/lib/oop","ace/mode/text","ace/mode/text_highlight_rules","ace/mode/tex_highlight_rules","ace/mode/matching_brace_outdent"], function(require, exports, module) {
"use strict";
var oop = require("../lib/oop");
var TextMode = require("./text").Mode;
var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules;
var TexHighlightRules = require("./tex_highlight_rules").TexHighlightRules;
var MatchingBraceOutdent = require("./matching_brace_outdent").MatchingBraceOutdent;
var Mode = function(suppressHighlighting) {
if (suppressHighlighting)
this.HighlightRules = TextHighlightRules;
else
this.HighlightRules = TexHighlightRules;
this.$outdent = new MatchingBraceOutdent();
this.$behaviour = this.$defaultBehaviour;
};
oop.inherits(Mode, TextMode);
(function() {
this.lineCommentStart = "%";
this.getNextLineIndent = function(state, line, tab) {
return this.$getIndent(line);
};
this.allowAutoInsert = function() {
return false;
};
this.$id = "ace/mode/tex";
}).call(Mode.prototype);
exports.Mode = Mode;
});
(function() {
ace.require(["ace/mode/tex"], function(m) {
if (typeof module == "object" && typeof exports == "object" && module) {
module.exports = m;
}
});
})();
|
(function(){
'use strict';
angular
.module('app')
.factory('ceUsers', ceUsers);
ceUsers.$inject = ['$resource'];
function ceUsers ($resource) {
console.log('ok');
return $resource('https://mysterious-eyrie-9135.herokuapp.com/users/:username',
{username: '@username'},
{'update': { method: 'PUT'}}
);
}
})();
|
'use strict';
import gulp from 'gulp';
import gutil from 'gulp-util';
import uglify from 'gulp-uglify';
import stylus from 'gulp-stylus';
import watch from 'gulp-watch';
import plumber from 'gulp-plumber';
import cleanCss from 'gulp-clean-css';
import imagemin from 'gulp-imagemin';
import concat from 'gulp-concat';
import babel from 'gulp-babel';
// Minificação dos arquivos .js
gulp.task('minjs', () => {
return gulp
// Define a origem dos arquivos .js
.src(['src/js/**/*.js'])
// Prevençãao de erros
.pipe(plumber())
// Suporte para o padrão ES6
.pipe(babel({
presets: ['es2015']
}))
// Realiza minificação
.pipe(uglify())
// Altera a extenção do arquivo
.pipe(concat('app.min.js'))
// Salva os arquivos minificados na pasta de destino
.pipe(gulp.dest('dist/js'));
});
gulp.task('stylus', () => {
return gulp
// Define a origem dos arquivos .scss
.src('src/stylus/**/*.styl')
// Prevençãao de erros
.pipe(plumber())
// Realiza o pré-processamento para css
.pipe(stylus())
// Realiza a minificação do css
.pipe(cleanCss())
// Altera a extenção do arquivo
.pipe(concat('style.min.css'))
// Salva os arquivos processados na pasta de destino
.pipe(gulp.dest('dist/css'));
});
gulp.task('images', () =>
gulp.src('src/assets/*')
.pipe(imagemin())
.pipe(gulp.dest('dist/assets'))
);
gulp.task('watch', function() {
gulp.start('default')
gulp.watch('src/js/**/*.js', ['minjs'])
gulp.watch('src/stylus/**/*.styl', ['stylus'])
gulp.watch('src/assets/*', ['images'])
});
gulp.task('default', ['minjs', 'stylus', 'images']);
|
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _createSvgIcon = _interopRequireDefault(require("./utils/createSvgIcon"));
var _jsxRuntime = require("react/jsx-runtime");
var _default = (0, _createSvgIcon.default)( /*#__PURE__*/(0, _jsxRuntime.jsx)("path", {
d: "M21 17h-1v-6c0-1.1-.9-2-2-2H7v-.74c0-.46-.56-.7-.89-.37L4.37 9.63c-.2.2-.2.53 0 .74l1.74 1.74c.33.33.89.1.89-.37V11h4v3H5c-.55 0-1 .45-1 1v2c0 1.1.9 2 2 2h2c0 1.66 1.34 3 3 3s3-1.34 3-3h7c.55 0 1-.45 1-1s-.45-1-1-1zm-10 3c-.55 0-1-.45-1-1s.45-1 1-1 1 .45 1 1-.45 1-1 1zm7-6h-4v-3h3c.55 0 1 .45 1 1v2zm-8-8h7v.74c0 .46.56.7.89.37l1.74-1.74c.2-.2.2-.53 0-.74l-1.74-1.74c-.33-.33-.89-.1-.89.37V4h-7c-.55 0-1 .45-1 1s.45 1 1 1z"
}), 'RvHookupRounded');
exports.default = _default; |
import { set } from 'ember-metal';
import { jQuery } from 'ember-views';
import { moduleFor, RenderingTest } from '../../utils/test-case';
import { Component, compile } from '../../utils/helpers';
import { strip } from '../../utils/abstract-test-case';
class AbstractAppendTest extends RenderingTest {
constructor() {
super();
this.components = [];
this.ids = [];
}
teardown() {
this.component = null;
this.components.forEach(component => {
this.runTask(() => component.destroy());
});
this.ids.forEach(id => {
let $element = jQuery(id).remove();
this.assert.strictEqual($element.length, 0, `Should not leak element: #${id}`);
});
super();
}
/* abstract append(component): Element; */
didAppend(component) {
this.components.push(component);
this.ids.push(component.elementId);
}
['@test lifecycle hooks during component append'](assert) {
let hooks = [];
let oldRegisterComponent = this.registerComponent;
let componentsByName = {};
// TODO: refactor/combine with other life-cycle tests
this.registerComponent = function(name, _options) {
function pushHook(hookName) {
hooks.push([name, hookName]);
}
let options = {
ComponentClass: _options.ComponentClass.extend({
init() {
expectDeprecation(() => { this._super(...arguments); }, /didInitAttrs called/);
if (name in componentsByName) {
throw new TypeError('Component named: ` ' + name + ' ` already registered');
}
componentsByName[name] = this;
pushHook('init');
this.on('init', () => pushHook('on(init)'));
},
didInitAttrs(options) {
pushHook('didInitAttrs', options);
},
didReceiveAttrs() {
pushHook('didReceiveAttrs');
},
willInsertElement() {
pushHook('willInsertElement');
},
willRender() {
pushHook('willRender');
},
didInsertElement() {
pushHook('didInsertElement');
},
didRender() {
pushHook('didRender');
},
didUpdateAttrs() {
pushHook('didUpdateAttrs');
},
willUpdate() {
pushHook('willUpdate');
},
didUpdate() {
pushHook('didUpdate');
},
willDestroyElement() {
pushHook('willDestroyElement');
},
willClearRender() {
pushHook('willClearRender');
},
didDestroyElement() {
pushHook('didDestroyElement');
},
willDestroy() {
pushHook('willDestroy');
this._super(...arguments);
}
}),
template: _options.template
};
oldRegisterComponent.call(this, name, options);
};
this.registerComponent('x-parent', {
ComponentClass: Component.extend({
layoutName: 'components/x-parent'
}),
template: '[parent: {{foo}}]{{#x-child bar=foo}}[yielded: {{foo}}]{{/x-child}}'
});
this.registerComponent('x-child', {
ComponentClass: Component.extend({
tagName: ''
}),
template: '[child: {{bar}}]{{yield}}'
});
let XParent = this.owner._lookupFactory('component:x-parent');
this.component = XParent.create({ foo: 'zomg' });
assert.deepEqual(hooks, [
['x-parent', 'init'],
['x-parent', 'didInitAttrs'],
['x-parent', 'didReceiveAttrs'],
['x-parent', 'on(init)']
], 'creation of x-parent');
hooks.length = 0;
this.element = this.append(this.component);
assert.deepEqual(hooks, [
['x-parent', 'willInsertElement'],
['x-child', 'init'],
['x-child', 'didInitAttrs'],
['x-child', 'didReceiveAttrs'],
['x-child', 'on(init)'],
['x-child', 'willRender'],
['x-child', 'willInsertElement'],
['x-child', 'didInsertElement'],
['x-child', 'didRender'],
['x-parent', 'didInsertElement'],
['x-parent', 'didRender']
], 'appending of x-parent');
hooks.length = 0;
this.runTask(() => componentsByName['x-parent'].rerender());
assert.deepEqual(hooks, [
['x-parent', 'willUpdate'],
['x-parent', 'willRender'],
['x-parent', 'didUpdate'],
['x-parent', 'didRender']
], 'rerender x-parent');
hooks.length = 0;
this.runTask(() => componentsByName['x-child'].rerender());
assert.deepEqual(hooks, [
['x-parent', 'willUpdate'],
['x-parent', 'willRender'],
['x-child', 'willUpdate'],
['x-child', 'willRender'],
['x-child', 'didUpdate'],
['x-child', 'didRender'],
['x-parent', 'didUpdate'],
['x-parent', 'didRender']
], 'rerender x-child');
hooks.length = 0;
this.runTask(() => set(this.component, 'foo', 'wow'));
assert.deepEqual(hooks, [
['x-parent', 'willUpdate'],
['x-parent', 'willRender'],
['x-child', 'didUpdateAttrs'],
['x-child', 'didReceiveAttrs'],
['x-child', 'willUpdate'],
['x-child', 'willRender'],
['x-child', 'didUpdate'],
['x-child', 'didRender'],
['x-parent', 'didUpdate'],
['x-parent', 'didRender']
], 'set foo = wow');
hooks.length = 0;
this.runTask(() => set(this.component, 'foo', 'zomg'));
assert.deepEqual(hooks, [
['x-parent', 'willUpdate'],
['x-parent', 'willRender'],
['x-child', 'didUpdateAttrs'],
['x-child', 'didReceiveAttrs'],
['x-child', 'willUpdate'],
['x-child', 'willRender'],
['x-child', 'didUpdate'],
['x-child', 'didRender'],
['x-parent', 'didUpdate'],
['x-parent', 'didRender']
], 'set foo = zomg');
hooks.length = 0;
this.runTask(() => this.component.destroy());
assert.deepEqual(hooks, [
['x-parent', 'willDestroyElement'],
['x-parent', 'willClearRender'],
['x-child', 'willDestroyElement'],
['x-child', 'willClearRender'],
['x-child', 'didDestroyElement'],
['x-parent', 'didDestroyElement'],
['x-parent', 'willDestroy'],
['x-child', 'willDestroy']
], 'destroy');
}
['@test appending, updating and destroying a single component'](assert) {
let willDestroyCalled = 0;
this.registerComponent('x-parent', {
ComponentClass: Component.extend({
layoutName: 'components/x-parent',
willDestroyElement() {
willDestroyCalled++;
}
}),
template: '[parent: {{foo}}]{{#x-child bar=foo}}[yielded: {{foo}}]{{/x-child}}'
});
this.registerComponent('x-child', {
ComponentClass: Component.extend({
tagName: ''
}),
template: '[child: {{bar}}]{{yield}}'
});
let XParent = this.owner._lookupFactory('component:x-parent');
this.component = XParent.create({ foo: 'zomg' });
assert.ok(!this.component.element, 'precond - should not have an element');
this.element = this.append(this.component);
let componentElement = this.component.element;
this.assertComponentElement(componentElement, { content: '[parent: zomg][child: zomg][yielded: zomg]' });
assert.equal(componentElement.parentElement, this.element, 'It should be attached to the target');
this.runTask(() => this.rerender());
this.assertComponentElement(componentElement, { content: '[parent: zomg][child: zomg][yielded: zomg]' });
assert.equal(componentElement.parentElement, this.element, 'It should be attached to the target');
this.runTask(() => set(this.component, 'foo', 'wow'));
this.assertComponentElement(componentElement, { content: '[parent: wow][child: wow][yielded: wow]' });
assert.equal(componentElement.parentElement, this.element, 'It should be attached to the target');
this.runTask(() => set(this.component, 'foo', 'zomg'));
this.assertComponentElement(componentElement, { content: '[parent: zomg][child: zomg][yielded: zomg]' });
assert.equal(componentElement.parentElement, this.element, 'It should be attached to the target');
this.runTask(() => this.component.destroy());
if (this.isHTMLBars) {
// Bug in Glimmer – component should not have .element at this point
assert.ok(!this.component.element, 'It should not have an element');
}
assert.ok(!componentElement.parentElement, 'The component element should be detached');
this.assert.equal(willDestroyCalled, 1);
}
['@test appending, updating and destroying multiple components'](assert) {
let willDestroyCalled = 0;
this.registerComponent('x-first', {
ComponentClass: Component.extend({
layoutName: 'components/x-first',
willDestroyElement() {
willDestroyCalled++;
}
}),
template: 'x-first {{foo}}!'
});
this.registerComponent('x-second', {
ComponentClass: Component.extend({
layoutName: 'components/x-second',
willDestroyElement() {
willDestroyCalled++;
}
}),
template: 'x-second {{bar}}!'
});
let First = this.owner._lookupFactory('component:x-first');
let Second = this.owner._lookupFactory('component:x-second');
let first = First.create({ foo: 'foo' });
let second = Second.create({ bar: 'bar' });
this.assert.ok(!first.element, 'precond - should not have an element');
this.assert.ok(!second.element, 'precond - should not have an element');
let wrapper1, wrapper2;
this.runTask(() => wrapper1 = this.append(first));
this.runTask(() => wrapper2 = this.append(second));
let componentElement1 = first.element;
let componentElement2 = second.element;
this.assertComponentElement(componentElement1, { content: 'x-first foo!' });
this.assertComponentElement(componentElement2, { content: 'x-second bar!' });
assert.equal(componentElement1.parentElement, wrapper1, 'The first component should be attached to the target');
assert.equal(componentElement2.parentElement, wrapper2, 'The second component should be attached to the target');
this.runTask(() => set(first, 'foo', 'FOO'));
this.assertComponentElement(componentElement1, { content: 'x-first FOO!' });
this.assertComponentElement(componentElement2, { content: 'x-second bar!' });
assert.equal(componentElement1.parentElement, wrapper1, 'The first component should be attached to the target');
assert.equal(componentElement2.parentElement, wrapper2, 'The second component should be attached to the target');
this.runTask(() => set(second, 'bar', 'BAR'));
this.assertComponentElement(componentElement1, { content: 'x-first FOO!' });
this.assertComponentElement(componentElement2, { content: 'x-second BAR!' });
assert.equal(componentElement1.parentElement, wrapper1, 'The first component should be attached to the target');
assert.equal(componentElement2.parentElement, wrapper2, 'The second component should be attached to the target');
this.runTask(() => {
set(first, 'foo', 'foo');
set(second, 'bar', 'bar');
});
this.assertComponentElement(componentElement1, { content: 'x-first foo!' });
this.assertComponentElement(componentElement2, { content: 'x-second bar!' });
assert.equal(componentElement1.parentElement, wrapper1, 'The first component should be attached to the target');
assert.equal(componentElement2.parentElement, wrapper2, 'The second component should be attached to the target');
this.runTask(() => {
first.destroy();
second.destroy();
});
if (this.isHTMLBars) {
// Bug in Glimmer – component should not have .element at this point
assert.ok(!first.element, 'The first component should not have an element');
assert.ok(!second.element, 'The second component should not have an element');
}
assert.ok(!componentElement1.parentElement, 'The first component element should be detached');
assert.ok(!componentElement2.parentElement, 'The second component element should be detached');
this.assert.equal(willDestroyCalled, 2);
}
['@test can appendTo while rendering'](assert) {
let owner = this.owner;
let append = (component) => {
return this.append(component);
};
let element1, element2;
this.registerComponent('first-component', {
ComponentClass: Component.extend({
layout: compile('component-one'),
didInsertElement() {
element1 = this.element;
let SecondComponent = owner._lookupFactory('component:second-component');
append(SecondComponent.create());
}
})
});
this.registerComponent('second-component', {
ComponentClass: Component.extend({
layout: compile(`component-two`),
didInsertElement() {
element2 = this.element;
}
})
});
let FirstComponent = this.owner._lookupFactory('component:first-component');
this.runTask(() => append(FirstComponent.create()));
this.assertComponentElement(element1, { content: 'component-one' });
this.assertComponentElement(element2, { content: 'component-two' });
}
['@test can appendTo and remove while rendering'](assert) {
let owner = this.owner;
let append = (component) => {
return this.append(component);
};
let element1, element2, element3, element4, component1, component2;
this.registerComponent('foo-bar', {
ComponentClass: Component.extend({
layout: compile('foo-bar'),
init() {
this._super(...arguments);
component1 = this;
},
didInsertElement() {
element1 = this.element;
let OtherRoot = owner._lookupFactory('component:other-root');
this._instance = OtherRoot.create({
didInsertElement() {
element2 = this.element;
}
});
append(this._instance);
},
willDestroy() {
this._instance.destroy();
}
})
});
this.registerComponent('baz-qux', {
ComponentClass: Component.extend({
layout: compile('baz-qux'),
init() {
this._super(...arguments);
component2 = this;
},
didInsertElement() {
element3 = this.element;
let OtherRoot = owner._lookupFactory('component:other-root');
this._instance = OtherRoot.create({
didInsertElement() {
element4 = this.element;
}
});
append(this._instance);
},
willDestroy() {
this._instance.destroy();
}
})
});
let instantiatedRoots = 0;
let destroyedRoots = 0;
this.registerComponent('other-root', {
ComponentClass: Component.extend({
layout: compile(`fake-thing: {{counter}}`),
init() {
this._super(...arguments);
this.counter = instantiatedRoots++;
},
willDestroy() {
destroyedRoots++;
this._super(...arguments);
}
})
});
this.render(strip`
{{#if showFooBar}}
{{foo-bar}}
{{else}}
{{baz-qux}}
{{/if}}
`, { showFooBar: true });
this.assertComponentElement(element1, { });
this.assertComponentElement(element2, { content: 'fake-thing: 0' });
assert.equal(instantiatedRoots, 1);
this.assertStableRerender();
this.runTask(() => set(this.context, 'showFooBar', false));
assert.equal(instantiatedRoots, 2);
assert.equal(destroyedRoots, 1);
this.assertComponentElement(element3, { });
this.assertComponentElement(element4, { content: 'fake-thing: 1' });
this.runTask(() => {
component1.destroy();
component2.destroy();
});
assert.equal(instantiatedRoots, 2);
assert.equal(destroyedRoots, 2);
}
}
moduleFor('append: no arguments (attaching to document.body)', class extends AbstractAppendTest {
append(component) {
this.runTask(() => component.append());
this.didAppend(component);
return document.body;
}
});
moduleFor('appendTo: a selector', class extends AbstractAppendTest {
append(component) {
this.runTask(() => component.appendTo('#qunit-fixture'));
this.didAppend(component);
return jQuery('#qunit-fixture')[0];
}
['@test raises an assertion when the target does not exist in the DOM'](assert) {
this.registerComponent('foo-bar', {
ComponentClass: Component.extend({
layoutName: 'components/foo-bar'
}),
template: 'FOO BAR!'
});
let FooBar = this.owner._lookupFactory('component:foo-bar');
this.component = FooBar.create();
assert.ok(!this.component.element, 'precond - should not have an element');
this.runTask(() => {
expectAssertion(() => {
this.component.appendTo('#does-not-exist-in-dom');
}, /You tried to append to \(#does-not-exist-in-dom\) but that isn't in the DOM/);
});
assert.ok(!this.component.element, 'component should not have an element');
}
});
moduleFor('appendTo: an element', class extends AbstractAppendTest {
append(component) {
let element = jQuery('#qunit-fixture')[0];
this.runTask(() => component.appendTo(element));
this.didAppend(component);
return element;
}
});
moduleFor('appendTo: with multiple components', class extends AbstractAppendTest {
append(component) {
this.runTask(() => component.appendTo('#qunit-fixture'));
this.didAppend(component);
return jQuery('#qunit-fixture')[0];
}
});
moduleFor('renderToElement: no arguments (defaults to a body context)', class extends AbstractAppendTest {
append(component) {
expectDeprecation(/Using the `renderToElement` is deprecated in favor of `appendTo`. Called in/);
let wrapper;
this.runTask(() => wrapper = component.renderToElement());
this.didAppend(component);
this.assert.equal(wrapper.tagName, 'BODY', 'wrapper is a body element');
this.assert.notEqual(wrapper, document.body, 'wrapper is not document.body');
this.assert.ok(!wrapper.parentNode, 'wrapper is detached');
return wrapper;
}
});
moduleFor('renderToElement: a div', class extends AbstractAppendTest {
append(component) {
expectDeprecation(/Using the `renderToElement` is deprecated in favor of `appendTo`. Called in/);
let wrapper;
this.runTask(() => wrapper = component.renderToElement('div'));
this.didAppend(component);
this.assert.equal(wrapper.tagName, 'DIV', 'wrapper is a body element');
this.assert.ok(!wrapper.parentNode, 'wrapper is detached');
return wrapper;
}
});
|
(function () {
var g = void 0,
k = !0,
m = null,
o = !1,
p, q = this,
r = function (a) {
var b = typeof a;
if ("object" == b) if (a) {
if (a instanceof Array) return "array";
if (a instanceof Object) return b;
var c = Object.prototype.toString.call(a);
if ("[object Window]" == c) return "object";
if ("[object Array]" == c || "number" == typeof a.length && "undefined" != typeof a.splice && "undefined" != typeof a.propertyIsEnumerable && !a.propertyIsEnumerable("splice")) return "array";
if ("[object Function]" == c || "undefined" != typeof a.call && "undefined" != typeof a.propertyIsEnumerable && !a.propertyIsEnumerable("call")) return "function"
} else return "null";
else if ("function" == b && "undefined" == typeof a.call) return "object";
return b
},
aa = function (a) {
var b = r(a);
return "array" == b || "object" == b && "number" == typeof a.length
},
u = function (a) {
return "string" == typeof a
},
ba = function (a) {
a = r(a);
return "object" == a || "array" == a || "function" == a
},
ca = function (a, b, c) {
return a.call.apply(a.bind, arguments)
},
da = function (a, b, c) {
if (!a) throw Error();
if (2 < arguments.length) {
var d = Array.prototype.slice.call(arguments, 2);
return function () {
var c = Array.prototype.slice.call(arguments);
Array.prototype.unshift.apply(c, d);
return a.apply(b, c)
}
}
return function () {
return a.apply(b, arguments)
}
},
v = function (a, b, c) {
v = Function.prototype.bind && -1 != Function.prototype.bind.toString().indexOf("native code") ? ca : da;
return v.apply(m, arguments)
},
ea = function (a, b) {
function c() {}
c.prototype = b.prototype;
a.Sa = b.prototype;
a.prototype = new c
};
Function.prototype.bind = Function.prototype.bind ||
function (a, b) {
if (1 < arguments.length) {
var c = Array.prototype.slice.call(arguments, 1);
c.unshift(this, a);
return v.apply(m, c)
}
return v(this, a)
};
var w = function (a) {
this.stack = Error().stack || "";
if (a) this.message = "" + a
};
ea(w, Error);
w.prototype.name = "CustomError";
var fa = function (a, b) {
for (var c = 1; c < arguments.length; c++) var d = ("" + arguments[c]).replace(/\$/g, "$$$$"),
a = a.replace(/\%s/, d);
return a
},
ma = function (a) {
if (!ga.test(a)) return a; - 1 != a.indexOf("&") && (a = a.replace(ha, "&")); - 1 != a.indexOf("<") && (a = a.replace(ia, "<")); - 1 != a.indexOf(">") && (a = a.replace(ka, ">")); - 1 != a.indexOf('"') && (a = a.replace(la, """));
return a
},
ha = /&/g,
ia = /</g,
ka = />/g,
la = /\"/g,
ga = /[&<>\"]/;
var x = function (a, b) {
b.unshift(a);
w.call(this, fa.apply(m, b));
b.shift();
this.Ra = a
};
ea(x, w);
x.prototype.name = "AssertionError";
var y = function (a, b, c) {
if (!a) {
var d = Array.prototype.slice.call(arguments, 2),
f = "Assertion failed";
if (b) var f = f + (": " + b),
e = d;
throw new x("" + f, e || []);
}
};
var z = Array.prototype,
na = z.indexOf ?
function (a, b, c) {
y(a.length != m);
return z.indexOf.call(a, b, c)
} : function (a, b, c) {
c = c == m ? 0 : 0 > c ? Math.max(0, a.length + c) : c;
if (u(a)) return !u(b) || 1 != b.length ? -1 : a.indexOf(b, c);
for (; c < a.length; c++) if (c in a && a[c] === b) return c;
return -1
}, oa = z.forEach ?
function (a, b, c) {
y(a.length != m);
z.forEach.call(a, b, c)
} : function (a, b, c) {
for (var d = a.length, f = u(a) ? a.split("") : a, e = 0; e < d; e++) e in f && b.call(c, f[e], e, a)
}, pa = function (a) {
return z.concat.apply(z, arguments)
}, qa = function (a) {
if ("array" == r(a)) return pa(a);
for (var b = [], c = 0, d = a.length; c < d; c++) b[c] = a[c];
return b
}, ra = function (a, b, c) {
y(a.length != m);
return 2 >= arguments.length ? z.slice.call(a, b) : z.slice.call(a, b, c)
};
var A = function (a, b) {
this.x = a !== g ? a : 0;
this.y = b !== g ? b : 0
};
A.prototype.toString = function () {
return "(" + this.x + ", " + this.y + ")"
};
var sa = function (a, b) {
for (var c in a) b.call(g, a[c], c, a)
},
ta = "constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf".split(","),
ua = function (a, b) {
for (var c, d, f = 1; f < arguments.length; f++) {
d = arguments[f];
for (c in d) a[c] = d[c];
for (var e = 0; e < ta.length; e++) c = ta[e], Object.prototype.hasOwnProperty.call(d, c) && (a[c] = d[c])
}
};
var B, va, C, wa, xa = function () {
return q.navigator ? q.navigator.userAgent : m
};
wa = C = va = B = o;
var D;
if (D = xa()) {
var ya = q.navigator;
B = 0 == D.indexOf("Opera");
va = !B && -1 != D.indexOf("MSIE");
C = !B && -1 != D.indexOf("WebKit");
wa = !B && !C && "Gecko" == ya.product
}
var za = B,
E = va,
F = wa,
G = C,
Aa;
a: {
var H = "",
I;
if (za && q.opera) var Ba = q.opera.version,
H = "function" == typeof Ba ? Ba() : Ba;
else if (F ? I = /rv\:([^\);]+)(\)|;)/ : E ? I = /MSIE\s+([^\);]+)(\)|;)/ : G && (I = /WebKit\/(\S+)/), I) var Ca = I.exec(xa()),
H = Ca ? Ca[1] : "";
if (E) {
var Da, Ea = q.document;
Da = Ea ? Ea.documentMode : g;
if (Da > parseFloat(H)) {
Aa = "" + Da;
break a
}
}
Aa = H
}
var Fa = Aa,
Ga = {},
Ha = function (a) {
var b;
if (!(b = Ga[a])) {
b = 0;
for (var c = ("" + Fa).replace(/^[\s\xa0]+|[\s\xa0]+$/g, "").split("."), d = ("" + a).replace(/^[\s\xa0]+|[\s\xa0]+$/g, "").split("."), f = Math.max(c.length, d.length), e = 0; 0 == b && e < f; e++) {
var h = c[e] || "",
n = d[e] || "",
j = RegExp("(\\d*)(\\D*)", "g"),
t = RegExp("(\\d*)(\\D*)", "g");
do {
var i = j.exec(h) || ["", "", ""],
l = t.exec(n) || ["", "", ""];
if (0 == i[0].length && 0 == l[0].length) break;
b = ((0 == i[1].length ? 0 : parseInt(i[1], 10)) < (0 == l[1].length ? 0 : parseInt(l[1], 10)) ? -1 : (0 == i[1].length ? 0 : parseInt(i[1], 10)) > (0 == l[1].length ? 0 : parseInt(l[1], 10)) ? 1 : 0) || ((0 == i[2].length) < (0 == l[2].length) ? -1 : (0 == i[2].length) > (0 == l[2].length) ? 1 : 0) || (i[2] < l[2] ? -1 : i[2] > l[2] ? 1 : 0)
} while (0 == b)
}
b = Ga[a] = 0 <= b
}
return b
},
Ia = {},
J = function (a) {
return Ia[a] || (Ia[a] = E && document.documentMode && document.documentMode >= a)
};
var Ja, Ka = !E || J(9);
!F && !E || E && J(9) || F && Ha("1.9.1");
E && Ha("9");
var La = function (a, b) {
var c;
c = (c = a.className) && "function" == typeof c.split ? c.split(/\s+/) : [];
var d = ra(arguments, 1),
f;
f = c;
for (var e = 0, h = 0; h < d.length; h++) 0 <= na(f, d[h]) || (f.push(d[h]), e++);
f = e == d.length;
a.className = c.join(" ");
return f
};
var Ma = function (a) {
return a ? new K(L(a)) : Ja || (Ja = new K)
},
Na = function (a, b) {
var c = b && "*" != b ? b.toUpperCase() : "";
return a.querySelectorAll && a.querySelector && (!G || "CSS1Compat" == document.compatMode || Ha("528")) && c ? a.querySelectorAll(c + "") : a.getElementsByTagName(c || "*")
},
Pa = function (a, b) {
sa(b, function (b, d) {
"style" == d ? a.style.cssText = b : "class" == d ? a.className = b : "for" == d ? a.htmlFor = b : d in Oa ? a.setAttribute(Oa[d], b) : 0 == d.lastIndexOf("aria-", 0) ? a.setAttribute(d, b) : a[d] = b
})
},
Oa = {
cellpadding: "cellPadding",
cellspacing: "cellSpacing",
colspan: "colSpan",
rowspan: "rowSpan",
valign: "vAlign",
height: "height",
width: "width",
usemap: "useMap",
frameborder: "frameBorder",
maxlength: "maxLength",
type: "type"
},
Qa = function (a, b, c) {
function d(c) {
c && b.appendChild(u(c) ? a.createTextNode(c) : c)
}
for (var f = 2; f < c.length; f++) {
var e = c[f];
if (aa(e) && !(ba(e) && 0 < e.nodeType)) {
var h;
a: {
if (e && "number" == typeof e.length) {
if (ba(e)) {
h = "function" == typeof e.item || "string" == typeof e.item;
break a
}
if ("function" == r(e)) {
h = "function" == typeof e.item;
break a
}
}
h = o
}
oa(h ? qa(e) : e, d)
} else d(e)
}
},
L = function (a) {
return 9 == a.nodeType ? a : a.ownerDocument || a.document
},
K = function (a) {
this.C = a || q.document || document
};
K.prototype.za = function (a, b, c) {
var d = this.C,
f = arguments,
e = f[0],
h = f[1];
if (!Ka && h && (h.name || h.type)) {
e = ["<", e];
h.name && e.push(' name="', ma(h.name), '"');
if (h.type) {
e.push(' type="', ma(h.type), '"');
var n = {};
ua(n, h);
h = n;
delete h.type
}
e.push(">");
e = e.join("")
}
e = d.createElement(e);
if (h) u(h) ? e.className = h : "array" == r(h) ? La.apply(m, [e].concat(h)) : Pa(e, h);
2 < f.length && Qa(d, e, f);
return e
};
K.prototype.createElement = function (a) {
return this.C.createElement(a)
};
K.prototype.createTextNode = function (a) {
return this.C.createTextNode(a)
};
K.prototype.appendChild = function (a, b) {
a.appendChild(b)
};
var M = function (a) {
var b;
a: {
b = L(a);
if (b.defaultView && b.defaultView.getComputedStyle && (b = b.defaultView.getComputedStyle(a, m))) {
b = b.position || b.getPropertyValue("position");
break a
}
b = ""
}
return b || (a.currentStyle ? a.currentStyle.position : m) || a.style && a.style.position
},
Ra = function (a) {
if (E && !J(8)) return a.offsetParent;
for (var b = L(a), c = M(a), d = "fixed" == c || "absolute" == c, a = a.parentNode; a && a != b; a = a.parentNode) if (c = M(a), d = d && "static" == c && a != b.documentElement && a != b.body, !d && (a.scrollWidth > a.clientWidth || a.scrollHeight > a.clientHeight || "fixed" == c || "absolute" == c || "relative" == c)) return a;
return m
},
N = function (a) {
var b, c = L(a),
d = M(a),
f = F && c.getBoxObjectFor && !a.getBoundingClientRect && "absolute" == d && (b = c.getBoxObjectFor(a)) && (0 > b.screenX || 0 > b.screenY),
e = new A(0, 0),
h;
b = c ? 9 == c.nodeType ? c : L(c) : document;
if (h = E) if (h = !J(9)) h = "CSS1Compat" != Ma(b).C.compatMode;
h = h ? b.body : b.documentElement;
if (a == h) return e;
if (a.getBoundingClientRect) {
b = a.getBoundingClientRect();
if (E) a = a.ownerDocument, b.left -= a.documentElement.clientLeft + a.body.clientLeft, b.top -= a.documentElement.clientTop + a.body.clientTop;
a = Ma(c).C;
c = !G && "CSS1Compat" == a.compatMode ? a.documentElement : a.body;
a = a.parentWindow || a.defaultView;
c = new A(a.pageXOffset || c.scrollLeft, a.pageYOffset || c.scrollTop);
e.x = b.left + c.x;
e.y = b.top + c.y
} else if (c.getBoxObjectFor && !f) b = c.getBoxObjectFor(a), c = c.getBoxObjectFor(h), e.x = b.screenX - c.screenX, e.y = b.screenY - c.screenY;
else {
b = a;
do {
e.x += b.offsetLeft;
e.y += b.offsetTop;
b != a && (e.x += b.clientLeft || 0, e.y += b.clientTop || 0);
if (G && "fixed" == M(b)) {
e.x += c.body.scrollLeft;
e.y += c.body.scrollTop;
break
}
b = b.offsetParent
} while (b && b != a);
if (za || G && "absolute" == d) e.y -= c.body.offsetTop;
for (b = a;
(b = Ra(b)) && b != c.body && b != h;) if (e.x -= b.scrollLeft, !za || "TR" != b.tagName) e.y -= b.scrollTop
}
return e
},
Ta = function () {
var a = Ma(g),
b = m;
if (E) b = a.C.createStyleSheet(), Sa(b);
else {
var c = Na(a.C, "head")[0];
c || (b = Na(a.C, "body")[0], c = a.za("head"), b.parentNode.insertBefore(c, b));
b = a.za("style");
Sa(b);
a.appendChild(c, b)
}
},
Sa = function (a) {
E ? a.cssText = "canvas:active{cursor:pointer}" : a[G ? "innerText" : "innerHTML"] = "canvas:active{cursor:pointer}"
};
var O = function (a, b) {
var c = {},
d;
for (d in b) c[d] = a.style[d], a.style[d] = b[d];
return c
},
P = function (a, b) {
this.M = a || m;
this.fa = m;
this.ya = b ||
function () {};
this.Q = 0;
this.ta = 0.05
},
Ua = function (a, b) {
a.ya = b
};
P.prototype.s = function () {
if (this.M && this.ta) {
this.Q += this.ta;
if (1 < this.Q) this.Q = 1, this.ta = 0, this.ya();
var a = "0 0 2px rgba(255,0,0," + this.Q + ")",
a = O(this.M, {
boxShadow: a,
MozBoxShadow: a,
webkitBoxShadow: a,
oBoxShadow: a,
msBoxShadow: a,
opacity: this.Q
});
if (!this.fa) this.fa = a
}
};
P.prototype.restore = function () {
this.M && this.fa && O(this.M, this.fa)
};
var Va = function () {
this.H = []
};
Va.prototype.k = function (a, b, c) {
if (a) {
this.H.push(arguments);
var d = a,
f = b,
e = c;
d.addEventListener ? d.addEventListener(f, e, o) : d.attachEvent("on" + f, e)
}
};
var Wa = function (a, b, c) {
a && (a.removeEventListener ? a.removeEventListener(b, c, o) : a.detachEvent("on" + b, c))
};
var Xa = Math.PI / 2,
Q = function (a, b, c) {
this.ca = a;
this.P = document.createElement("div");
this.P.style.position = "absolute";
var a = Math.floor(3 * Math.random() + 0),
d = "\u2744";
1 < a ? d = "\u2745" : 2 < a && (d = "\u2746");
this.P.innerHTML = d;
this.ca.appendChild(this.P);
this.Y = c;
this.X = b;
this.reset()
};
Q.prototype.reset = function () {
this.x = Math.random() * this.X;
this.ea = 4.5 * Math.random() + 1;
this.y = -this.ea;
this.B = 2 * Math.random() + -1;
this.xa = this.ea;
var a = Math.floor(255 * (0.4 * Math.random() + 0.5)).toString(16);
O(this.P, {
fontSize: 2.5 * this.ea + "px",
left: this.x + "px",
top: this.y + "px",
color: "#" + a + a + a
})
};
Q.prototype.move = function (a, b) {
this.y += this.B * b + this.xa * a;
this.B += 0.2 * Math.random() + -0.1;
if (-1 > this.B) this.B = -1;
else if (1 < this.B) this.B = 1;
this.x += this.B * a + this.xa * b;
this.y > this.Y + this.ea && this.reset()
};
Q.prototype.s = function () {
this.P.style.left = this.x + "px";
this.P.style.top = this.y + "px"
};
var R = function (a) {
this.ca = a;
this.X = a.offsetWidth;
this.Y = a.offsetHeight;
this.da = [];
this.ra = 1;
this.sa = 0;
this.Ma = !! navigator.userAgent.match(/(iPod|iPhone|iPad)/)
};
R.prototype.s = function () {
200 > this.da.length && 0.5 > Math.random() && this.da.push(new Q(this.ca, this.X, this.Y));
for (var a = 0, b; b = this.da[a]; a++) b.move(this.ra, this.sa), b.s()
};
R.prototype.Ca = function (a) {
if (this.Ma) {
var b = window.orientation & 2,
c = b ? a.beta : a.gamma / 2,
a = b ? 0 > a.gamma ? 1 : -1 : 0 > a.beta ? -1 : 1;
if (c && 45 > Math.abs(c)) c = a * Xa * (c / 45), this.ra = Math.cos(c), this.sa = Math.sin(c)
} else {
if (!a.gamma && a.x) a.gamma = -(a.x * (180 / Math.PI));
if (a.gamma && 90 > Math.abs(a.gamma)) c = Xa * (a.gamma / 90), this.ra = Math.cos(c), this.sa = Math.sin(c)
}
};
R.prototype.N = function (a, b) {
O(this.ca, {
width: a + "px",
height: b + "px"
});
this.X = a;
this.Y = b;
for (var c = 0, d; d = this.da[c]; c++) {
var f = b;
d.X = a;
d.Y = f
}
};
var Ya = function (a, b, c, d) {
this.oa = b;
this.g = a;
this.x = c;
this.y = d;
this.width = b.width;
this.height = b.height;
this.la = (this.width + 120) / 88;
this.Ea = (this.height + 120) / 66;
this.ga = 0;
this.$ = o;
this.w = [];
this.G = [];
for (a = 0; 66 > a; a++) {
this.w[a] = [];
this.G[a] = [];
b = Math.min(a, 65 - a);
for (c = 0; 88 > c; c++) d = Math.min(c, 87 - c), 8 > d || 8 > b ? (d = 1 - Math.min(d, b) / 8, this.G[a].push(4 * Math.random() * d * d)) : this.G[a].push(0), this.w[a].push(0)
}
this.S = 0;
this.L = [];
this.v = m;
this.ka = [];
this.W = this.aa = 0;
this.I = m;
this.ma = o
},
Za = function (a, b, c) {
b = (b + 60) / a.la | 0;
c = (c + 60) / a.Ea | 0;
return [b, c]
},
$a = function (a, b, c) {
for (var d = 0, f = c - 1; f <= c + 1; f++) for (var e = b - 1; e <= b + 1; e++) var h = a,
n = e,
j = f,
n = Math.max(0, Math.min(87, n)),
j = Math.max(0, Math.min(65, j)),
d = d + h.w[j][n];
return d / 9
},
ab = function (a, b) {
a.$ = k;
b.fillStyle = "rgba(240,246,246,0.8)";
b.fillRect(0, 0, b.canvas.width, b.canvas.height)
};
Ya.prototype.s = function (a) {
if (!(this.$ || 88 < this.ga || 5808 < this.S)) {
a.fillStyle = "rgba(240,246,246,0.08)";
for (var b = 0; 200 > b; b++) {
var c = Math.random() * (this.width + 120) - 60,
d = Math.random() * (this.height + 120) - 60,
f = Za(this, c, d),
e = this.w[f[1]][f[0]];
e >= 4 * (1 + Math.random()) / 2 && (c |= 0, d |= 0, a.beginPath(), a.arc(c, d, e / 4 * this.la | 0, 0, 2 * Math.PI, k), a.fill(), a.closePath(), this.S++)
}
for (b = 0; 200 > b; b++) if (c = Math.random() * (this.width + 120) - 60, d = Math.random() * (this.height + 120) - 60, f = Za(this, c, d), e = this.w[f[1]][f[0]], f = this.G[f[1]][f[0]], e = 2 > e ? Math.max(e, f) : f, e >= Math.random()) e = 3 * Math.min(1, e) * this.la | 0, c |= 0, d |= 0, f = a.createRadialGradient(c, d, 0, c, d, e), f.addColorStop(0, "rgba(240,246,246,0.16)"), f.addColorStop(1, "rgba(240,246,246,0)"), a.fillStyle = f, a.fillRect(c - e + 1, d - e + 1, 2 * e - 1, 2 * e - 1), this.S++
}
bb(this);
bb(this);
for (b = 0; b < this.L.length; b++) this.L[b].s(a)
};
var cb = function (a, b) {
a.ka = b;
a.aa = 0;
a.W = 0;
a.I = m
},
bb = function (a) {
if (!(a.v || a.aa >= a.ka.length)) {
var b = a.ka[a.aa].O;
if (!a.I) a.I = new S, a.L.push(a.I);
a.I.ba.apply(a.I, b[a.W]);
a.W++;
if (a.W >= b.length) a.W = 0, a.aa++, a.I = m
}
},
T = function (a, b) {
a.v && a.v.ba(b[0], b[1])
},
db = function (a) {
a.g.k(window, "touchmove", v(a.Ka, a));
a.g.k(window, "touchstart", v(a.La, a));
a.g.k(window, "touchend", v(a.Ja, a));
a.g.k(window, "mousemove", v(a.Ha, a));
a.g.k(window, "mousedown", v(a.Ga, a));
a.g.k(window, "mouseup", v(a.Ia, a))
};
p = Ya.prototype;
p.Ha = function (a) {
this.v && !this.ma && T(this, [a.clientX - this.x | 0, a.clientY - this.y | 0])
};
p.Ga = function (a) {
if ((a.target || a.srcElement) == this.oa && (0 == a.button || 1 == a.button)) {
var b = [a.clientX - this.x | 0, a.clientY - this.y | 0];
this.v = new S;
this.L.push(this.v);
T(this, b);
a.preventDefault();
return o
}
};
p.Ia = function () {
this.v = m
};
p.La = function (a) {
this.ma = k;
a = a.touches.item(0);
a = [a.clientX - this.x | 0, a.clientY - this.y | 0];
this.v = new S;
this.L.push(this.v);
T(this, a)
};
p.Ja = function (a) {
this.ma = o;
this.v = m;
a.preventDefault();
return o
};
p.Ka = function (a) {
var b = a.touches.item(0);
T(this, [b.clientX - this.x | 0, b.clientY - this.y | 0]);
a.preventDefault();
return o
};
p.N = function (a, b, c) {
this.oa.width = a;
this.oa.height = b;
this.width = a;
this.height = b;
ab(this, c)
};
var S = function () {
this.Qa = this.Oa = 30;
this.O = []
};
S.prototype.ba = function (a, b) {
this.O.push([a, b])
};
S.prototype.s = function (a) {
if (0 != this.O.length) {
var b = a.globalCompositeOperation;
a.globalCompositeOperation = "destination-out";
a.lineWidth = this.Oa;
a.lineCap = "round";
a.lineJoin = "round";
a.beginPath();
var c = this.O[0];
a.moveTo(c[0], c[1] - 1);
for (var d = 0; c = this.O[d]; d++) a.lineTo(c[0], c[1]);
a.stroke();
a.globalCompositeOperation = b
}
};
var U = function (a) {
this.n = this.o = m;
this.g = a;
this.D = new P
},
eb = function (a) {
if (!a.o) return m;
var b = document.createElement("button"),
c = N(a.o),
d = a.o.offsetWidth,
a = a.o.offsetHeight;
navigator.userAgent.match(/iPad/) && (d = 86, a = 40);
document.getElementById("skb") ? (b.className = "lsbb", O(b, {
fontSize: "15px",
background: "url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAAmCAYAAAAFvPEHAAAABGdBTUEAALGPC/xhBQAAAAFzUkdCAK7OHOkAAAAgY0hSTQAAeiYAAICEAAD6AAAAgOgAAHUwAADqYAAAOpgAABdwnLpRPAAAAAZiS0dEAAAAAAAA+UO7fwAAAAlwSFlzAAALEwAACxMBAJqcGAAAAAl2cEFnAAAAJgAAACYAB/nYBgAAADFJREFUCNd9jDEKACAQw0L//17BKW4iR3ErbVL20ihE4EkgdVAIo7swBe6av7+pWYcD6Xg4BFIWHrsAAAAldEVYdGRhdGU6Y3JlYXRlADIwMTEtMTItMTNUMTA6MTE6MjctMDg6MDD1wN6AAAAAJXRFWHRkYXRlOm1vZGlmeQAyMDExLTEyLTEzVDEwOjExOjI3LTA4OjAwhJ1mPAAAAABJRU5ErkJggg==') repeat-x",
color: "#374A82"
}), b.innerHTML = "\u2652", c.y -= 1) : (b.innerHTML = "Defrost", O(b, {
backgroundColor: "#4d90fe",
backgroundImage: "-webkit-,-moz-,-ms-,-o-,,".split(",").join("linear-gradient(top,#4d90fe,#4787ed);"),
filter: "progid:DXImageTransform.Microsoft.gradient(startColorStr='#4d90fe',EndColorStr='#4787ed')",
border: "1px solid #3079ed",
borderRadius: "2px",
webkitBorderRadius: "2px",
mozBorderRadius: "2px",
color: "white",
fontSize: "11px",
fontWeight: "bold",
textAlign: "center",
position: "fixed",
top: c.y + "px",
left: c.x + "px",
width: d + "px",
height: a + "px",
padding: "0 8px",
zIndex: 1201,
opacity: 0
}), 30 < a && O(b, {
fontSize: "15px"
}));
return b
};
U.prototype.qa = function (a) {
var b = this.o = document.getElementById("gbqfb") || document.getElementById("sblsbb") || document.getElementsByName("btnG")[0];
if (this.o) {
this.n = eb(this);
this.D.M = this.n;
Ua(this.D, function () {
b.style.visibility = "hidden"
});
var c = this.o.parentNode;
if (c && "sbds" == c.id) c.style.width = c.offsetWidth + "px";
this.g.k(this.n, "click", a);
document.body.insertBefore(this.n, document.body.firstChild)
}
};
U.prototype.detach = function () {
if (this.o && this.n) this.n.parentNode.removeChild(this.n), this.n = m, this.o.style.visibility = "visible"
};
U.prototype.pa = function () {
if (this.o && this.n) {
var a = N(this.o);
this.n.style.top = a.y + "px";
this.n.style.left = a.x + "px"
}
};
var V = function (a, b) {
this.i = b;
this.g = a;
this.U = this.V = this.a = m;
this.va = {};
this.ua = {};
this.p = m;
this.D = new P;
this.m = m
},
fb = function (a) {
function b(a) {
return d.charAt(a >> 6 & 63) + d.charAt(a & 63)
}
function c(a) {
var c = 0;
0 > a && (c = 32, a = -a);
return b(c | a & 31).charAt(1)
}
for (var d = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_", a = a.i.L, f = [], e = 0, h; h = a[e]; ++e) {
var n = [];
h = h.O;
for (var j = m, t = 0, i; i = h[t]; t++) j && 32 > Math.abs(i[0] - j[0]) && 32 > Math.abs(i[1] - j[1]) ? (j = [i[0] - j[0], i[1] - j[1]], n.push(c(j[0]) + c(j[1]))) : n.push((0 == t ? "" : ";") + (b(i[0]) + b(i[1]))), j = i;
f.push(n.join(""))
}
return "1;" + f.join("!")
},
gb = function (a) {
function b(a) {
var b = String.fromCharCode(a);
return "A" <= b && "Z" >= b ? a - 65 : "a" <= b && "z" >= b ? a - 97 + 26 : "0" <= b && "9" >= b ? a - 48 + 52 : "-" == b ? 62 : "_" == b ? 63 : m
}
function c(a, c) {
var d = b(a.charCodeAt(c)),
e = b(a.charCodeAt(c + 1));
return d === m || e === m ? m : d << 6 | e
}
function d(a, c) {
var d = b(a.charCodeAt(c));
if (d === m) return m;
d & 32 && (d = -(d & 31));
return d
}
var f = /&frostwriting=([A-Za-z0-9-_!;]+)/.exec(window.location.href);
if (!f) return o;
var f = f[1].split("!"),
e = [],
h = 0;
0 < f.length && "1;" == f[0].substr(0, 2) && (f[0] = f[0].substr(2), h = 1);
for (var n = 0, j; j = f[n]; ++n) {
for (var t = new S, i = m, l = 0; l < j.length;) {
var s = o;
if (";" == j.charAt(l)) {
if (0 == h) return o;
l++;
s = k
}
if (0 == h || !i || s) {
if (l + 3 >= j.length) return o;
i = c(j, l);
s = c(j, l + 2);
if (i === m || s === m) return o;
t.ba(i, s);
i = [i, s];
l += 4
} else {
if (l + 1 >= j.length) return o;
var s = d(j, l),
ja = d(j, l + 1);
if (s === m || ja === m) return o;
t.ba(i[0] + s, i[1] + ja);
i = [i[0] + s, i[1] + ja];
l += 2
}
}
e.push(t)
}
cb(a.i, e);
return k
},
hb = function () {
return -1 == window.location.hash.indexOf("&fp=") ? window.location.href : window.location.protocol + "//" + window.location.host + "/search?" + window.location.hash.substr(1).replace(/&fp=[0-9a-z]+/, "")
};
V.prototype.wa = function (a) {
a.stopPropagation();
a.preventDefault();
return o
};
V.prototype.Fa = function (a) {
var b = fb(this),
c = hb() + "&frostwriting=" + b;
if ("1;" == b) W(this, hb(), "Draw something on your window. #letitsnow");
else if (480 < c.length) {
if (this.m !== m) clearTimeout(this.m), this.m = m;
google.letitsnowGCO = v(this.Na, this);
ib(c);
this.m = setTimeout(v(function () {
W(this, window.location.href, "My drawing is too complex to share, but you should try this out and have fun, anyway. #letitsnow");
this.m = m
}, this), 5E3)
} else W(this, c, "Check out what I drew. #letitsnow");
return this.wa(a)
};
var W = function (a, b, c) {
if (a.m !== m) clearTimeout(a.m), a.m = m;
gbar.asmc(function () {
return {
items: [{
properties: {
url: [b],
name: ["Google - Let it snow!"],
image: ["http://www.google.com/images/logos/google_logo_41.png"],
description: [c]
}
}]
}
});
if (document.createEvent) {
var d = document.createEvent("MouseEvents");
d.initEvent("click", k, o);
a.V.dispatchEvent(d)
} else a.V.fireEvent && a.V.fireEvent("onclick")
};
V.prototype.qa = function () {
this.a = document.getElementById("gbgs3");
this.U = document.getElementById("gbwc");
this.V = document.getElementById("gbg3");
if (this.a && this.U && this.V) {
this.p = document.createElement("div");
O(this.p, {
height: this.a.offsetHeight + "px",
width: this.a.offsetWidth + "px"
});
this.a.parentNode.insertBefore(this.p, this.a);
var a = N(this.a);
this.va = O(this.a, {
font: "13px/27px Arial,sans-serif",
left: a.x + "px",
position: "fixed",
top: a.y - this.a.offsetHeight + "px",
zIndex: 1201
});
this.ua = O(this.U, {
background: "#fff",
zIndex: 1201
});
this.a.parentNode.removeChild(this.a);
document.body.appendChild(this.a);
"SPAN" == this.a.tagName ? this.a.style.lineHeight = "20px" : this.D.M = this.a;
this.g.k(this.a, "click", v(this.Fa, this));
this.g.k(this.a, "mousedown", v(this.wa, this))
}
};
V.prototype.detach = function () {
if (this.a && this.U) {
this.m !== m && clearTimeout(this.m);
O(this.a, this.va);
O(this.U, this.ua);
this.D.restore();
for (var a = this.g, b = this.a, c = 0; c < a.H.length; ++c) {
var d = a.H[c];
d && d[0] == b && (Wa.apply(m, d), a.H[c] = m)
}
this.a.parentNode.removeChild(this.a);
this.p.parentNode.insertBefore(this.a, this.p);
this.p.parentNode.removeChild(this.p);
this.p = this.a = m
}
};
V.prototype.pa = function () {
if (this.a && this.p) this.a.style.left = N(this.p).x + "px"
};
V.prototype.Na = function (a) {
a && "OK" == a.status && !a.error && a.id && (clearTimeout(this.m), W(this, a.id, "Check out what I drew. #letitsnow"))
};
var ib = function (a) {
var a = a.replace(window.location.host, "www.google.com"),
b = document.createElement("script");
b.src = "//google-doodles.appspot.com/?callback=google.letitsnowGCO&url=" + encodeURIComponent(a);
document.body.appendChild(b)
};
var jb = Math.floor(60),
kb = Math.floor(300),
X = function () {
this.J = this.i = this.K = this.h = this.A = m;
this.Z = this.ia = o;
this.g = this.F = m;
this.ha = o;
this.T = 0;
this.ja = this.R = m;
this.Da = window.opera || navigator.userAgent.match(/MSIE/) ? jb : kb
},
Y = "goog.egg.snowyfog.Snowyfog".split("."),
Z = q;
!(Y[0] in Z) && Z.execScript && Z.execScript("var " + Y[0]);
for (var $; Y.length && ($ = Y.shift());)!Y.length && X !== g ? Z[$] = X : Z = Z[$] ? Z[$] : Z[$] = {};
X.prototype.init = function () {
var a = this,
b = function () {
document.getElementById("snfloader_script") && (!document.getElementById("foot") && !document.getElementById("bfoot") ? window.setTimeout(b, 50) : (google.rein && google.dstr && (google.rein.push(v(a.Aa, a)), google.dstr.push(v(a.Pa, a))), a.Aa()))
};
b()
};
X.prototype.init = X.prototype.init;
X.prototype.Aa = function () {
if (!google || !google.snowyfogInited) {
google.snowyfogInited = k;
var a = document.createElement("canvas");
document.body.insertBefore(a, document.body.firstChild);
this.h = a;
O(this.h, {
pointerEvents: "none",
position: "fixed",
top: "0",
left: "0",
zIndex: 1200
});
this.h.width = window.innerWidth;
this.h.height = window.innerHeight;
this.T = 0;
this.ha = this.Z = this.ia = o;
this.g = new Va;
this.A = document.createElement("div");
a = window.opera || navigator.userAgent.match(/MSIE/) ? 0 : 800;
O(this.A, {
pointerEvents: "none",
position: "absolute",
zIndex: a,
width: document.body.clientWidth + "px",
height: Math.max(window.innerHeight, document.body.clientHeight) + "px",
overflow: "hidden"
});
document.body.insertBefore(this.A, document.body.firstChild);
this.K = new R(this.A);
this.i = new Ya(this.g, this.h, 0, 0);
this.F = new V(this.g, this.i);
this.J = new U(this.g);
a = v(this.K.Ca, this.K);
this.g.k(window, "resize", v(this.N, this));
this.g.k(window, "deviceorientation", a);
this.g.k(window, "MozOrientation", a);
this.R = this.h.getContext("2d");
gb(this.F) && (ab(this.i, this.R), lb(this));
this.ja = v(this.Ba, this);
window.setTimeout(this.ja, 50)
}
};
X.prototype.Pa = function () {
this.ha = k;
for (var a = this.g, b = 0; b < a.H.length; ++b) {
var c = a.H[b];
c && (Wa.apply(m, c), a.H[b] = m)
}
this.J.detach();
this.F.detach();
if (this.h) this.h.parentNode.removeChild(this.h), this.h = m;
if (this.A) this.A.parentNode.removeChild(this.A), this.A = m
};
var lb = function (a) {
if (!a.ia) a.ia = k, a.h.style.pointerEvents = "auto", Ta(), db(a.i), a.F.qa(), a.J.qa(v(function (a) {
this.Z = o;
this.i = m;
this.h && this.h.parentNode.removeChild(this.h);
this.h = m;
this.J.detach();
this.F.detach();
a.stopPropagation()
}, a))
},
mb = function (a) {
a.K.s();
if (a.Z) {
var b = a.i;
if (!(580.8 > b.S) && !(b.$ || 88 < b.ga)) {
for (var c = b.S = 0, d = 0; 66 > d; d++) for (var f = 0; 88 > f; f++) b.w[d][f] += b.G[d][f], 3.5 <= b.w[d][f] && c++;
b.ga++;
if (c >= 70.4 * 66) b.$ = k;
else for (d = 0; 66 > d; d++) for (f = 0; 88 > f; f++) if (c = 4 - b.w[d][f], c > 4 * Math.random() && 0.7 < Math.random()) {
var e = Math.min(1, 3 * $a(b, f, d)) * Math.random();
b.G[d][f] = c * e
} else b.G[d][f] = 0
}
a.i.s(a.R);
a.J.D.s();
a.F.D.s()
}
};
X.prototype.Ba = function () {
if (!this.ha) {
window.setTimeout(this.ja, 50);
this.T++;
if (this.T == jb) this.Z = k;
this.T == this.Da && lb(this);
mb(this)
}
};
X.prototype.N = function () {
this.K && this.K.N(document.body.offsetWidth, Math.max(document.body.offsetHeight, window.innerHeight));
this.i && (!navigator.userAgent.match(/iPad/) || this.T > jb) && this.i.N(window.innerWidth, window.innerHeight, this.R);
lb(this);
this.J.pa();
this.F.pa();
this.A && this.R && mb(this)
};
X.prototype.resize = X.prototype.N;
})(); |
import HomeRoute from 'routes/Home';
describe('(Route) Home', () => {
let _component;
beforeEach(() => {
_component = HomeRoute.component();
});
it('Should return a route configuration object', () => {
expect(typeof HomeRoute).to.equal('object');
});
it('Should define a route component', () => {
expect(_component.type).to.equal('div');
});
});
|
import 'docs/src/modules/components/bootstrap';
// --- Post bootstrap -----
import React from 'react';
import MarkdownDocs from 'docs/src/modules/components/MarkdownDocs';
import markdown from './input.md';
function Page() {
return <MarkdownDocs markdown={markdown} />;
}
export default Page;
|
var searchData=
[
['clear',['clear',['../d8/d84/a00001.html#a11dc3b617f2fedbb3b499971493b9c4f',1,'ArrayBase']]]
];
|
/*jslint node: true, vars: true, plusplus: true, devel: true, nomen: true, regexp: true, indent: 2, maxerr: 50*/
/*global define, $, brackets, Mustache, window, appshell*/
define(function (require, exports, module) {
"use strict";
// HEADER >>
var NodeConnection = brackets.getModule("utils/NodeConnection"),
Menus = brackets.getModule("command/Menus"),
CommandManager = brackets.getModule("command/CommandManager"),
Commands = brackets.getModule("command/Commands"),
PreferencesManager = brackets.getModule("preferences/PreferencesManager"),
_ = brackets.getModule("thirdparty/lodash"),
KeyBindingManager = brackets.getModule("command/KeyBindingManager");
var ExtensionDiagnosis = require("modules/ExtensionDiagnosis"),
Log = require("modules/Log"),
Panel = require("modules/Panel"),
FileTreeView = require("modules/FileTreeView"),
Strings = require("strings");
var treeViewContextMenu = null;
var _nodeConnection = null;
var showMainPanel,
initTreeViewContextMenu,
setRootMenu,
setDebugMenu,
reloadBrackets,
treeViewContextMenuState;
var _disableTreeViewContextMenuAllItem;
//<<
var ContextMenuIds = {
TREEVIEW_CTX_MENU: "kohei-synapse-treeview-context-menu"
};
var ContextMenuCommandIds = {
SYNAPSE_FILE_NEW: "kohei.synapse.file_new",
SYNAPSE_DIRECTORY_NEW: "kohei.synapse.directory_new",
SYNAPSE_FILE_REFRESH: "kohei.synapse.file_refresh",
SYNAPSE_FILE_RENAME: "kohei.synapse.file_rename",
SYNAPSE_DELETE: "kohei.synapse.delete"
};
var MenuText = {
SYNAPSE_CTX_FILE_NEW: Strings.SYNAPSE_CTX_FILE_NEW,
SYNAPSE_CTX_DIRECTORY_NEW: Strings.SYNAPSE_CTX_DIRECTORY_NEW,
SYNAPSE_CTX_FILE_REFRESH: Strings.SYNAPSE_CTX_FILE_REFRESH,
SYNAPSE_CTX_FILE_RENAME: Strings.SYNAPSE_CTX_FILE_RENAME,
SYNAPSE_CTX_DELETE: Strings.SYNAPSE_CTX_DELETE
};
var Open_TreeView_Context_Menu_On_Directory_State = [
ContextMenuCommandIds.SYNAPSE_FILE_NEW,
ContextMenuCommandIds.SYNAPSE_DIRECTORY_NEW,
ContextMenuCommandIds.SYNAPSE_DELETE,
ContextMenuCommandIds.SYNAPSE_FILE_REFRESH,
ContextMenuCommandIds.SYNAPSE_FILE_RENAME
];
var Open_TreeView_Context_Menu_On_Linked_Directory_State = [
ContextMenuCommandIds.SYNAPSE_FILE_NEW,
ContextMenuCommandIds.SYNAPSE_DIRECTORY_NEW,
ContextMenuCommandIds.SYNAPSE_DELETE,
ContextMenuCommandIds.SYNAPSE_FILE_REFRESH
];
var Open_TreeView_Context_Menu_On_File_State = [
ContextMenuCommandIds.SYNAPSE_FILE_RENAME,
ContextMenuCommandIds.SYNAPSE_DELETE
];
var Open_TreeView_Context_Menu_On_Linked_File_State = [
ContextMenuCommandIds.SYNAPSE_FILE_RENAME,
ContextMenuCommandIds.SYNAPSE_DELETE
];
var Open_TreeView_Context_Menu_On_Root_State = [
ContextMenuCommandIds.SYNAPSE_FILE_NEW,
ContextMenuCommandIds.SYNAPSE_DIRECTORY_NEW,
ContextMenuCommandIds.SYNAPSE_FILE_REFRESH
];
showMainPanel = function () {
CommandManager.execute("kohei.synapse.mainPanel");
};
treeViewContextMenuState = function (entity) {
_disableTreeViewContextMenuAllItem();
if (entity.class === "treeview-root") {
Open_TreeView_Context_Menu_On_Root_State.forEach(function (id) {
CommandManager.get(id).setEnabled(true);
});
return;
}
if (entity.class === "treeview-directory") {
Open_TreeView_Context_Menu_On_Directory_State.forEach(function (id) {
CommandManager.get(id).setEnabled(true);
});
return;
} else
if (entity.class === "treeview-ldirectory") {
Open_TreeView_Context_Menu_On_Linked_Directory_State.forEach(function (id) {
CommandManager.get(id).setEnabled(true);
});
return;
} else
if (entity.class === "treeview-file") {
Open_TreeView_Context_Menu_On_File_State.forEach(function (id) {
CommandManager.get(id).setEnabled(true);
});
return;
}
};
setRootMenu = function (domain) {
var menu = CommandManager.register(
"Synapse",
"kohei.synapse.mainPanel",
Panel.showMain);
var topMenu = Menus.getMenu(Menus.AppMenuBar.VIEW_MENU);
topMenu.addMenuDivider();
topMenu.addMenuItem(menu, {
key: "Ctrl-Shift-Alt-Enter",
displayKey: "Ctrl-Shift-Alt-Enter"
});
//For Debug >
//Panel.showMain();
setDebugMenu();
return new $.Deferred().resolve(domain).promise();
};
setDebugMenu = function () {
var menu = CommandManager.register(
"Reload App wiz Node",
"kohei.syanpse.reloadBrackets",
reloadBrackets);
var topMenu = Menus.getMenu(Menus.AppMenuBar.VIEW_MENU);
topMenu.addMenuDivider();
topMenu.addMenuItem(menu, {
key: "Ctrl-Shift-F6",
displeyKey: "Ctrl-Shift-F6"
});
};
reloadBrackets = function () {
try {
_nodeConnection.domains.base.restartNode();
CommandManager.execute(Commands.APP_RELOAD);
} catch (e) {
console.log("SYNAPSE ERROR - Failed trying to restart Node", e);
}
};
initTreeViewContextMenu = function () {
var d = new $.Deferred();
CommandManager
.register(MenuText.SYNAPSE_CTX_FILE_REFRESH, ContextMenuCommandIds.SYNAPSE_FILE_REFRESH, FileTreeView.refresh);
CommandManager
.register(MenuText.SYNAPSE_CTX_FILE_RENAME, ContextMenuCommandIds.SYNAPSE_FILE_RENAME, FileTreeView.rename);
CommandManager
.register(MenuText.SYNAPSE_CTX_FILE_NEW, ContextMenuCommandIds.SYNAPSE_FILE_NEW, FileTreeView.newFile);
CommandManager
.register(MenuText.SYNAPSE_CTX_DIRECTORY_NEW, ContextMenuCommandIds.SYNAPSE_DIRECTORY_NEW, FileTreeView.newDirectory);
CommandManager
.register(MenuText.SYNAPSE_CTX_DELETE, ContextMenuCommandIds.SYNAPSE_DELETE, FileTreeView.removeFile);
treeViewContextMenu = Menus.registerContextMenu(ContextMenuIds.TREEVIEW_CTX_MENU);
treeViewContextMenu
.addMenuItem(ContextMenuCommandIds.SYNAPSE_FILE_REFRESH);
treeViewContextMenu
.addMenuItem(ContextMenuCommandIds.SYNAPSE_FILE_RENAME, null, Menus.LAST, null);
treeViewContextMenu
.addMenuDivider();
treeViewContextMenu
.addMenuItem(ContextMenuCommandIds.SYNAPSE_FILE_NEW, null, Menus.LAST, null);
treeViewContextMenu
.addMenuItem(ContextMenuCommandIds.SYNAPSE_DIRECTORY_NEW, null, Menus.LAST, null);
treeViewContextMenu
.addMenuDivider();
treeViewContextMenu
.addMenuItem(ContextMenuCommandIds.SYNAPSE_DELETE, null, Menus.LAST, null);
$("#synapse-treeview-container").contextmenu(function (e) {
FileTreeView.onTreeViewContextMenu(e, treeViewContextMenu);
});
return d.resolve().promise();
};
/* Private Methods */
_disableTreeViewContextMenuAllItem = function () {
if (treeViewContextMenu === null) {
return;
}
_.forIn(ContextMenuCommandIds, function (val, key) {
CommandManager.get(val).setEnabled(false);
});
};
/* for Debug */
_nodeConnection = new NodeConnection();
_nodeConnection.connect(true);
exports.showMainPanel = showMainPanel;
exports.setRootMenu = setRootMenu;
exports.initTreeViewContextMenu = initTreeViewContextMenu;
exports.ContextMenuCommandIds = ContextMenuCommandIds;
exports.ContextMenuIds = ContextMenuIds;
exports.treeViewContextMenuState = treeViewContextMenuState;
exports.getModuleName = function () {
return module.id;
};
});
|
const ASSETS_MODS_LENGTH = 13;//'/assets/mods/'.length;
const CONTENT_TYPES = {
'css': 'text/css',
'js': 'text/javascript',
'json': 'application/json',
'png': 'image/png',
'jpg': 'image/jpeg',
'jpeg': 'image/jpeg',
'html': 'text/html',
'htm': 'text/html'
};
/**
* @type {Map<string, JSZip>}
*/
const jszipCache = new Map();
//Not exported because serviceworkers can't use es6 modules
// eslint-disable-next-line no-unused-vars
class PackedManager {
/**
*
* @param {string} url
*/
async get(url) {
try {
const zip = await this._openZip(url);
const file = zip.file(this._assetPath(url));
if (file === null) {
return new Response(new Blob(), {
status: 404,
statusText: 'not found'
});
}
return new Response(await file.async('blob'), {
headers: {
'Content-Type': this._contentType(url)
},
status: 200,
statusText: 'ok'
});
} catch (e) {
console.error('An error occured while reading a packed mod', e);
return e;
}
}
/**
*
* @param {string} url
* @returns {Promise<string[]>}
*/
async getFiles(url) {
const zip = await this._openZip(url);
const folder = this._openFolder(zip, this._assetPath(url));
const result = [];
folder.forEach((relativePath, file) => {
if (!file.dir) {
result.push(relativePath);
}
});
return result;
}
/**
*
* @param {string} url
* @returns {Promise<boolean>}
*/
async isDirectory(url) {
const zip = await this._openZip(url);
const file = zip.file(this._assetPath(url));
return file && file.dir;
}
/**
*
* @param {string} url
* @returns {Promise<boolean>}
*/
async isFile(url) {
const zip = await this._openZip(url);
const file = zip.file(this._assetPath(url));
return !!file;
}
/**
*
* @param {string} url
*/
packedName(url) {
url = this._normalize(url);
return decodeURIComponent(url.substring(ASSETS_MODS_LENGTH, url.indexOf('/', ASSETS_MODS_LENGTH)));
}
/**
*
* @param {string} url
*/
async _openZip(url) {
const zip = this._zipPath(url);
const cached = jszipCache.get(zip);
if (cached) {
return cached;
}
const request = new Request('http://' + location.hostname + '.cc' + zip);
const cache = await caches.open('zips');
let response = await cache.match(request);
if (!response) {
response = await fetch(zip);
cache.put(request, response.clone());
}
const result = await JSZip.loadAsync(response.blob());
jszipCache.set(zip, result);
return result;
}
/**
*
* @param {JSZip} root
* @param {string} path
*/
_openFolder(root, path) {
const folders = path.split(/\//g);
for (const folder of folders) {
root = root.folder(folder);
}
return root;
}
/**
* @param {string} url
* @returns {string}
*/
_contentType(url) {
url = this._normalize(url);
return CONTENT_TYPES[url.substr(url.lastIndexOf('.') + 1)] || 'text/plain';
}
/**
*
* @param {string} url
*/
_zipPath(url) {
url = this._normalize(url);
return url.substr(0, url.indexOf('/', ASSETS_MODS_LENGTH));
}
/**
*
* @param {string} url
*/
_assetPath(url) {
url = this._normalize(url);
return url.substr(url.indexOf('/', ASSETS_MODS_LENGTH) + 1);
}
/**
*
* @param {string} url
*/
_normalize(url) {
url = url.replace(/\\/g, '/').replace(/\/\//, '/');
//TODO: resolve absolute paths
if (!url.startsWith('/')) {
url = '/' + url;
}
if (url.startsWith('/ccloader')) {
url = url.substr(9); // '/ccloader'.length
}
return url;
}
}
|
/* micropolisJS. Adapted by Graeme McCutcheon from Micropolis.
*
* This code is released under the GNU GPL v3, with some additional terms.
* Please see the files LICENSE and COPYING for details. Alternatively,
* consult http://micropolisjs.graememcc.co.uk/LICENSE and
* http://micropolisjs.graememcc.co.uk/COPYING
*
*/
Micro.GameTools = function (map) {
return {
airport: new Micro.BuildingTool(10000, Tile.AIRPORT, map, 6, false),
bulldozer: new Micro.BulldozerTool(map),
coal: new Micro.BuildingTool(3000, Tile.POWERPLANT, map, 4, false),
commercial: new Micro.BuildingTool(100, Tile.COMCLR, map, 3, false),
fire: new Micro.BuildingTool(500, Tile.FIRESTATION, map, 3, false),
industrial: new Micro.BuildingTool(100, Tile.INDCLR, map, 3, false),
nuclear: new Micro.BuildingTool(5000, Tile.NUCLEAR, map, 4, true),
park: new Micro.ParkTool(map),
police: new Micro.BuildingTool(500, Tile.POLICESTATION, map, 3, false),
port: new Micro.BuildingTool(3000, Tile.PORT, map, 4, false),
rail: new Micro.RailTool(map),
residential: new Micro.BuildingTool(100, Tile.FREEZ, map, 3, false),
road: new Micro.RoadTool(map),
query: new Micro.QueryTool(map),
stadium: new Micro.BuildingTool(5000, Tile.STADIUM, map, 4, false),
wire: new Micro.WireTool(map),
};
}; |
export { default as createShallow } from './createShallow';
export { default as createMount } from './createMount';
export { default as createRender } from './createRender';
export { default as findOutermostIntrinsic, wrapsIntrinsicElement } from './findOutermostIntrinsic';
export { default as getClasses } from './getClasses';
export { default as unwrap } from './unwrap';
|
var expect = require("chai").expect;
var reindeerRace = require("../../src/day-14/reindeer-race");
describe("--- Day 14: (1/2) distance traveled --- ", () => {
it("counts the distance traveled after 1000s", () => {
var reindeerSpecs = [
"Comet can fly 14 km/s for 10 seconds, but then must rest for 127 seconds.",
"Dancer can fly 16 km/s for 11 seconds, but then must rest for 162 seconds."
];
expect(reindeerRace.race(reindeerSpecs, 1000).winnerByDistance.distanceTraveled).to.equal(1120);
});
});
describe("--- Day 14: (2/2) points awarded --- ", () => {
it("counts the points awarded for being in the lead after 1000s", () => {
var reindeerSpecs = [
"Comet can fly 14 km/s for 10 seconds, but then must rest for 127 seconds.",
"Dancer can fly 16 km/s for 11 seconds, but then must rest for 162 seconds."
];
expect(reindeerRace.race(reindeerSpecs, 1000).winnerByPoints.pointsAwarded).to.equal(689);
});
});
|
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var jsdom = require("jsdom");
var chai_1 = require("chai");
var ColorManager_1 = require("./ColorManager");
describe('ColorManager', function () {
var cm;
var dom;
var document;
var window;
beforeEach(function () {
dom = new jsdom.JSDOM('');
window = dom.window;
document = window.document;
window.HTMLCanvasElement.prototype.getContext = function () { return ({
createLinearGradient: function () {
return null;
},
fillRect: function () { },
getImageData: function () {
return { data: [0, 0, 0, 0xFF] };
}
}); };
cm = new ColorManager_1.ColorManager(document, false);
});
describe('constructor', function () {
it('should fill all colors with values', function () {
for (var _i = 0, _a = Object.keys(cm.colors); _i < _a.length; _i++) {
var key = _a[_i];
if (key !== 'ansi') {
chai_1.assert.ok(cm.colors[key].css.length >= 7);
}
}
chai_1.assert.equal(cm.colors.ansi.length, 256);
});
it('should fill 240 colors with expected values', function () {
chai_1.assert.equal(cm.colors.ansi[16].css, '#000000');
chai_1.assert.equal(cm.colors.ansi[17].css, '#00005f');
chai_1.assert.equal(cm.colors.ansi[18].css, '#000087');
chai_1.assert.equal(cm.colors.ansi[19].css, '#0000af');
chai_1.assert.equal(cm.colors.ansi[20].css, '#0000d7');
chai_1.assert.equal(cm.colors.ansi[21].css, '#0000ff');
chai_1.assert.equal(cm.colors.ansi[22].css, '#005f00');
chai_1.assert.equal(cm.colors.ansi[23].css, '#005f5f');
chai_1.assert.equal(cm.colors.ansi[24].css, '#005f87');
chai_1.assert.equal(cm.colors.ansi[25].css, '#005faf');
chai_1.assert.equal(cm.colors.ansi[26].css, '#005fd7');
chai_1.assert.equal(cm.colors.ansi[27].css, '#005fff');
chai_1.assert.equal(cm.colors.ansi[28].css, '#008700');
chai_1.assert.equal(cm.colors.ansi[29].css, '#00875f');
chai_1.assert.equal(cm.colors.ansi[30].css, '#008787');
chai_1.assert.equal(cm.colors.ansi[31].css, '#0087af');
chai_1.assert.equal(cm.colors.ansi[32].css, '#0087d7');
chai_1.assert.equal(cm.colors.ansi[33].css, '#0087ff');
chai_1.assert.equal(cm.colors.ansi[34].css, '#00af00');
chai_1.assert.equal(cm.colors.ansi[35].css, '#00af5f');
chai_1.assert.equal(cm.colors.ansi[36].css, '#00af87');
chai_1.assert.equal(cm.colors.ansi[37].css, '#00afaf');
chai_1.assert.equal(cm.colors.ansi[38].css, '#00afd7');
chai_1.assert.equal(cm.colors.ansi[39].css, '#00afff');
chai_1.assert.equal(cm.colors.ansi[40].css, '#00d700');
chai_1.assert.equal(cm.colors.ansi[41].css, '#00d75f');
chai_1.assert.equal(cm.colors.ansi[42].css, '#00d787');
chai_1.assert.equal(cm.colors.ansi[43].css, '#00d7af');
chai_1.assert.equal(cm.colors.ansi[44].css, '#00d7d7');
chai_1.assert.equal(cm.colors.ansi[45].css, '#00d7ff');
chai_1.assert.equal(cm.colors.ansi[46].css, '#00ff00');
chai_1.assert.equal(cm.colors.ansi[47].css, '#00ff5f');
chai_1.assert.equal(cm.colors.ansi[48].css, '#00ff87');
chai_1.assert.equal(cm.colors.ansi[49].css, '#00ffaf');
chai_1.assert.equal(cm.colors.ansi[50].css, '#00ffd7');
chai_1.assert.equal(cm.colors.ansi[51].css, '#00ffff');
chai_1.assert.equal(cm.colors.ansi[52].css, '#5f0000');
chai_1.assert.equal(cm.colors.ansi[53].css, '#5f005f');
chai_1.assert.equal(cm.colors.ansi[54].css, '#5f0087');
chai_1.assert.equal(cm.colors.ansi[55].css, '#5f00af');
chai_1.assert.equal(cm.colors.ansi[56].css, '#5f00d7');
chai_1.assert.equal(cm.colors.ansi[57].css, '#5f00ff');
chai_1.assert.equal(cm.colors.ansi[58].css, '#5f5f00');
chai_1.assert.equal(cm.colors.ansi[59].css, '#5f5f5f');
chai_1.assert.equal(cm.colors.ansi[60].css, '#5f5f87');
chai_1.assert.equal(cm.colors.ansi[61].css, '#5f5faf');
chai_1.assert.equal(cm.colors.ansi[62].css, '#5f5fd7');
chai_1.assert.equal(cm.colors.ansi[63].css, '#5f5fff');
chai_1.assert.equal(cm.colors.ansi[64].css, '#5f8700');
chai_1.assert.equal(cm.colors.ansi[65].css, '#5f875f');
chai_1.assert.equal(cm.colors.ansi[66].css, '#5f8787');
chai_1.assert.equal(cm.colors.ansi[67].css, '#5f87af');
chai_1.assert.equal(cm.colors.ansi[68].css, '#5f87d7');
chai_1.assert.equal(cm.colors.ansi[69].css, '#5f87ff');
chai_1.assert.equal(cm.colors.ansi[70].css, '#5faf00');
chai_1.assert.equal(cm.colors.ansi[71].css, '#5faf5f');
chai_1.assert.equal(cm.colors.ansi[72].css, '#5faf87');
chai_1.assert.equal(cm.colors.ansi[73].css, '#5fafaf');
chai_1.assert.equal(cm.colors.ansi[74].css, '#5fafd7');
chai_1.assert.equal(cm.colors.ansi[75].css, '#5fafff');
chai_1.assert.equal(cm.colors.ansi[76].css, '#5fd700');
chai_1.assert.equal(cm.colors.ansi[77].css, '#5fd75f');
chai_1.assert.equal(cm.colors.ansi[78].css, '#5fd787');
chai_1.assert.equal(cm.colors.ansi[79].css, '#5fd7af');
chai_1.assert.equal(cm.colors.ansi[80].css, '#5fd7d7');
chai_1.assert.equal(cm.colors.ansi[81].css, '#5fd7ff');
chai_1.assert.equal(cm.colors.ansi[82].css, '#5fff00');
chai_1.assert.equal(cm.colors.ansi[83].css, '#5fff5f');
chai_1.assert.equal(cm.colors.ansi[84].css, '#5fff87');
chai_1.assert.equal(cm.colors.ansi[85].css, '#5fffaf');
chai_1.assert.equal(cm.colors.ansi[86].css, '#5fffd7');
chai_1.assert.equal(cm.colors.ansi[87].css, '#5fffff');
chai_1.assert.equal(cm.colors.ansi[88].css, '#870000');
chai_1.assert.equal(cm.colors.ansi[89].css, '#87005f');
chai_1.assert.equal(cm.colors.ansi[90].css, '#870087');
chai_1.assert.equal(cm.colors.ansi[91].css, '#8700af');
chai_1.assert.equal(cm.colors.ansi[92].css, '#8700d7');
chai_1.assert.equal(cm.colors.ansi[93].css, '#8700ff');
chai_1.assert.equal(cm.colors.ansi[94].css, '#875f00');
chai_1.assert.equal(cm.colors.ansi[95].css, '#875f5f');
chai_1.assert.equal(cm.colors.ansi[96].css, '#875f87');
chai_1.assert.equal(cm.colors.ansi[97].css, '#875faf');
chai_1.assert.equal(cm.colors.ansi[98].css, '#875fd7');
chai_1.assert.equal(cm.colors.ansi[99].css, '#875fff');
chai_1.assert.equal(cm.colors.ansi[100].css, '#878700');
chai_1.assert.equal(cm.colors.ansi[101].css, '#87875f');
chai_1.assert.equal(cm.colors.ansi[102].css, '#878787');
chai_1.assert.equal(cm.colors.ansi[103].css, '#8787af');
chai_1.assert.equal(cm.colors.ansi[104].css, '#8787d7');
chai_1.assert.equal(cm.colors.ansi[105].css, '#8787ff');
chai_1.assert.equal(cm.colors.ansi[106].css, '#87af00');
chai_1.assert.equal(cm.colors.ansi[107].css, '#87af5f');
chai_1.assert.equal(cm.colors.ansi[108].css, '#87af87');
chai_1.assert.equal(cm.colors.ansi[109].css, '#87afaf');
chai_1.assert.equal(cm.colors.ansi[110].css, '#87afd7');
chai_1.assert.equal(cm.colors.ansi[111].css, '#87afff');
chai_1.assert.equal(cm.colors.ansi[112].css, '#87d700');
chai_1.assert.equal(cm.colors.ansi[113].css, '#87d75f');
chai_1.assert.equal(cm.colors.ansi[114].css, '#87d787');
chai_1.assert.equal(cm.colors.ansi[115].css, '#87d7af');
chai_1.assert.equal(cm.colors.ansi[116].css, '#87d7d7');
chai_1.assert.equal(cm.colors.ansi[117].css, '#87d7ff');
chai_1.assert.equal(cm.colors.ansi[118].css, '#87ff00');
chai_1.assert.equal(cm.colors.ansi[119].css, '#87ff5f');
chai_1.assert.equal(cm.colors.ansi[120].css, '#87ff87');
chai_1.assert.equal(cm.colors.ansi[121].css, '#87ffaf');
chai_1.assert.equal(cm.colors.ansi[122].css, '#87ffd7');
chai_1.assert.equal(cm.colors.ansi[123].css, '#87ffff');
chai_1.assert.equal(cm.colors.ansi[124].css, '#af0000');
chai_1.assert.equal(cm.colors.ansi[125].css, '#af005f');
chai_1.assert.equal(cm.colors.ansi[126].css, '#af0087');
chai_1.assert.equal(cm.colors.ansi[127].css, '#af00af');
chai_1.assert.equal(cm.colors.ansi[128].css, '#af00d7');
chai_1.assert.equal(cm.colors.ansi[129].css, '#af00ff');
chai_1.assert.equal(cm.colors.ansi[130].css, '#af5f00');
chai_1.assert.equal(cm.colors.ansi[131].css, '#af5f5f');
chai_1.assert.equal(cm.colors.ansi[132].css, '#af5f87');
chai_1.assert.equal(cm.colors.ansi[133].css, '#af5faf');
chai_1.assert.equal(cm.colors.ansi[134].css, '#af5fd7');
chai_1.assert.equal(cm.colors.ansi[135].css, '#af5fff');
chai_1.assert.equal(cm.colors.ansi[136].css, '#af8700');
chai_1.assert.equal(cm.colors.ansi[137].css, '#af875f');
chai_1.assert.equal(cm.colors.ansi[138].css, '#af8787');
chai_1.assert.equal(cm.colors.ansi[139].css, '#af87af');
chai_1.assert.equal(cm.colors.ansi[140].css, '#af87d7');
chai_1.assert.equal(cm.colors.ansi[141].css, '#af87ff');
chai_1.assert.equal(cm.colors.ansi[142].css, '#afaf00');
chai_1.assert.equal(cm.colors.ansi[143].css, '#afaf5f');
chai_1.assert.equal(cm.colors.ansi[144].css, '#afaf87');
chai_1.assert.equal(cm.colors.ansi[145].css, '#afafaf');
chai_1.assert.equal(cm.colors.ansi[146].css, '#afafd7');
chai_1.assert.equal(cm.colors.ansi[147].css, '#afafff');
chai_1.assert.equal(cm.colors.ansi[148].css, '#afd700');
chai_1.assert.equal(cm.colors.ansi[149].css, '#afd75f');
chai_1.assert.equal(cm.colors.ansi[150].css, '#afd787');
chai_1.assert.equal(cm.colors.ansi[151].css, '#afd7af');
chai_1.assert.equal(cm.colors.ansi[152].css, '#afd7d7');
chai_1.assert.equal(cm.colors.ansi[153].css, '#afd7ff');
chai_1.assert.equal(cm.colors.ansi[154].css, '#afff00');
chai_1.assert.equal(cm.colors.ansi[155].css, '#afff5f');
chai_1.assert.equal(cm.colors.ansi[156].css, '#afff87');
chai_1.assert.equal(cm.colors.ansi[157].css, '#afffaf');
chai_1.assert.equal(cm.colors.ansi[158].css, '#afffd7');
chai_1.assert.equal(cm.colors.ansi[159].css, '#afffff');
chai_1.assert.equal(cm.colors.ansi[160].css, '#d70000');
chai_1.assert.equal(cm.colors.ansi[161].css, '#d7005f');
chai_1.assert.equal(cm.colors.ansi[162].css, '#d70087');
chai_1.assert.equal(cm.colors.ansi[163].css, '#d700af');
chai_1.assert.equal(cm.colors.ansi[164].css, '#d700d7');
chai_1.assert.equal(cm.colors.ansi[165].css, '#d700ff');
chai_1.assert.equal(cm.colors.ansi[166].css, '#d75f00');
chai_1.assert.equal(cm.colors.ansi[167].css, '#d75f5f');
chai_1.assert.equal(cm.colors.ansi[168].css, '#d75f87');
chai_1.assert.equal(cm.colors.ansi[169].css, '#d75faf');
chai_1.assert.equal(cm.colors.ansi[170].css, '#d75fd7');
chai_1.assert.equal(cm.colors.ansi[171].css, '#d75fff');
chai_1.assert.equal(cm.colors.ansi[172].css, '#d78700');
chai_1.assert.equal(cm.colors.ansi[173].css, '#d7875f');
chai_1.assert.equal(cm.colors.ansi[174].css, '#d78787');
chai_1.assert.equal(cm.colors.ansi[175].css, '#d787af');
chai_1.assert.equal(cm.colors.ansi[176].css, '#d787d7');
chai_1.assert.equal(cm.colors.ansi[177].css, '#d787ff');
chai_1.assert.equal(cm.colors.ansi[178].css, '#d7af00');
chai_1.assert.equal(cm.colors.ansi[179].css, '#d7af5f');
chai_1.assert.equal(cm.colors.ansi[180].css, '#d7af87');
chai_1.assert.equal(cm.colors.ansi[181].css, '#d7afaf');
chai_1.assert.equal(cm.colors.ansi[182].css, '#d7afd7');
chai_1.assert.equal(cm.colors.ansi[183].css, '#d7afff');
chai_1.assert.equal(cm.colors.ansi[184].css, '#d7d700');
chai_1.assert.equal(cm.colors.ansi[185].css, '#d7d75f');
chai_1.assert.equal(cm.colors.ansi[186].css, '#d7d787');
chai_1.assert.equal(cm.colors.ansi[187].css, '#d7d7af');
chai_1.assert.equal(cm.colors.ansi[188].css, '#d7d7d7');
chai_1.assert.equal(cm.colors.ansi[189].css, '#d7d7ff');
chai_1.assert.equal(cm.colors.ansi[190].css, '#d7ff00');
chai_1.assert.equal(cm.colors.ansi[191].css, '#d7ff5f');
chai_1.assert.equal(cm.colors.ansi[192].css, '#d7ff87');
chai_1.assert.equal(cm.colors.ansi[193].css, '#d7ffaf');
chai_1.assert.equal(cm.colors.ansi[194].css, '#d7ffd7');
chai_1.assert.equal(cm.colors.ansi[195].css, '#d7ffff');
chai_1.assert.equal(cm.colors.ansi[196].css, '#ff0000');
chai_1.assert.equal(cm.colors.ansi[197].css, '#ff005f');
chai_1.assert.equal(cm.colors.ansi[198].css, '#ff0087');
chai_1.assert.equal(cm.colors.ansi[199].css, '#ff00af');
chai_1.assert.equal(cm.colors.ansi[200].css, '#ff00d7');
chai_1.assert.equal(cm.colors.ansi[201].css, '#ff00ff');
chai_1.assert.equal(cm.colors.ansi[202].css, '#ff5f00');
chai_1.assert.equal(cm.colors.ansi[203].css, '#ff5f5f');
chai_1.assert.equal(cm.colors.ansi[204].css, '#ff5f87');
chai_1.assert.equal(cm.colors.ansi[205].css, '#ff5faf');
chai_1.assert.equal(cm.colors.ansi[206].css, '#ff5fd7');
chai_1.assert.equal(cm.colors.ansi[207].css, '#ff5fff');
chai_1.assert.equal(cm.colors.ansi[208].css, '#ff8700');
chai_1.assert.equal(cm.colors.ansi[209].css, '#ff875f');
chai_1.assert.equal(cm.colors.ansi[210].css, '#ff8787');
chai_1.assert.equal(cm.colors.ansi[211].css, '#ff87af');
chai_1.assert.equal(cm.colors.ansi[212].css, '#ff87d7');
chai_1.assert.equal(cm.colors.ansi[213].css, '#ff87ff');
chai_1.assert.equal(cm.colors.ansi[214].css, '#ffaf00');
chai_1.assert.equal(cm.colors.ansi[215].css, '#ffaf5f');
chai_1.assert.equal(cm.colors.ansi[216].css, '#ffaf87');
chai_1.assert.equal(cm.colors.ansi[217].css, '#ffafaf');
chai_1.assert.equal(cm.colors.ansi[218].css, '#ffafd7');
chai_1.assert.equal(cm.colors.ansi[219].css, '#ffafff');
chai_1.assert.equal(cm.colors.ansi[220].css, '#ffd700');
chai_1.assert.equal(cm.colors.ansi[221].css, '#ffd75f');
chai_1.assert.equal(cm.colors.ansi[222].css, '#ffd787');
chai_1.assert.equal(cm.colors.ansi[223].css, '#ffd7af');
chai_1.assert.equal(cm.colors.ansi[224].css, '#ffd7d7');
chai_1.assert.equal(cm.colors.ansi[225].css, '#ffd7ff');
chai_1.assert.equal(cm.colors.ansi[226].css, '#ffff00');
chai_1.assert.equal(cm.colors.ansi[227].css, '#ffff5f');
chai_1.assert.equal(cm.colors.ansi[228].css, '#ffff87');
chai_1.assert.equal(cm.colors.ansi[229].css, '#ffffaf');
chai_1.assert.equal(cm.colors.ansi[230].css, '#ffffd7');
chai_1.assert.equal(cm.colors.ansi[231].css, '#ffffff');
chai_1.assert.equal(cm.colors.ansi[232].css, '#080808');
chai_1.assert.equal(cm.colors.ansi[233].css, '#121212');
chai_1.assert.equal(cm.colors.ansi[234].css, '#1c1c1c');
chai_1.assert.equal(cm.colors.ansi[235].css, '#262626');
chai_1.assert.equal(cm.colors.ansi[236].css, '#303030');
chai_1.assert.equal(cm.colors.ansi[237].css, '#3a3a3a');
chai_1.assert.equal(cm.colors.ansi[238].css, '#444444');
chai_1.assert.equal(cm.colors.ansi[239].css, '#4e4e4e');
chai_1.assert.equal(cm.colors.ansi[240].css, '#585858');
chai_1.assert.equal(cm.colors.ansi[241].css, '#626262');
chai_1.assert.equal(cm.colors.ansi[242].css, '#6c6c6c');
chai_1.assert.equal(cm.colors.ansi[243].css, '#767676');
chai_1.assert.equal(cm.colors.ansi[244].css, '#808080');
chai_1.assert.equal(cm.colors.ansi[245].css, '#8a8a8a');
chai_1.assert.equal(cm.colors.ansi[246].css, '#949494');
chai_1.assert.equal(cm.colors.ansi[247].css, '#9e9e9e');
chai_1.assert.equal(cm.colors.ansi[248].css, '#a8a8a8');
chai_1.assert.equal(cm.colors.ansi[249].css, '#b2b2b2');
chai_1.assert.equal(cm.colors.ansi[250].css, '#bcbcbc');
chai_1.assert.equal(cm.colors.ansi[251].css, '#c6c6c6');
chai_1.assert.equal(cm.colors.ansi[252].css, '#d0d0d0');
chai_1.assert.equal(cm.colors.ansi[253].css, '#dadada');
chai_1.assert.equal(cm.colors.ansi[254].css, '#e4e4e4');
chai_1.assert.equal(cm.colors.ansi[255].css, '#eeeeee');
});
});
describe('setTheme', function () {
it('should not throw when not setting all colors', function () {
chai_1.assert.doesNotThrow(function () {
cm.setTheme({});
});
});
it('should set a partial set of colors, using the default if not present', function () {
chai_1.assert.equal(cm.colors.background.css, '#000000');
chai_1.assert.equal(cm.colors.foreground.css, '#ffffff');
cm.setTheme({
background: '#FF0000',
foreground: '#00FF00'
});
chai_1.assert.equal(cm.colors.background.css, '#FF0000');
chai_1.assert.equal(cm.colors.foreground.css, '#00FF00');
cm.setTheme({
background: '#0000FF'
});
chai_1.assert.equal(cm.colors.background.css, '#0000FF');
chai_1.assert.equal(cm.colors.foreground.css, '#ffffff');
});
});
});
//# sourceMappingURL=ColorManager.test.js.map
|
/**
* Copyright 2014 Google Inc. 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.
*/
/* jshint maxlen: false */
'use strict';
var createAPIRequest = require('../../lib/apirequest');
/**
* Admin Directory API
*
* @classdesc The Admin SDK Directory API lets you view and manage enterprise resources such as users and groups, administrative notifications, security features, and more.
* @namespace admin
* @version directory_v1
* @variation directory_v1
* @this Admin
* @param {object=} options Options for Admin
*/
function Admin(options) {
var self = this;
this._options = options || {};
this.asps = {
/**
* directory.asps.delete
*
* @desc Delete an ASP issued by a user.
*
* @alias directory.asps.delete
* @memberOf! admin(directory_v1)
*
* @param {object} params - Parameters for request
* @param {integer} params.codeId - The unique ID of the ASP to be deleted.
* @param {string} params.userKey - Identifies the user in the API request. The value can be the user's primary email address, alias email address, or unique user ID.
* @param {callback} callback - The callback that handles the response.
* @return {object} Request object
*/
delete: function(params, callback) {
var parameters = {
options: {
url: 'https://www.googleapis.com/admin/directory/v1/users/{userKey}/asps/{codeId}',
method: 'DELETE'
},
params: params,
requiredParams: ['userKey', 'codeId'],
pathParams: ['codeId', 'userKey'],
context: self
};
return createAPIRequest(parameters, callback);
},
/**
* directory.asps.get
*
* @desc Get information about an ASP issued by a user.
*
* @alias directory.asps.get
* @memberOf! admin(directory_v1)
*
* @param {object} params - Parameters for request
* @param {integer} params.codeId - The unique ID of the ASP.
* @param {string} params.userKey - Identifies the user in the API request. The value can be the user's primary email address, alias email address, or unique user ID.
* @param {callback} callback - The callback that handles the response.
* @return {object} Request object
*/
get: function(params, callback) {
var parameters = {
options: {
url: 'https://www.googleapis.com/admin/directory/v1/users/{userKey}/asps/{codeId}',
method: 'GET'
},
params: params,
requiredParams: ['userKey', 'codeId'],
pathParams: ['codeId', 'userKey'],
context: self
};
return createAPIRequest(parameters, callback);
},
/**
* directory.asps.list
*
* @desc List the ASPs issued by a user.
*
* @alias directory.asps.list
* @memberOf! admin(directory_v1)
*
* @param {object} params - Parameters for request
* @param {string} params.userKey - Identifies the user in the API request. The value can be the user's primary email address, alias email address, or unique user ID.
* @param {callback} callback - The callback that handles the response.
* @return {object} Request object
*/
list: function(params, callback) {
var parameters = {
options: {
url: 'https://www.googleapis.com/admin/directory/v1/users/{userKey}/asps',
method: 'GET'
},
params: params,
requiredParams: ['userKey'],
pathParams: ['userKey'],
context: self
};
return createAPIRequest(parameters, callback);
}
};
this.channels = {
/**
* admin.channels.stop
*
* @desc Stop watching resources through this channel
*
* @alias admin.channels.stop
* @memberOf! admin(directory_v1)
*
* @param {object} params - Parameters for request
* @param {object} params.resource - Request body data
* @param {callback} callback - The callback that handles the response.
* @return {object} Request object
*/
stop: function(params, callback) {
var parameters = {
options: {
url: 'https://www.googleapis.com/admin/directory/v1/admin/directory_v1/channels/stop',
method: 'POST'
},
params: params,
requiredParams: [],
pathParams: [],
context: self
};
return createAPIRequest(parameters, callback);
}
};
this.chromeosdevices = {
/**
* directory.chromeosdevices.get
*
* @desc Retrieve Chrome OS Device
*
* @alias directory.chromeosdevices.get
* @memberOf! admin(directory_v1)
*
* @param {object} params - Parameters for request
* @param {string} params.customerId - Immutable id of the Google Apps account
* @param {string} params.deviceId - Immutable id of Chrome OS Device
* @param {string=} params.projection - Restrict information returned to a set of selected fields.
* @param {callback} callback - The callback that handles the response.
* @return {object} Request object
*/
get: function(params, callback) {
var parameters = {
options: {
url: 'https://www.googleapis.com/admin/directory/v1/customer/{customerId}/devices/chromeos/{deviceId}',
method: 'GET'
},
params: params,
requiredParams: ['customerId', 'deviceId'],
pathParams: ['customerId', 'deviceId'],
context: self
};
return createAPIRequest(parameters, callback);
},
/**
* directory.chromeosdevices.list
*
* @desc Retrieve all Chrome OS Devices of a customer (paginated)
*
* @alias directory.chromeosdevices.list
* @memberOf! admin(directory_v1)
*
* @param {object} params - Parameters for request
* @param {string} params.customerId - Immutable id of the Google Apps account
* @param {integer=} params.maxResults - Maximum number of results to return. Default is 100
* @param {string=} params.orderBy - Column to use for sorting results
* @param {string=} params.pageToken - Token to specify next page in the list
* @param {string=} params.projection - Restrict information returned to a set of selected fields.
* @param {string=} params.query - Search string in the format given at http://support.google.com/chromeos/a/bin/answer.py?hl=en&answer=1698333
* @param {string=} params.sortOrder - Whether to return results in ascending or descending order. Only of use when orderBy is also used
* @param {callback} callback - The callback that handles the response.
* @return {object} Request object
*/
list: function(params, callback) {
var parameters = {
options: {
url: 'https://www.googleapis.com/admin/directory/v1/customer/{customerId}/devices/chromeos',
method: 'GET'
},
params: params,
requiredParams: ['customerId'],
pathParams: ['customerId'],
context: self
};
return createAPIRequest(parameters, callback);
},
/**
* directory.chromeosdevices.patch
*
* @desc Update Chrome OS Device. This method supports patch semantics.
*
* @alias directory.chromeosdevices.patch
* @memberOf! admin(directory_v1)
*
* @param {object} params - Parameters for request
* @param {string} params.customerId - Immutable id of the Google Apps account
* @param {string} params.deviceId - Immutable id of Chrome OS Device
* @param {string=} params.projection - Restrict information returned to a set of selected fields.
* @param {object} params.resource - Request body data
* @param {callback} callback - The callback that handles the response.
* @return {object} Request object
*/
patch: function(params, callback) {
var parameters = {
options: {
url: 'https://www.googleapis.com/admin/directory/v1/customer/{customerId}/devices/chromeos/{deviceId}',
method: 'PATCH'
},
params: params,
requiredParams: ['customerId', 'deviceId'],
pathParams: ['customerId', 'deviceId'],
context: self
};
return createAPIRequest(parameters, callback);
},
/**
* directory.chromeosdevices.update
*
* @desc Update Chrome OS Device
*
* @alias directory.chromeosdevices.update
* @memberOf! admin(directory_v1)
*
* @param {object} params - Parameters for request
* @param {string} params.customerId - Immutable id of the Google Apps account
* @param {string} params.deviceId - Immutable id of Chrome OS Device
* @param {string=} params.projection - Restrict information returned to a set of selected fields.
* @param {object} params.resource - Request body data
* @param {callback} callback - The callback that handles the response.
* @return {object} Request object
*/
update: function(params, callback) {
var parameters = {
options: {
url: 'https://www.googleapis.com/admin/directory/v1/customer/{customerId}/devices/chromeos/{deviceId}',
method: 'PUT'
},
params: params,
requiredParams: ['customerId', 'deviceId'],
pathParams: ['customerId', 'deviceId'],
context: self
};
return createAPIRequest(parameters, callback);
}
};
this.groups = {
/**
* directory.groups.delete
*
* @desc Delete Group
*
* @alias directory.groups.delete
* @memberOf! admin(directory_v1)
*
* @param {object} params - Parameters for request
* @param {string} params.groupKey - Email or immutable Id of the group
* @param {callback} callback - The callback that handles the response.
* @return {object} Request object
*/
delete: function(params, callback) {
var parameters = {
options: {
url: 'https://www.googleapis.com/admin/directory/v1/groups/{groupKey}',
method: 'DELETE'
},
params: params,
requiredParams: ['groupKey'],
pathParams: ['groupKey'],
context: self
};
return createAPIRequest(parameters, callback);
},
/**
* directory.groups.get
*
* @desc Retrieve Group
*
* @alias directory.groups.get
* @memberOf! admin(directory_v1)
*
* @param {object} params - Parameters for request
* @param {string} params.groupKey - Email or immutable Id of the group
* @param {callback} callback - The callback that handles the response.
* @return {object} Request object
*/
get: function(params, callback) {
var parameters = {
options: {
url: 'https://www.googleapis.com/admin/directory/v1/groups/{groupKey}',
method: 'GET'
},
params: params,
requiredParams: ['groupKey'],
pathParams: ['groupKey'],
context: self
};
return createAPIRequest(parameters, callback);
},
/**
* directory.groups.insert
*
* @desc Create Group
*
* @alias directory.groups.insert
* @memberOf! admin(directory_v1)
*
* @param {object} params - Parameters for request
* @param {object} params.resource - Request body data
* @param {callback} callback - The callback that handles the response.
* @return {object} Request object
*/
insert: function(params, callback) {
var parameters = {
options: {
url: 'https://www.googleapis.com/admin/directory/v1/groups',
method: 'POST'
},
params: params,
requiredParams: [],
pathParams: [],
context: self
};
return createAPIRequest(parameters, callback);
},
/**
* directory.groups.list
*
* @desc Retrieve all groups in a domain (paginated)
*
* @alias directory.groups.list
* @memberOf! admin(directory_v1)
*
* @param {object=} params - Parameters for request
* @param {string=} params.customer - Immutable id of the Google Apps account. In case of multi-domain, to fetch all groups for a customer, fill this field instead of domain.
* @param {string=} params.domain - Name of the domain. Fill this field to get groups from only this domain. To return all groups in a multi-domain fill customer field instead.
* @param {integer=} params.maxResults - Maximum number of results to return. Default is 200
* @param {string=} params.pageToken - Token to specify next page in the list
* @param {string=} params.userKey - Email or immutable Id of the user if only those groups are to be listed, the given user is a member of. If Id, it should match with id of user object
* @param {callback} callback - The callback that handles the response.
* @return {object} Request object
*/
list: function(params, callback) {
var parameters = {
options: {
url: 'https://www.googleapis.com/admin/directory/v1/groups',
method: 'GET'
},
params: params,
requiredParams: [],
pathParams: [],
context: self
};
return createAPIRequest(parameters, callback);
},
/**
* directory.groups.patch
*
* @desc Update Group. This method supports patch semantics.
*
* @alias directory.groups.patch
* @memberOf! admin(directory_v1)
*
* @param {object} params - Parameters for request
* @param {string} params.groupKey - Email or immutable Id of the group. If Id, it should match with id of group object
* @param {object} params.resource - Request body data
* @param {callback} callback - The callback that handles the response.
* @return {object} Request object
*/
patch: function(params, callback) {
var parameters = {
options: {
url: 'https://www.googleapis.com/admin/directory/v1/groups/{groupKey}',
method: 'PATCH'
},
params: params,
requiredParams: ['groupKey'],
pathParams: ['groupKey'],
context: self
};
return createAPIRequest(parameters, callback);
},
/**
* directory.groups.update
*
* @desc Update Group
*
* @alias directory.groups.update
* @memberOf! admin(directory_v1)
*
* @param {object} params - Parameters for request
* @param {string} params.groupKey - Email or immutable Id of the group. If Id, it should match with id of group object
* @param {object} params.resource - Request body data
* @param {callback} callback - The callback that handles the response.
* @return {object} Request object
*/
update: function(params, callback) {
var parameters = {
options: {
url: 'https://www.googleapis.com/admin/directory/v1/groups/{groupKey}',
method: 'PUT'
},
params: params,
requiredParams: ['groupKey'],
pathParams: ['groupKey'],
context: self
};
return createAPIRequest(parameters, callback);
},
aliases: {
/**
* directory.groups.aliases.delete
*
* @desc Remove a alias for the group
*
* @alias directory.groups.aliases.delete
* @memberOf! admin(directory_v1)
*
* @param {object} params - Parameters for request
* @param {string} params.alias - The alias to be removed
* @param {string} params.groupKey - Email or immutable Id of the group
* @param {callback} callback - The callback that handles the response.
* @return {object} Request object
*/
delete: function(params, callback) {
var parameters = {
options: {
url: 'https://www.googleapis.com/admin/directory/v1/groups/{groupKey}/aliases/{alias}',
method: 'DELETE'
},
params: params,
requiredParams: ['groupKey', 'alias'],
pathParams: ['alias', 'groupKey'],
context: self
};
return createAPIRequest(parameters, callback);
},
/**
* directory.groups.aliases.insert
*
* @desc Add a alias for the group
*
* @alias directory.groups.aliases.insert
* @memberOf! admin(directory_v1)
*
* @param {object} params - Parameters for request
* @param {string} params.groupKey - Email or immutable Id of the group
* @param {object} params.resource - Request body data
* @param {callback} callback - The callback that handles the response.
* @return {object} Request object
*/
insert: function(params, callback) {
var parameters = {
options: {
url: 'https://www.googleapis.com/admin/directory/v1/groups/{groupKey}/aliases',
method: 'POST'
},
params: params,
requiredParams: ['groupKey'],
pathParams: ['groupKey'],
context: self
};
return createAPIRequest(parameters, callback);
},
/**
* directory.groups.aliases.list
*
* @desc List all aliases for a group
*
* @alias directory.groups.aliases.list
* @memberOf! admin(directory_v1)
*
* @param {object} params - Parameters for request
* @param {string} params.groupKey - Email or immutable Id of the group
* @param {callback} callback - The callback that handles the response.
* @return {object} Request object
*/
list: function(params, callback) {
var parameters = {
options: {
url: 'https://www.googleapis.com/admin/directory/v1/groups/{groupKey}/aliases',
method: 'GET'
},
params: params,
requiredParams: ['groupKey'],
pathParams: ['groupKey'],
context: self
};
return createAPIRequest(parameters, callback);
}
}
};
this.members = {
/**
* directory.members.delete
*
* @desc Remove membership.
*
* @alias directory.members.delete
* @memberOf! admin(directory_v1)
*
* @param {object} params - Parameters for request
* @param {string} params.groupKey - Email or immutable Id of the group
* @param {string} params.memberKey - Email or immutable Id of the member
* @param {callback} callback - The callback that handles the response.
* @return {object} Request object
*/
delete: function(params, callback) {
var parameters = {
options: {
url: 'https://www.googleapis.com/admin/directory/v1/groups/{groupKey}/members/{memberKey}',
method: 'DELETE'
},
params: params,
requiredParams: ['groupKey', 'memberKey'],
pathParams: ['groupKey', 'memberKey'],
context: self
};
return createAPIRequest(parameters, callback);
},
/**
* directory.members.get
*
* @desc Retrieve Group Member
*
* @alias directory.members.get
* @memberOf! admin(directory_v1)
*
* @param {object} params - Parameters for request
* @param {string} params.groupKey - Email or immutable Id of the group
* @param {string} params.memberKey - Email or immutable Id of the member
* @param {callback} callback - The callback that handles the response.
* @return {object} Request object
*/
get: function(params, callback) {
var parameters = {
options: {
url: 'https://www.googleapis.com/admin/directory/v1/groups/{groupKey}/members/{memberKey}',
method: 'GET'
},
params: params,
requiredParams: ['groupKey', 'memberKey'],
pathParams: ['groupKey', 'memberKey'],
context: self
};
return createAPIRequest(parameters, callback);
},
/**
* directory.members.insert
*
* @desc Add user to the specified group.
*
* @alias directory.members.insert
* @memberOf! admin(directory_v1)
*
* @param {object} params - Parameters for request
* @param {string} params.groupKey - Email or immutable Id of the group
* @param {object} params.resource - Request body data
* @param {callback} callback - The callback that handles the response.
* @return {object} Request object
*/
insert: function(params, callback) {
var parameters = {
options: {
url: 'https://www.googleapis.com/admin/directory/v1/groups/{groupKey}/members',
method: 'POST'
},
params: params,
requiredParams: ['groupKey'],
pathParams: ['groupKey'],
context: self
};
return createAPIRequest(parameters, callback);
},
/**
* directory.members.list
*
* @desc Retrieve all members in a group (paginated)
*
* @alias directory.members.list
* @memberOf! admin(directory_v1)
*
* @param {object} params - Parameters for request
* @param {string} params.groupKey - Email or immutable Id of the group
* @param {integer=} params.maxResults - Maximum number of results to return. Default is 200
* @param {string=} params.pageToken - Token to specify next page in the list
* @param {string=} params.roles - Comma separated role values to filter list results on.
* @param {callback} callback - The callback that handles the response.
* @return {object} Request object
*/
list: function(params, callback) {
var parameters = {
options: {
url: 'https://www.googleapis.com/admin/directory/v1/groups/{groupKey}/members',
method: 'GET'
},
params: params,
requiredParams: ['groupKey'],
pathParams: ['groupKey'],
context: self
};
return createAPIRequest(parameters, callback);
},
/**
* directory.members.patch
*
* @desc Update membership of a user in the specified group. This method supports patch semantics.
*
* @alias directory.members.patch
* @memberOf! admin(directory_v1)
*
* @param {object} params - Parameters for request
* @param {string} params.groupKey - Email or immutable Id of the group. If Id, it should match with id of group object
* @param {string} params.memberKey - Email or immutable Id of the user. If Id, it should match with id of member object
* @param {object} params.resource - Request body data
* @param {callback} callback - The callback that handles the response.
* @return {object} Request object
*/
patch: function(params, callback) {
var parameters = {
options: {
url: 'https://www.googleapis.com/admin/directory/v1/groups/{groupKey}/members/{memberKey}',
method: 'PATCH'
},
params: params,
requiredParams: ['groupKey', 'memberKey'],
pathParams: ['groupKey', 'memberKey'],
context: self
};
return createAPIRequest(parameters, callback);
},
/**
* directory.members.update
*
* @desc Update membership of a user in the specified group.
*
* @alias directory.members.update
* @memberOf! admin(directory_v1)
*
* @param {object} params - Parameters for request
* @param {string} params.groupKey - Email or immutable Id of the group. If Id, it should match with id of group object
* @param {string} params.memberKey - Email or immutable Id of the user. If Id, it should match with id of member object
* @param {object} params.resource - Request body data
* @param {callback} callback - The callback that handles the response.
* @return {object} Request object
*/
update: function(params, callback) {
var parameters = {
options: {
url: 'https://www.googleapis.com/admin/directory/v1/groups/{groupKey}/members/{memberKey}',
method: 'PUT'
},
params: params,
requiredParams: ['groupKey', 'memberKey'],
pathParams: ['groupKey', 'memberKey'],
context: self
};
return createAPIRequest(parameters, callback);
}
};
this.mobiledevices = {
/**
* directory.mobiledevices.action
*
* @desc Take action on Mobile Device
*
* @alias directory.mobiledevices.action
* @memberOf! admin(directory_v1)
*
* @param {object} params - Parameters for request
* @param {string} params.customerId - Immutable id of the Google Apps account
* @param {string} params.resourceId - Immutable id of Mobile Device
* @param {object} params.resource - Request body data
* @param {callback} callback - The callback that handles the response.
* @return {object} Request object
*/
action: function(params, callback) {
var parameters = {
options: {
url: 'https://www.googleapis.com/admin/directory/v1/customer/{customerId}/devices/mobile/{resourceId}/action',
method: 'POST'
},
params: params,
requiredParams: ['customerId', 'resourceId'],
pathParams: ['customerId', 'resourceId'],
context: self
};
return createAPIRequest(parameters, callback);
},
/**
* directory.mobiledevices.delete
*
* @desc Delete Mobile Device
*
* @alias directory.mobiledevices.delete
* @memberOf! admin(directory_v1)
*
* @param {object} params - Parameters for request
* @param {string} params.customerId - Immutable id of the Google Apps account
* @param {string} params.resourceId - Immutable id of Mobile Device
* @param {callback} callback - The callback that handles the response.
* @return {object} Request object
*/
delete: function(params, callback) {
var parameters = {
options: {
url: 'https://www.googleapis.com/admin/directory/v1/customer/{customerId}/devices/mobile/{resourceId}',
method: 'DELETE'
},
params: params,
requiredParams: ['customerId', 'resourceId'],
pathParams: ['customerId', 'resourceId'],
context: self
};
return createAPIRequest(parameters, callback);
},
/**
* directory.mobiledevices.get
*
* @desc Retrieve Mobile Device
*
* @alias directory.mobiledevices.get
* @memberOf! admin(directory_v1)
*
* @param {object} params - Parameters for request
* @param {string} params.customerId - Immutable id of the Google Apps account
* @param {string=} params.projection - Restrict information returned to a set of selected fields.
* @param {string} params.resourceId - Immutable id of Mobile Device
* @param {callback} callback - The callback that handles the response.
* @return {object} Request object
*/
get: function(params, callback) {
var parameters = {
options: {
url: 'https://www.googleapis.com/admin/directory/v1/customer/{customerId}/devices/mobile/{resourceId}',
method: 'GET'
},
params: params,
requiredParams: ['customerId', 'resourceId'],
pathParams: ['customerId', 'resourceId'],
context: self
};
return createAPIRequest(parameters, callback);
},
/**
* directory.mobiledevices.list
*
* @desc Retrieve all Mobile Devices of a customer (paginated)
*
* @alias directory.mobiledevices.list
* @memberOf! admin(directory_v1)
*
* @param {object} params - Parameters for request
* @param {string} params.customerId - Immutable id of the Google Apps account
* @param {integer=} params.maxResults - Maximum number of results to return. Default is 100
* @param {string=} params.orderBy - Column to use for sorting results
* @param {string=} params.pageToken - Token to specify next page in the list
* @param {string=} params.projection - Restrict information returned to a set of selected fields.
* @param {string=} params.query - Search string in the format given at http://support.google.com/a/bin/answer.py?hl=en&answer=1408863#search
* @param {string=} params.sortOrder - Whether to return results in ascending or descending order. Only of use when orderBy is also used
* @param {callback} callback - The callback that handles the response.
* @return {object} Request object
*/
list: function(params, callback) {
var parameters = {
options: {
url: 'https://www.googleapis.com/admin/directory/v1/customer/{customerId}/devices/mobile',
method: 'GET'
},
params: params,
requiredParams: ['customerId'],
pathParams: ['customerId'],
context: self
};
return createAPIRequest(parameters, callback);
}
};
this.notifications = {
/**
* directory.notifications.delete
*
* @desc Deletes a notification
*
* @alias directory.notifications.delete
* @memberOf! admin(directory_v1)
*
* @param {object} params - Parameters for request
* @param {string} params.customer - The unique ID for the customer's Google account. The customerId is also returned as part of the Users resource.
* @param {string} params.notificationId - The unique ID of the notification.
* @param {callback} callback - The callback that handles the response.
* @return {object} Request object
*/
delete: function(params, callback) {
var parameters = {
options: {
url: 'https://www.googleapis.com/admin/directory/v1/customer/{customer}/notifications/{notificationId}',
method: 'DELETE'
},
params: params,
requiredParams: ['customer', 'notificationId'],
pathParams: ['customer', 'notificationId'],
context: self
};
return createAPIRequest(parameters, callback);
},
/**
* directory.notifications.get
*
* @desc Retrieves a notification.
*
* @alias directory.notifications.get
* @memberOf! admin(directory_v1)
*
* @param {object} params - Parameters for request
* @param {string} params.customer - The unique ID for the customer's Google account. The customerId is also returned as part of the Users resource.
* @param {string} params.notificationId - The unique ID of the notification.
* @param {callback} callback - The callback that handles the response.
* @return {object} Request object
*/
get: function(params, callback) {
var parameters = {
options: {
url: 'https://www.googleapis.com/admin/directory/v1/customer/{customer}/notifications/{notificationId}',
method: 'GET'
},
params: params,
requiredParams: ['customer', 'notificationId'],
pathParams: ['customer', 'notificationId'],
context: self
};
return createAPIRequest(parameters, callback);
},
/**
* directory.notifications.list
*
* @desc Retrieves a list of notifications.
*
* @alias directory.notifications.list
* @memberOf! admin(directory_v1)
*
* @param {object} params - Parameters for request
* @param {string} params.customer - The unique ID for the customer's Google account.
* @param {string=} params.language - The ISO 639-1 code of the language notifications are returned in. The default is English (en).
* @param {integer=} params.maxResults - Maximum number of notifications to return per page. The default is 100.
* @param {string=} params.pageToken - The token to specify the page of results to retrieve.
* @param {callback} callback - The callback that handles the response.
* @return {object} Request object
*/
list: function(params, callback) {
var parameters = {
options: {
url: 'https://www.googleapis.com/admin/directory/v1/customer/{customer}/notifications',
method: 'GET'
},
params: params,
requiredParams: ['customer'],
pathParams: ['customer'],
context: self
};
return createAPIRequest(parameters, callback);
},
/**
* directory.notifications.patch
*
* @desc Updates a notification. This method supports patch semantics.
*
* @alias directory.notifications.patch
* @memberOf! admin(directory_v1)
*
* @param {object} params - Parameters for request
* @param {string} params.customer - The unique ID for the customer's Google account.
* @param {string} params.notificationId - The unique ID of the notification.
* @param {object} params.resource - Request body data
* @param {callback} callback - The callback that handles the response.
* @return {object} Request object
*/
patch: function(params, callback) {
var parameters = {
options: {
url: 'https://www.googleapis.com/admin/directory/v1/customer/{customer}/notifications/{notificationId}',
method: 'PATCH'
},
params: params,
requiredParams: ['customer', 'notificationId'],
pathParams: ['customer', 'notificationId'],
context: self
};
return createAPIRequest(parameters, callback);
},
/**
* directory.notifications.update
*
* @desc Updates a notification.
*
* @alias directory.notifications.update
* @memberOf! admin(directory_v1)
*
* @param {object} params - Parameters for request
* @param {string} params.customer - The unique ID for the customer's Google account.
* @param {string} params.notificationId - The unique ID of the notification.
* @param {object} params.resource - Request body data
* @param {callback} callback - The callback that handles the response.
* @return {object} Request object
*/
update: function(params, callback) {
var parameters = {
options: {
url: 'https://www.googleapis.com/admin/directory/v1/customer/{customer}/notifications/{notificationId}',
method: 'PUT'
},
params: params,
requiredParams: ['customer', 'notificationId'],
pathParams: ['customer', 'notificationId'],
context: self
};
return createAPIRequest(parameters, callback);
}
};
this.orgunits = {
/**
* directory.orgunits.delete
*
* @desc Remove Organization Unit
*
* @alias directory.orgunits.delete
* @memberOf! admin(directory_v1)
*
* @param {object} params - Parameters for request
* @param {string} params.customerId - Immutable id of the Google Apps account
* @param {string} params.orgUnitPath - Full path of the organization unit
* @param {callback} callback - The callback that handles the response.
* @return {object} Request object
*/
delete: function(params, callback) {
var parameters = {
options: {
url: 'https://www.googleapis.com/admin/directory/v1/customer/{customerId}/orgunits/{orgUnitPath}',
method: 'DELETE'
},
params: params,
requiredParams: ['customerId', 'orgUnitPath'],
pathParams: ['customerId', 'orgUnitPath'],
context: self
};
return createAPIRequest(parameters, callback);
},
/**
* directory.orgunits.get
*
* @desc Retrieve Organization Unit
*
* @alias directory.orgunits.get
* @memberOf! admin(directory_v1)
*
* @param {object} params - Parameters for request
* @param {string} params.customerId - Immutable id of the Google Apps account
* @param {string} params.orgUnitPath - Full path of the organization unit
* @param {callback} callback - The callback that handles the response.
* @return {object} Request object
*/
get: function(params, callback) {
var parameters = {
options: {
url: 'https://www.googleapis.com/admin/directory/v1/customer/{customerId}/orgunits/{orgUnitPath}',
method: 'GET'
},
params: params,
requiredParams: ['customerId', 'orgUnitPath'],
pathParams: ['customerId', 'orgUnitPath'],
context: self
};
return createAPIRequest(parameters, callback);
},
/**
* directory.orgunits.insert
*
* @desc Add Organization Unit
*
* @alias directory.orgunits.insert
* @memberOf! admin(directory_v1)
*
* @param {object} params - Parameters for request
* @param {string} params.customerId - Immutable id of the Google Apps account
* @param {object} params.resource - Request body data
* @param {callback} callback - The callback that handles the response.
* @return {object} Request object
*/
insert: function(params, callback) {
var parameters = {
options: {
url: 'https://www.googleapis.com/admin/directory/v1/customer/{customerId}/orgunits',
method: 'POST'
},
params: params,
requiredParams: ['customerId'],
pathParams: ['customerId'],
context: self
};
return createAPIRequest(parameters, callback);
},
/**
* directory.orgunits.list
*
* @desc Retrieve all Organization Units
*
* @alias directory.orgunits.list
* @memberOf! admin(directory_v1)
*
* @param {object} params - Parameters for request
* @param {string} params.customerId - Immutable id of the Google Apps account
* @param {string=} params.orgUnitPath - the URL-encoded organization unit
* @param {string=} params.type - Whether to return all sub-organizations or just immediate children
* @param {callback} callback - The callback that handles the response.
* @return {object} Request object
*/
list: function(params, callback) {
var parameters = {
options: {
url: 'https://www.googleapis.com/admin/directory/v1/customer/{customerId}/orgunits',
method: 'GET'
},
params: params,
requiredParams: ['customerId'],
pathParams: ['customerId'],
context: self
};
return createAPIRequest(parameters, callback);
},
/**
* directory.orgunits.patch
*
* @desc Update Organization Unit. This method supports patch semantics.
*
* @alias directory.orgunits.patch
* @memberOf! admin(directory_v1)
*
* @param {object} params - Parameters for request
* @param {string} params.customerId - Immutable id of the Google Apps account
* @param {string} params.orgUnitPath - Full path of the organization unit
* @param {object} params.resource - Request body data
* @param {callback} callback - The callback that handles the response.
* @return {object} Request object
*/
patch: function(params, callback) {
var parameters = {
options: {
url: 'https://www.googleapis.com/admin/directory/v1/customer/{customerId}/orgunits/{orgUnitPath}',
method: 'PATCH'
},
params: params,
requiredParams: ['customerId', 'orgUnitPath'],
pathParams: ['customerId', 'orgUnitPath'],
context: self
};
return createAPIRequest(parameters, callback);
},
/**
* directory.orgunits.update
*
* @desc Update Organization Unit
*
* @alias directory.orgunits.update
* @memberOf! admin(directory_v1)
*
* @param {object} params - Parameters for request
* @param {string} params.customerId - Immutable id of the Google Apps account
* @param {string} params.orgUnitPath - Full path of the organization unit
* @param {object} params.resource - Request body data
* @param {callback} callback - The callback that handles the response.
* @return {object} Request object
*/
update: function(params, callback) {
var parameters = {
options: {
url: 'https://www.googleapis.com/admin/directory/v1/customer/{customerId}/orgunits/{orgUnitPath}',
method: 'PUT'
},
params: params,
requiredParams: ['customerId', 'orgUnitPath'],
pathParams: ['customerId', 'orgUnitPath'],
context: self
};
return createAPIRequest(parameters, callback);
}
};
this.schemas = {
/**
* directory.schemas.delete
*
* @desc Delete schema
*
* @alias directory.schemas.delete
* @memberOf! admin(directory_v1)
*
* @param {object} params - Parameters for request
* @param {string} params.customerId - Immutable id of the Google Apps account
* @param {string} params.schemaKey - Name or immutable Id of the schema
* @param {callback} callback - The callback that handles the response.
* @return {object} Request object
*/
delete: function(params, callback) {
var parameters = {
options: {
url: 'https://www.googleapis.com/admin/directory/v1/customer/{customerId}/schemas/{schemaKey}',
method: 'DELETE'
},
params: params,
requiredParams: ['customerId', 'schemaKey'],
pathParams: ['customerId', 'schemaKey'],
context: self
};
return createAPIRequest(parameters, callback);
},
/**
* directory.schemas.get
*
* @desc Retrieve schema
*
* @alias directory.schemas.get
* @memberOf! admin(directory_v1)
*
* @param {object} params - Parameters for request
* @param {string} params.customerId - Immutable id of the Google Apps account
* @param {string} params.schemaKey - Name or immutable Id of the schema
* @param {callback} callback - The callback that handles the response.
* @return {object} Request object
*/
get: function(params, callback) {
var parameters = {
options: {
url: 'https://www.googleapis.com/admin/directory/v1/customer/{customerId}/schemas/{schemaKey}',
method: 'GET'
},
params: params,
requiredParams: ['customerId', 'schemaKey'],
pathParams: ['customerId', 'schemaKey'],
context: self
};
return createAPIRequest(parameters, callback);
},
/**
* directory.schemas.insert
*
* @desc Create schema.
*
* @alias directory.schemas.insert
* @memberOf! admin(directory_v1)
*
* @param {object} params - Parameters for request
* @param {string} params.customerId - Immutable id of the Google Apps account
* @param {object} params.resource - Request body data
* @param {callback} callback - The callback that handles the response.
* @return {object} Request object
*/
insert: function(params, callback) {
var parameters = {
options: {
url: 'https://www.googleapis.com/admin/directory/v1/customer/{customerId}/schemas',
method: 'POST'
},
params: params,
requiredParams: ['customerId'],
pathParams: ['customerId'],
context: self
};
return createAPIRequest(parameters, callback);
},
/**
* directory.schemas.list
*
* @desc Retrieve all schemas for a customer
*
* @alias directory.schemas.list
* @memberOf! admin(directory_v1)
*
* @param {object} params - Parameters for request
* @param {string} params.customerId - Immutable id of the Google Apps account
* @param {callback} callback - The callback that handles the response.
* @return {object} Request object
*/
list: function(params, callback) {
var parameters = {
options: {
url: 'https://www.googleapis.com/admin/directory/v1/customer/{customerId}/schemas',
method: 'GET'
},
params: params,
requiredParams: ['customerId'],
pathParams: ['customerId'],
context: self
};
return createAPIRequest(parameters, callback);
},
/**
* directory.schemas.patch
*
* @desc Update schema. This method supports patch semantics.
*
* @alias directory.schemas.patch
* @memberOf! admin(directory_v1)
*
* @param {object} params - Parameters for request
* @param {string} params.customerId - Immutable id of the Google Apps account
* @param {string} params.schemaKey - Name or immutable Id of the schema.
* @param {object} params.resource - Request body data
* @param {callback} callback - The callback that handles the response.
* @return {object} Request object
*/
patch: function(params, callback) {
var parameters = {
options: {
url: 'https://www.googleapis.com/admin/directory/v1/customer/{customerId}/schemas/{schemaKey}',
method: 'PATCH'
},
params: params,
requiredParams: ['customerId', 'schemaKey'],
pathParams: ['customerId', 'schemaKey'],
context: self
};
return createAPIRequest(parameters, callback);
},
/**
* directory.schemas.update
*
* @desc Update schema
*
* @alias directory.schemas.update
* @memberOf! admin(directory_v1)
*
* @param {object} params - Parameters for request
* @param {string} params.customerId - Immutable id of the Google Apps account
* @param {string} params.schemaKey - Name or immutable Id of the schema.
* @param {object} params.resource - Request body data
* @param {callback} callback - The callback that handles the response.
* @return {object} Request object
*/
update: function(params, callback) {
var parameters = {
options: {
url: 'https://www.googleapis.com/admin/directory/v1/customer/{customerId}/schemas/{schemaKey}',
method: 'PUT'
},
params: params,
requiredParams: ['customerId', 'schemaKey'],
pathParams: ['customerId', 'schemaKey'],
context: self
};
return createAPIRequest(parameters, callback);
}
};
this.tokens = {
/**
* directory.tokens.delete
*
* @desc Delete all access tokens issued by a user for an application.
*
* @alias directory.tokens.delete
* @memberOf! admin(directory_v1)
*
* @param {object} params - Parameters for request
* @param {string} params.clientId - The Client ID of the application the token is issued to.
* @param {string} params.userKey - Identifies the user in the API request. The value can be the user's primary email address, alias email address, or unique user ID.
* @param {callback} callback - The callback that handles the response.
* @return {object} Request object
*/
delete: function(params, callback) {
var parameters = {
options: {
url: 'https://www.googleapis.com/admin/directory/v1/users/{userKey}/tokens/{clientId}',
method: 'DELETE'
},
params: params,
requiredParams: ['userKey', 'clientId'],
pathParams: ['clientId', 'userKey'],
context: self
};
return createAPIRequest(parameters, callback);
},
/**
* directory.tokens.get
*
* @desc Get information about an access token issued by a user.
*
* @alias directory.tokens.get
* @memberOf! admin(directory_v1)
*
* @param {object} params - Parameters for request
* @param {string} params.clientId - The Client ID of the application the token is issued to.
* @param {string} params.userKey - Identifies the user in the API request. The value can be the user's primary email address, alias email address, or unique user ID.
* @param {callback} callback - The callback that handles the response.
* @return {object} Request object
*/
get: function(params, callback) {
var parameters = {
options: {
url: 'https://www.googleapis.com/admin/directory/v1/users/{userKey}/tokens/{clientId}',
method: 'GET'
},
params: params,
requiredParams: ['userKey', 'clientId'],
pathParams: ['clientId', 'userKey'],
context: self
};
return createAPIRequest(parameters, callback);
},
/**
* directory.tokens.list
*
* @desc Returns the set of tokens specified user has issued to 3rd party applications.
*
* @alias directory.tokens.list
* @memberOf! admin(directory_v1)
*
* @param {object} params - Parameters for request
* @param {string} params.userKey - Identifies the user in the API request. The value can be the user's primary email address, alias email address, or unique user ID.
* @param {callback} callback - The callback that handles the response.
* @return {object} Request object
*/
list: function(params, callback) {
var parameters = {
options: {
url: 'https://www.googleapis.com/admin/directory/v1/users/{userKey}/tokens',
method: 'GET'
},
params: params,
requiredParams: ['userKey'],
pathParams: ['userKey'],
context: self
};
return createAPIRequest(parameters, callback);
}
};
this.users = {
/**
* directory.users.delete
*
* @desc Delete user
*
* @alias directory.users.delete
* @memberOf! admin(directory_v1)
*
* @param {object} params - Parameters for request
* @param {string} params.userKey - Email or immutable Id of the user
* @param {callback} callback - The callback that handles the response.
* @return {object} Request object
*/
delete: function(params, callback) {
var parameters = {
options: {
url: 'https://www.googleapis.com/admin/directory/v1/users/{userKey}',
method: 'DELETE'
},
params: params,
requiredParams: ['userKey'],
pathParams: ['userKey'],
context: self
};
return createAPIRequest(parameters, callback);
},
/**
* directory.users.get
*
* @desc retrieve user
*
* @alias directory.users.get
* @memberOf! admin(directory_v1)
*
* @param {object} params - Parameters for request
* @param {string=} params.customFieldMask - Comma-separated list of schema names. All fields from these schemas are fetched. This should only be set when projection=custom.
* @param {string=} params.projection - What subset of fields to fetch for this user.
* @param {string} params.userKey - Email or immutable Id of the user
* @param {string=} params.viewType - Whether to fetch the ADMIN_VIEW or DOMAIN_PUBLIC view of the user.
* @param {callback} callback - The callback that handles the response.
* @return {object} Request object
*/
get: function(params, callback) {
var parameters = {
options: {
url: 'https://www.googleapis.com/admin/directory/v1/users/{userKey}',
method: 'GET'
},
params: params,
requiredParams: ['userKey'],
pathParams: ['userKey'],
context: self
};
return createAPIRequest(parameters, callback);
},
/**
* directory.users.insert
*
* @desc create user.
*
* @alias directory.users.insert
* @memberOf! admin(directory_v1)
*
* @param {object} params - Parameters for request
* @param {object} params.resource - Request body data
* @param {callback} callback - The callback that handles the response.
* @return {object} Request object
*/
insert: function(params, callback) {
var parameters = {
options: {
url: 'https://www.googleapis.com/admin/directory/v1/users',
method: 'POST'
},
params: params,
requiredParams: [],
pathParams: [],
context: self
};
return createAPIRequest(parameters, callback);
},
/**
* directory.users.list
*
* @desc Retrieve either deleted users or all users in a domain (paginated)
*
* @alias directory.users.list
* @memberOf! admin(directory_v1)
*
* @param {object=} params - Parameters for request
* @param {string=} params.customFieldMask - Comma-separated list of schema names. All fields from these schemas are fetched. This should only be set when projection=custom.
* @param {string=} params.customer - Immutable id of the Google Apps account. In case of multi-domain, to fetch all users for a customer, fill this field instead of domain.
* @param {string=} params.domain - Name of the domain. Fill this field to get users from only this domain. To return all users in a multi-domain fill customer field instead.
* @param {string=} params.event - Event on which subscription is intended (if subscribing)
* @param {integer=} params.maxResults - Maximum number of results to return. Default is 100. Max allowed is 500
* @param {string=} params.orderBy - Column to use for sorting results
* @param {string=} params.pageToken - Token to specify next page in the list
* @param {string=} params.projection - What subset of fields to fetch for this user.
* @param {string=} params.query - Query string search. Should be of the form "". Complete documentation is at https://developers.google.com/admin-sdk/directory/v1/guides/search-users
* @param {string=} params.showDeleted - If set to true retrieves the list of deleted users. Default is false
* @param {string=} params.sortOrder - Whether to return results in ascending or descending order.
* @param {string=} params.viewType - Whether to fetch the ADMIN_VIEW or DOMAIN_PUBLIC view of the user.
* @param {callback} callback - The callback that handles the response.
* @return {object} Request object
*/
list: function(params, callback) {
var parameters = {
options: {
url: 'https://www.googleapis.com/admin/directory/v1/users',
method: 'GET'
},
params: params,
requiredParams: [],
pathParams: [],
context: self
};
return createAPIRequest(parameters, callback);
},
/**
* directory.users.makeAdmin
*
* @desc change admin status of a user
*
* @alias directory.users.makeAdmin
* @memberOf! admin(directory_v1)
*
* @param {object} params - Parameters for request
* @param {string} params.userKey - Email or immutable Id of the user as admin
* @param {object} params.resource - Request body data
* @param {callback} callback - The callback that handles the response.
* @return {object} Request object
*/
makeAdmin: function(params, callback) {
var parameters = {
options: {
url: 'https://www.googleapis.com/admin/directory/v1/users/{userKey}/makeAdmin',
method: 'POST'
},
params: params,
requiredParams: ['userKey'],
pathParams: ['userKey'],
context: self
};
return createAPIRequest(parameters, callback);
},
/**
* directory.users.patch
*
* @desc update user. This method supports patch semantics.
*
* @alias directory.users.patch
* @memberOf! admin(directory_v1)
*
* @param {object} params - Parameters for request
* @param {string} params.userKey - Email or immutable Id of the user. If Id, it should match with id of user object
* @param {object} params.resource - Request body data
* @param {callback} callback - The callback that handles the response.
* @return {object} Request object
*/
patch: function(params, callback) {
var parameters = {
options: {
url: 'https://www.googleapis.com/admin/directory/v1/users/{userKey}',
method: 'PATCH'
},
params: params,
requiredParams: ['userKey'],
pathParams: ['userKey'],
context: self
};
return createAPIRequest(parameters, callback);
},
/**
* directory.users.undelete
*
* @desc Undelete a deleted user
*
* @alias directory.users.undelete
* @memberOf! admin(directory_v1)
*
* @param {object} params - Parameters for request
* @param {string} params.userKey - The immutable id of the user
* @param {object} params.resource - Request body data
* @param {callback} callback - The callback that handles the response.
* @return {object} Request object
*/
undelete: function(params, callback) {
var parameters = {
options: {
url: 'https://www.googleapis.com/admin/directory/v1/users/{userKey}/undelete',
method: 'POST'
},
params: params,
requiredParams: ['userKey'],
pathParams: ['userKey'],
context: self
};
return createAPIRequest(parameters, callback);
},
/**
* directory.users.update
*
* @desc update user
*
* @alias directory.users.update
* @memberOf! admin(directory_v1)
*
* @param {object} params - Parameters for request
* @param {string} params.userKey - Email or immutable Id of the user. If Id, it should match with id of user object
* @param {object} params.resource - Request body data
* @param {callback} callback - The callback that handles the response.
* @return {object} Request object
*/
update: function(params, callback) {
var parameters = {
options: {
url: 'https://www.googleapis.com/admin/directory/v1/users/{userKey}',
method: 'PUT'
},
params: params,
requiredParams: ['userKey'],
pathParams: ['userKey'],
context: self
};
return createAPIRequest(parameters, callback);
},
/**
* directory.users.watch
*
* @desc Watch for changes in users list
*
* @alias directory.users.watch
* @memberOf! admin(directory_v1)
*
* @param {object} params - Parameters for request
* @param {string=} params.customFieldMask - Comma-separated list of schema names. All fields from these schemas are fetched. This should only be set when projection=custom.
* @param {string=} params.customer - Immutable id of the Google Apps account. In case of multi-domain, to fetch all users for a customer, fill this field instead of domain.
* @param {string=} params.domain - Name of the domain. Fill this field to get users from only this domain. To return all users in a multi-domain fill customer field instead.
* @param {string=} params.event - Event on which subscription is intended (if subscribing)
* @param {integer=} params.maxResults - Maximum number of results to return. Default is 100. Max allowed is 500
* @param {string=} params.orderBy - Column to use for sorting results
* @param {string=} params.pageToken - Token to specify next page in the list
* @param {string=} params.projection - What subset of fields to fetch for this user.
* @param {string=} params.query - Query string search. Should be of the form "". Complete documentation is at https://developers.google.com/admin-sdk/directory/v1/guides/search-users
* @param {string=} params.showDeleted - If set to true retrieves the list of deleted users. Default is false
* @param {string=} params.sortOrder - Whether to return results in ascending or descending order.
* @param {string=} params.viewType - Whether to fetch the ADMIN_VIEW or DOMAIN_PUBLIC view of the user.
* @param {object} params.resource - Request body data
* @param {callback} callback - The callback that handles the response.
* @return {object} Request object
*/
watch: function(params, callback) {
var parameters = {
options: {
url: 'https://www.googleapis.com/admin/directory/v1/users/watch',
method: 'POST'
},
params: params,
requiredParams: [],
pathParams: [],
context: self
};
return createAPIRequest(parameters, callback);
},
aliases: {
/**
* directory.users.aliases.delete
*
* @desc Remove a alias for the user
*
* @alias directory.users.aliases.delete
* @memberOf! admin(directory_v1)
*
* @param {object} params - Parameters for request
* @param {string} params.alias - The alias to be removed
* @param {string} params.userKey - Email or immutable Id of the user
* @param {callback} callback - The callback that handles the response.
* @return {object} Request object
*/
delete: function(params, callback) {
var parameters = {
options: {
url: 'https://www.googleapis.com/admin/directory/v1/users/{userKey}/aliases/{alias}',
method: 'DELETE'
},
params: params,
requiredParams: ['userKey', 'alias'],
pathParams: ['alias', 'userKey'],
context: self
};
return createAPIRequest(parameters, callback);
},
/**
* directory.users.aliases.insert
*
* @desc Add a alias for the user
*
* @alias directory.users.aliases.insert
* @memberOf! admin(directory_v1)
*
* @param {object} params - Parameters for request
* @param {string} params.userKey - Email or immutable Id of the user
* @param {object} params.resource - Request body data
* @param {callback} callback - The callback that handles the response.
* @return {object} Request object
*/
insert: function(params, callback) {
var parameters = {
options: {
url: 'https://www.googleapis.com/admin/directory/v1/users/{userKey}/aliases',
method: 'POST'
},
params: params,
requiredParams: ['userKey'],
pathParams: ['userKey'],
context: self
};
return createAPIRequest(parameters, callback);
},
/**
* directory.users.aliases.list
*
* @desc List all aliases for a user
*
* @alias directory.users.aliases.list
* @memberOf! admin(directory_v1)
*
* @param {object} params - Parameters for request
* @param {string=} params.event - Event on which subscription is intended (if subscribing)
* @param {string} params.userKey - Email or immutable Id of the user
* @param {callback} callback - The callback that handles the response.
* @return {object} Request object
*/
list: function(params, callback) {
var parameters = {
options: {
url: 'https://www.googleapis.com/admin/directory/v1/users/{userKey}/aliases',
method: 'GET'
},
params: params,
requiredParams: ['userKey'],
pathParams: ['userKey'],
context: self
};
return createAPIRequest(parameters, callback);
},
/**
* directory.users.aliases.watch
*
* @desc Watch for changes in user aliases list
*
* @alias directory.users.aliases.watch
* @memberOf! admin(directory_v1)
*
* @param {object} params - Parameters for request
* @param {string=} params.event - Event on which subscription is intended (if subscribing)
* @param {string} params.userKey - Email or immutable Id of the user
* @param {object} params.resource - Request body data
* @param {callback} callback - The callback that handles the response.
* @return {object} Request object
*/
watch: function(params, callback) {
var parameters = {
options: {
url: 'https://www.googleapis.com/admin/directory/v1/users/{userKey}/aliases/watch',
method: 'POST'
},
params: params,
requiredParams: ['userKey'],
pathParams: ['userKey'],
context: self
};
return createAPIRequest(parameters, callback);
}
},
photos: {
/**
* directory.users.photos.delete
*
* @desc Remove photos for the user
*
* @alias directory.users.photos.delete
* @memberOf! admin(directory_v1)
*
* @param {object} params - Parameters for request
* @param {string} params.userKey - Email or immutable Id of the user
* @param {callback} callback - The callback that handles the response.
* @return {object} Request object
*/
delete: function(params, callback) {
var parameters = {
options: {
url: 'https://www.googleapis.com/admin/directory/v1/users/{userKey}/photos/thumbnail',
method: 'DELETE'
},
params: params,
requiredParams: ['userKey'],
pathParams: ['userKey'],
context: self
};
return createAPIRequest(parameters, callback);
},
/**
* directory.users.photos.get
*
* @desc Retrieve photo of a user
*
* @alias directory.users.photos.get
* @memberOf! admin(directory_v1)
*
* @param {object} params - Parameters for request
* @param {string} params.userKey - Email or immutable Id of the user
* @param {callback} callback - The callback that handles the response.
* @return {object} Request object
*/
get: function(params, callback) {
var parameters = {
options: {
url: 'https://www.googleapis.com/admin/directory/v1/users/{userKey}/photos/thumbnail',
method: 'GET'
},
params: params,
requiredParams: ['userKey'],
pathParams: ['userKey'],
context: self
};
return createAPIRequest(parameters, callback);
},
/**
* directory.users.photos.patch
*
* @desc Add a photo for the user. This method supports patch semantics.
*
* @alias directory.users.photos.patch
* @memberOf! admin(directory_v1)
*
* @param {object} params - Parameters for request
* @param {string} params.userKey - Email or immutable Id of the user
* @param {object} params.resource - Request body data
* @param {callback} callback - The callback that handles the response.
* @return {object} Request object
*/
patch: function(params, callback) {
var parameters = {
options: {
url: 'https://www.googleapis.com/admin/directory/v1/users/{userKey}/photos/thumbnail',
method: 'PATCH'
},
params: params,
requiredParams: ['userKey'],
pathParams: ['userKey'],
context: self
};
return createAPIRequest(parameters, callback);
},
/**
* directory.users.photos.update
*
* @desc Add a photo for the user
*
* @alias directory.users.photos.update
* @memberOf! admin(directory_v1)
*
* @param {object} params - Parameters for request
* @param {string} params.userKey - Email or immutable Id of the user
* @param {object} params.resource - Request body data
* @param {callback} callback - The callback that handles the response.
* @return {object} Request object
*/
update: function(params, callback) {
var parameters = {
options: {
url: 'https://www.googleapis.com/admin/directory/v1/users/{userKey}/photos/thumbnail',
method: 'PUT'
},
params: params,
requiredParams: ['userKey'],
pathParams: ['userKey'],
context: self
};
return createAPIRequest(parameters, callback);
}
}
};
this.verificationCodes = {
/**
* directory.verificationCodes.generate
*
* @desc Generate new backup verification codes for the user.
*
* @alias directory.verificationCodes.generate
* @memberOf! admin(directory_v1)
*
* @param {object} params - Parameters for request
* @param {string} params.userKey - Email or immutable Id of the user
* @param {callback} callback - The callback that handles the response.
* @return {object} Request object
*/
generate: function(params, callback) {
var parameters = {
options: {
url: 'https://www.googleapis.com/admin/directory/v1/users/{userKey}/verificationCodes/generate',
method: 'POST'
},
params: params,
requiredParams: ['userKey'],
pathParams: ['userKey'],
context: self
};
return createAPIRequest(parameters, callback);
},
/**
* directory.verificationCodes.invalidate
*
* @desc Invalidate the current backup verification codes for the user.
*
* @alias directory.verificationCodes.invalidate
* @memberOf! admin(directory_v1)
*
* @param {object} params - Parameters for request
* @param {string} params.userKey - Email or immutable Id of the user
* @param {callback} callback - The callback that handles the response.
* @return {object} Request object
*/
invalidate: function(params, callback) {
var parameters = {
options: {
url: 'https://www.googleapis.com/admin/directory/v1/users/{userKey}/verificationCodes/invalidate',
method: 'POST'
},
params: params,
requiredParams: ['userKey'],
pathParams: ['userKey'],
context: self
};
return createAPIRequest(parameters, callback);
},
/**
* directory.verificationCodes.list
*
* @desc Returns the current set of valid backup verification codes for the specified user.
*
* @alias directory.verificationCodes.list
* @memberOf! admin(directory_v1)
*
* @param {object} params - Parameters for request
* @param {string} params.userKey - Identifies the user in the API request. The value can be the user's primary email address, alias email address, or unique user ID.
* @param {callback} callback - The callback that handles the response.
* @return {object} Request object
*/
list: function(params, callback) {
var parameters = {
options: {
url: 'https://www.googleapis.com/admin/directory/v1/users/{userKey}/verificationCodes',
method: 'GET'
},
params: params,
requiredParams: ['userKey'],
pathParams: ['userKey'],
context: self
};
return createAPIRequest(parameters, callback);
}
};
}
/**
* Exports Admin object
* @type Admin
*/
module.exports = Admin; |
/*
* Copyright 2017 Hewlett Packard Enterprise Development Company, L.P.
* Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License.
*/
define([
'underscore',
'jquery',
'find/idol/app/page/dashboard/widgets/updating-widget',
'find/idol/app/page/dashboard/update-tracker-model'
], function(_, $, UpdatingWidget, UpdateTrackerModel) {
'use strict';
const spies = jasmine.createSpyObj('spies', ['onComplete', 'onIncrement', 'onCancelled', 'doUpdate']);
const TestUpdatingWidget = UpdatingWidget.extend(spies);
describe('Updating Widget', function() {
beforeEach(function() {
jasmine.addMatchers({
toShowLoadingSpinner: function() {
return {
compare: function(actual) {
const pass = !actual.$loadingSpinner.hasClass('hide');
return {
pass: pass,
message: 'Expected the view ' +
(pass ? 'not ' : '') +
'to show a loading spinner'
};
}
}
}
});
this.widget = new TestUpdatingWidget({
name: 'Test Widget'
});
this.widget.render();
this.updateDeferred = $.Deferred();
this.updateTrackerModel = new UpdateTrackerModel();
});
afterEach(function() {
_.each(spies, function(spy) {
spy.calls.reset();
})
});
describe('when the update is synchronous', function() {
beforeEach(function() {
this.widget.doUpdate.and.callFake(function(done) {
done();
});
this.widget.update(this.updateTrackerModel);
});
it('it should increment the model when the done callback is called', function() {
expect(this.updateTrackerModel.get('count')).toBe(1);
});
it('should call onIncrement when the count increases', function() {
// count increased when the widget updated
expect(this.widget.onIncrement.calls.count()).toBe(1);
});
it('should call onComplete when the model is set to complete', function() {
this.updateTrackerModel.set('complete', true);
expect(this.widget.onComplete.calls.count()).toBe(1);
});
it('should call onCancelled when the model is set to cancelled', function() {
this.updateTrackerModel.set('cancelled', true);
expect(this.widget.onCancelled.calls.count()).toBe(1);
});
});
describe('when the update is asynchronous', function() {
beforeEach(function() {
// when a test resolves the deferred, call the done callback
this.widget.doUpdate.and.callFake(function(done) {
this.updateDeferred.done(done);
}.bind(this));
});
describe('and the update is called', function() {
beforeEach(function() {
this.widget.update(this.updateTrackerModel);
});
it('should show the loading spinner until the update completes', function() {
expect(this.widget).toShowLoadingSpinner();
this.updateDeferred.resolve();
expect(this.widget).not.toShowLoadingSpinner();
});
it('should not increment the model until the update is complete', function() {
expect(this.updateTrackerModel.get('count')).toBe(0);
this.updateDeferred.resolve();
expect(this.updateTrackerModel.get('count')).toBe(1);
});
it('should call onIncrement when the count increases', function() {
this.updateTrackerModel.increment();
expect(this.widget.onIncrement.calls.count()).toBe(1);
});
it('should call onComplete when the model is set to complete', function() {
this.updateTrackerModel.set('complete', true);
expect(this.widget.onComplete.calls.count()).toBe(1);
});
it('should call onCancelled when the model is set to cancelled', function() {
this.updateTrackerModel.set('cancelled', true);
expect(this.widget.onCancelled.calls.count()).toBe(1);
});
});
})
});
});
|
import PropTypes from 'prop-types'
import React from 'react'
import { List } from 'immutable'
import Modal from './warningmodal.js'
import Path from 'path'
const FilesList = ({ folders, folderPathToRemove, actions }) => {
const addStorageLocation = () => actions.addFolderAskPathSize()
const removeStorageLocation = folder => () => {
actions.removeFolder(folder)
actions.updateFolderToRemove()
}
const onResizeStorageLocationClick = folder => () =>
actions.resizeFolder(folder)
const onRemoveStorageLocationClick = folder => () =>
actions.updateFolderToRemove(folder.get('path'))
const hideRemoveStorageModal = () => actions.updateFolderToRemove()
// sort folders by their name
const sortedFolders = folders.sortBy(folder => folder.get('path'))
const FileList = sortedFolders.map((folder, key) => (
<div className='property pure-g' key={key}>
<div className='pure-u-3-4'>
<div className='name'>{folder.get('path')}</div>
</div>
<div className='pure-u-1-12'>
<div>{Math.floor(folder.get('free')).toString()} GB</div>
</div>
<div className='pure-u-1-12'>
<div>{Math.floor(folder.get('size')).toString()} GB</div>
</div>
<div
className='pure-u-1-24'
onClick={onResizeStorageLocationClick(folder)}
>
<div>
<i className='fa fa-edit button' />
</div>
</div>
<div
className='pure-u-1-24'
onClick={onRemoveStorageLocationClick(folder)}
>
<div>
<i className='fa fa-remove button' />
</div>
</div>
{folderPathToRemove && folderPathToRemove === folder.get('path') ? (
<Modal
title={`Remove "${Path.basename(folder.get('path'))}"?`}
message='No longer use this folder for storage? You may lose collateral if you do not have enough space to fill all contracts.'
actions={{
acceptModal: removeStorageLocation(folder),
declineModal: hideRemoveStorageModal
}}
/>
) : null}
</div>
))
return (
<div className='files section'>
<div className='property row'>
<div className='title' />
<div className='controls full'>
<div className='button left' id='edit' onClick={addStorageLocation}>
<i className='fa fa-folder-open' />
Add Storage Folder
</div>
<div className='pure-u-1-12' style={{ textAlign: 'left' }}>
Free
</div>
<div className='pure-u-1-12' style={{ textAlign: 'left' }}>
Max
</div>
<div className='pure-u-1-12' />
</div>
</div>
{FileList}
</div>
)
}
FilesList.propTypes = {
folderPathToRemove: PropTypes.string,
folders: PropTypes.instanceOf(List).isRequired
}
export default FilesList
|
/**
* Framework APIs (global - app.*)
*
* Note: View APIs are in view.js (view - view.*)
*
* @author Tim Lauv
* @created 2015.07.29
* @updated 2017.04.04
*/
;(function(app){
/**
* Universal app object creation api entry point
* ----------------------------------------------------
* @deprecated Use the detailed apis instead.
*/
app.create = function(type, config){
console.warn('DEV::Application::create() method is deprecated, use methods listed in ', app._apis, ' for alternatives');
};
/**
* Detailed api entry point
* ------------------------
* If you don't want to use .create() there you go:
*/
_.extend(app, {
//----------------view------------------
//pass in [name,] options to define view (named view will be registered)
//pass in name to get registered view def
//pass in options, true to create anonymous view
view: function(name /*or options*/, options /*or instance flag*/){
if(_.isString(name) && _.isPlainObject(options)){
return app.Core.View.register(name, options);
}
if(_.isPlainObject(name)){
var instance = options;
options = name;
var Def = app.Core.View.register(options);
if(_.isBoolean(instance) && instance) return Def.create();
return Def;
}
return app.Core.View.get(name);
},
//@deprecated---------------------
//pass in [name,] options to register (always requires a name)
//pass in [name] to get (name can be of path form)
context: function(name /*or options*/, options){
if(!options) {
if(_.isString(name) || !name)
return app.Core.Context.get(name);
else
options = name;
}
else
_.extend(options, {name: name});
console.warn('DEV::Application::context() method is deprecated, use .view() instead for', options.name || options /*as an indicator of anonymous view*/);
return app.Core.Context.register(options);
},
//--------------------------------
//pass in name, factory to register
//pass in name, options to create
//pass in [name] to get (name can be of path form)
widget: function(name, options /*or factory*/){
if(!options) return app.Core.Widget.get(name);
if(_.isFunction(options))
//register
return app.Core.Widget.register(name, options);
return app.Core.Widget.create(name, options);
//you can not register the definition when providing name, options.
},
//pass in name, factory to register
//pass in name, options to create
//pass in [name] to get (name can be of path form)
editor: function(name, options /*or factory*/){
if(!options) return app.Core.Editor.get(name);
if(_.isFunction(options))
//register
return app.Core.Editor.register(name, options);
return app.Core.Editor.create(name, options);
//you can not register the definition when providing name, options.
},
//@deprecated---------------------
regional: function(name, options){
options = options || {};
if(_.isString(name))
_.extend(options, {name: name});
else
_.extend(options, name);
console.warn('DEV::Application::regional() method is deprecated, use .view() instead for', options.name || options /*as an indicator of anonymous view*/);
return app.view(options, !options.name);
},
//--------------------------------
//(name can be of path form)
has: function(name, type){
type = type || 'View';
if(name)
return app.Core[type] && app.Core[type].has(name);
_.each(['Context', 'View', 'Widget', 'Editor'], function(t){
if(!type && app.Core[t].has(name))
type = t;
});
return type;
},
//(name can be of path form)
//always return View definition.
get: function(name, type, options){
if(!name)
return {
'Context': app.Core.Context.get(),
'View': app.Core.View.get(),
'Widget': app.Core.Widget.get(),
'Editor': app.Core.Editor.get()
};
if(_.isPlainObject(type)){
options = type;
type = undefined;
}
var Reusable, t = type || 'View';
options = _.extend({fallback: false, override: false}, options);
//try local
if(!options.override)
Reusable = (app.Core[t] && app.Core[t].get(name)) || (options.fallback && app.Core['View'].get(name));
//try remote, if we have app.viewSrcs set to load the View def dynamically
if(!Reusable && app.config && app.config.viewSrcs){
var targetJS = _.compact([app.config.viewSrcs, t.toLowerCase()/*not view.category yet*/, app.nameToPath(name)]).join('/') + '.js';
app.inject.js(
targetJS, true //sync
).done(function(){
app.debug(t, name, 'injected', 'from', app.config.viewSrcs);
if(app.has(name, t) || (options.fallback && app.has(name)))
Reusable = app.get(name, t, {fallback: true});
else
throw new Error('DEV::Application::get() loaded definitions other than required ' + name + ' of type ' + t + ' from ' + targetJS + ', please check your view name in that file!');
}).fail(function(jqXHR, settings, e){
if(!options.fallback || (t === 'View'))
throw new Error('DEV::Application::get() can NOT load definition for ' + name + ' - [' + e + ']');
else
Reusable = app.get(name, 'View');
});
}
return Reusable;
},
//**Caveat**: spray returns the region (created on $anchor), upon returning, its 'show' event has already passed.
spray: function($anchor, View /*or template or name or instance or options or svg draw(paper){} func */, options, parentCt){
var $el = $($anchor);
parentCt = parentCt || app.mainView;
//check if $anchor is already a region
var region = $el.data('region');
var regionName = region && region._name;
if(!regionName){
regionName = $el.attr('region') || _.uniqueId('anonymous-region-');
$el.attr('region', regionName);
region = parentCt.addRegion(regionName, '[region="' + regionName + '"]');
region.ensureEl(parentCt);
} else
parentCt = region.parentCt;
//see if it is an svg draw(paper){} function
if(_.isFunction(View) && View.length === 1){
//svg
return parentCt.show(regionName, {
template: '<div svg="canvas"></div>',
data: options && options.data, //only honor options.data if passed in.
svg: {
canvas: View
},
onPaperCleared: function(paper){
paper._fit($el);
},
});
}else
//view
return parentCt.show(regionName, View, options); //returns the sub-regional view.
},
icing: function(name, flag, View, options){
if(_.isBoolean(name)){
options = View;
View = flag;
flag = name;
name = 'default';
}
var regionName = ['icing', 'region', name].join('-');
if(!app.mainView.getRegion(regionName) && !_.isBoolean(name)){
options = flag;
View = name;
flag = true;
name = 'default';
}
regionName = ['icing', 'region', name].join('-');
var ir = app.mainView.getRegion(regionName);
if(flag === false){
ir.$el.hide();
ir.currentView && ir.currentView.close();
}
else {
ir.$el.show();
app.mainView.show(regionName, View, options);
}
},
coop: function(event){
var args = _.toArray(arguments);
args.unshift('app:coop');
app.trigger.apply(app, args);
args = args.slice(2);
args.unshift('app:coop-' + event);
app.trigger.apply(app, args);
return app;
},
pathToName: function(path){
if(!_.isString(path)) throw new Error('DEV::Application::pathToName() You must pass in a valid path string.');
if(_.contains(path, '.')) return path;
return path.split('/').map(_.string.humanize).map(_.string.classify).join('.');
},
nameToPath: function(name){
if(!_.isString(name)) throw new Error('DEV::Application::nameToPath() You must pass in a Reusable view name.');
if(_.contains(name, '/')) return name;
return name.split('.').map(_.string.humanize).map(_.string.slugify).join('/');
},
//----------------navigation-----------
navigate: function(options, silent){
return app.trigger('app:navigate', options, silent);
},
navPathArray: function(){
return _.compact(window.location.hash.replace('#navigate', '').split('/'));
},
//-----------------mutex---------------
lock: function(topic){
return app.Core.Lock.lock(topic);
},
unlock: function(topic){
return app.Core.Lock.unlock(topic);
},
available: function(topic){
return app.Core.Lock.available(topic);
},
//-----------------remote data------------
//returns jqXHR object (use promise pls)
remote: function(options /*or url*/, payload, restOpt){
options = options || {};
if(options.payload || payload){
payload = options.payload || payload;
return app.Core.Remote.change(options, _.extend({payload: payload}, restOpt));
}
else
return app.Core.Remote.get(options, restOpt);
},
download: function(ticket /*or url*/, options /*{params:{...}} only*/){
return app.Util.download(ticket, options);
},
upload: function(url, options){
return app.Util.upload(url, options);
},
//data push
//(ws channels)
_websockets: {},
/**
* returns a promise.
*
* Usage
* -----
* register: app.config.defaultWebsocket or app.ws(socketPath);
* receive (e): view.coop['ws-data-[channel]'] or app.onWsData = custom fn;
* send (json): app.ws(socketPath)
* .then(function(ws){ws.channel(...).json({...});}); default per channel data
* .then(function(ws){ws.send(); or ws.json();}); anything by any contract
* e.websocket = ws in .then(function(ws){})
*
* Default messaging contract
* --------------------------
* Nodejs /devserver: json {channel: '..:..', payload: {..data..}} through ws.channel('..:..').json({..data..})
* Python ASGI: json {stream: '...', payload: {..data..}} through ws.stream('...').json({..data..})
*
* Reconnecting websockets
* -----------------------
* websocket path ends with '+' will be reconnecting websocket when created.
*
*/
ws: function(socketPath, coopEvent /*or callback or options*/){
if(!app.detect('websockets')) throw new Error('DEV::Application::ws() Websocket is not supported by your browser!');
socketPath = socketPath || app.config.defaultWebsocket || '/ws';
var reconnect = false;
if(_.string.endsWith(socketPath, '+')){
socketPath = socketPath.slice(0, socketPath.length - 1);
reconnect = true;
}
var d = $.Deferred();
if(!app._websockets[socketPath]) {
app._websockets[socketPath] = new WebSocket(location.protocol.replace('http', 'ws') + '//' + location.host + socketPath);
app._websockets[socketPath].path = socketPath;
app._websockets[socketPath].reconnect = reconnect;
//events: 'open', 'error', 'close', 'message' = e.data
//apis: send(), +json(), +channel().json(), close()
app._websockets[socketPath].json = function(data){
app._websockets[socketPath].send(JSON.stringify(data));
};
app._websockets[socketPath].channel = function(channel){
return {
name: channel,
websocket: app._websockets[socketPath],
json: function(data){
app._websockets[socketPath].json({
channel: channel,
stream: channel, //alias for ASGI backends
payload: data
});
}
};
};
app._websockets[socketPath].stream = app._websockets[socketPath].channel; //alias for ASGI backends
app._websockets[socketPath].onclose = function(){
var ws = app._websockets[socketPath];
delete app._websockets[socketPath];
if(ws.reconnect)
app.ws(ws.path + '+');
};
app._websockets[socketPath].onopen = function(){
return d.resolve(app._websockets[socketPath]);
};
//general ws data stub
//server need to always send default json contract string {"channel/stream": "...", "payload": "..."}
//Opt: override this through app.ws(path).then(function(ws){ws.onmessage=...});
app._websockets[socketPath].onmessage = function(e){
//opt a. override app.onWsData to active otherwise
app.trigger('app:ws-data', {websocket: app._websockets[socketPath], raw: e.data});
//opt b. use global coop event 'ws-data-[channel]' in views directly (default json contract)
try {
var data = JSON.parse(e.data);
app.coop('ws-data-' + (data.channel || data.stream), data.payload, app._websockets[socketPath].channel(data.channel || data.stream));
}catch(ex){
console.warn('DEV::Application::ws() Websocket is getting non-default {channel: ..., payload: ...} json contract strings...');
}
};
//register coopEvent or callback function or callback options
if(coopEvent){
//onmessage callback function
if(_.isFunction(coopEvent)){
//overwrite onmessage callback function defined by framework
app._websockets[socketPath].onmessage = function(e){
coopEvent(e.data, e, app._websockets[socketPath]);
};
}
//object may contain onmessage, onerror, since onopen and onclose is done by the framework
else if(_.isPlainObject(coopEvent)){
//traverse through object to register all callback events
_.each(coopEvent, function(fn, eventName){
//guard events
if(_.contains(['onmessage', 'onerror'], eventName))
app._websockets[socketPath][eventName] = fn;
});
}
//app coop event
else if(_.isString(coopEvent)){
//trigger coop event with data from sse's onmessage callback
app._websockets[socketPath].onmessage = function(e){
app.coop('ws-data-' + coopEvent, e.data, e, app._websockets[socketPath]);
};
}
//type is not right
else
console.warn('DEV::Application::ws() The coopEvent or callback function or callbacks\' options you give is not right.');
}
}else
d.resolve(app._websockets[socketPath]);
return d.promise();
},
//data polling
//(through later.js) and emit data events/or invoke callback
_polls: {},
poll: function(url /*or {options} for app.remote()*/, occurrence, coopEvent /*or callback or options*/) {
//stop everything
if (url === false){
return _.map(this._polls, function(card) {
return card.cancel();
});
}
var schedule;
if (_.isString(occurrence) && !Number.parseInt(occurrence)) {
schedule = app.later.parse.text(occurrence);
if (schedule.error !== -1)
throw new Error('DEV::Application::poll() occurrence string unrecognizable...');
} else if (_.isPlainObject(occurrence))
schedule = occurrence;
else //number
schedule = Number(occurrence);
//make a key from url, or {url: ..., params/querys}
var key = url;
if (_.isPlainObject(key))
key = [key.url, _.reduce((_.map(key.params || key.querys, function(qV, qKey) {
return [qKey, qV].join('=');
})).sort(), function(qSignature, more) {
return [more, qSignature].join('&');
}, '')].join('?');
//cancel polling
if (occurrence === false) {
if (this._polls[key])
return this._polls[key].cancel();
console.warn('DEV::Application::poll() No polling card registered yet for ' + key);
return;
}
//cancel previous polling
if (this._polls[key])
this._polls[key].cancel();
//register polling card
if (!occurrence || !coopEvent)
throw new Error('DEV::Application::poll() You must specify an occurrence and a coop event or callback...');
var card = {
_key: key,
url: url,
eof: coopEvent,
timerId: undefined,
failed: 0,
valid: true,
occurrence: occurrence, //info only
};
this._polls[key] = card;
var call = _.isNumber(schedule) ? window.setTimeout : app.later.setTimeout;
//if coopEvent is an object. register options events before calling app.remote
if(_.isPlainObject(coopEvent)){
//save url
var temp = url;
//build url as an object for app.remote
url = {
url: temp
};
_.each(coopEvent, function(fn, eventName){
//guard for only allowing $.ajax events
if(_.contains(['beforeSend', 'error', 'dataFilter', 'success', 'complete'], eventName))
url[eventName] = fn;
});
}
var worker = function() {
app.remote(url).done(function(data) {
//callback
if (_.isFunction(card.eof))
card.eof(data, card);
//coop event
else
app.coop('poll-data-' + card.eof, data, card);
}).fail(function() {
card.failed++;
//Warning: Hardcoded 3 attemps here!
if (card.failed >= 3) card.cancel();
}).always(function() {
//go schedule the next call
if (card.valid)
card.timerId = call(worker, schedule);
});
};
//+timerType
card.timerType = (call === window.setTimeout) ? 'native' : 'later.js';
//+cancel()
var that = this;
card.cancel = function() {
this.valid = false;
if (this.timerType === 'native')
!_.isUndefined(this.timerId) && window.clearTimeout(this.timerId);
else
!_.isUndefined(this.timerId) && this.timerId.clear();
delete that._polls[this._key];
return this;
};
//make the 1st call (eagerly)
worker();
},
//-----------------ee/observer with built-in state-machine----------------
//use start('stateB') or trigger('stateA-->stateB') to swap between states
//use ['stateA-->stateB', 'stateC<-->stateB', 'stateA<--stateC', ...] in edges to constrain state changes.
ee: function(data, evtmap, edges){ //+on/once, off, +start/reset/stop/getState/getEdges; +listenTo/Once, stopListening; +trigger*;
var dispatcher;
data = _.extend({}, data, {cid: _.uniqueId('ee')});
evtmap = _.extend({
'initialize': _.noop,
'finalize': _.noop,
}, evtmap);
edges = _.reduce(edges || {}, function(mem, val, index){
var bi = val.match('(.*)<-->(.*)'),
left = val.match('(.*)<--(.*)'),
right = val.match('(.*)-->(.*)');
if(bi){
mem[bi[1] + '-->' + bi[2]] = true;
mem[bi[2] + '-->' + bi[1]] = true;
} else if (left)
mem[left[2] + '-->' + left[1]] = true;
else if (right)
mem[val] = true;
else
console.warn('DEV::Application::ee() illegal edge format: ' + val);
return mem;
}, {});
if(!_.size(edges)) edges = undefined;
dispatcher = _.extend(data, Backbone.Events);
var oldTriggerFn = dispatcher.trigger;
var currentState = '';
//add a state-machine friendly .trigger method;
dispatcher.trigger = function(){
var changeOfStates = arguments[0] && arguments[0].match('(.*)-->(.*)');
if(changeOfStates && changeOfStates.length){
var from = _.string.trim(changeOfStates[1]), to = _.string.trim(changeOfStates[2]);
//check edge constraints
if(from && to && edges && !edges[arguments[0]]){
console.warn('DEV::Application::ee() edge constraint: ' + from + '-x->' + to);
return this;
}
//check current state
if(from != currentState){
console.warn('DEV::Application::ee() current state is ' + (currentState || '\'\'') + ' not ' + from);
return this;
}
this.trigger('leave', {to: to});
//unregister event listeners in [from] state
_.each(evtmap[from], function(listener, e){
dispatcher.off(from + ':' + e);
});
//register event listeners in [to] state
_.each(evtmap[to], function(listener, e){
dispatcher.on(to + ':' + e, listener);
});
currentState = to;
this.trigger('enter', {from: from});
} else {
if(evtmap[currentState] && evtmap[currentState][arguments[0]])
arguments[0] = currentState + ':' + arguments[0];
oldTriggerFn.apply(this, arguments);
}
return this;
};
//add an internal worker swap method;
dispatcher._swap = function(targetState){
targetState = targetState || '';
this.trigger(currentState + '-->' + targetState);
return this;
};
//add a start method; (start at any state)
dispatcher.start = function(targetState){
targetState = targetState || currentState;
return this._swap(targetState);
};
//add a reset method; (reset to '' state)
dispatcher.reset = function(){
return this._swap();
};
//add a clean-up method;
dispatcher.stop = function(){
this.trigger('finalize');
this.off();
this.stopListening();
};
//add some getters;
dispatcher.getState = function(){
return currentState;
};
dispatcher.getEdges = function(){
return edges;
};
//mount shared events
_.each(evtmap, function(listener, eOrStateName){
if(!_.isFunction(listener)) return;
dispatcher.on(eOrStateName, listener);
});
this.trigger('initialize');
return dispatcher;
},
model: function(data, flat){
if(_.isBoolean(data)){
flat = data;
data = undefined;
}
if(flat)
return new Backbone.Model(data);
//Warning: Possible performance impact...(default)
return new Backbone.DeepModel(data);
/////////////////////////////////////////
},
collection: function(data){
if(data && !_.isArray(data))
throw new Error('DEV::Application::collection You need to specify an array to init a collection');
return new Backbone.Collection(data);
},
//bridge extract from app.Util.deepObjectKeys
extract: function(keypath, from){
return app.Util.deepObjectKeys.extract(keypath, from);
},
//bridge pack from app.Util.deepObjectKeys
pack: function(keypathObj, to){
return app.Util.deepObjectKeys.pack(keypathObj, to);
},
mock: function(schema, provider/*optional*/, url/*optional*/){
return app.Util.mock(schema, provider, url);
},
//----------------url params---------------------------------
param: function(key, defaultVal){
var params = app.uri(window.location.href).search(true) || {};
if(key) return params[key] || defaultVal;
return params;
},
//----------------raw animation (DON'T mix with jQuery fx)---------------
//(specifically, don't call $.animate() inside updateFn)
//(you also can NOT control the rate the browser calls updateFn, its 60 FPS all the time...)
animation: function(updateFn, condition, ctx){
var id;
var stepFn = function(t){
updateFn.call(ctx);//...update...(1 tick)
if(!condition || (condition && condition.call(ctx)))//...condition...(to continue)
move();
};
var move = function(){
if(id === undefined) return;
id = app._nextFrame(stepFn);
};
var stop = function(){
app._cancelFrame(id);
id = undefined;
};
return {
start: function(){id = -1; move();},
stop: stop
};
},
_nextFrame: function(stepFn){
//return request id
return window.requestAnimationFrame(stepFn);
},
_cancelFrame: function(id){
return window.cancelAnimationFrame(id);
},
//effects see https://daneden.github.io/animate.css/
//sample usage: 'ready' --> app.animateItems();
animateItems: function(selector /*or $items*/, effect, stagger){
var $selector = $(selector);
if(_.isNumber(effect)){
stagger = effect;
effect = undefined;
}
effect = effect || 'flipInX';
stagger = stagger || 150;
var inOrOut = /In/.test(effect)? 1: (/Out/.test(effect)? -1: 0);
$selector.each(function(i, el){
var $el = $(el);
//////////////////different than region.show effect because of stagger delay//////////////////
if(inOrOut)
if(inOrOut === 1) $el.css('opacity', 0);
else $el.css('opacity', 1);
//////////////////////////////////////////////////////////////////////////////////////////////
_.delay(function($el){
var fxName = effect + ' animated';
$el.anyone(app.ADE, function(){
$el.removeClass(fxName);
}).addClass(fxName);
///////////////reset opacity immediately, not after ADE///////////////
if(inOrOut)
if(inOrOut === 1) $el.css('opacity', 1);
else $el.css('opacity', 0);
//////////////////////////////////////////////////////////////////////
}, i * stagger, $el);
});
},
//Built-in web worker utility, bridged from app.Util.worker.
worker: function(name/*web worker's name*/, coopEOrCallbackOrOpts){
return app.Util.worker(name, coopEOrCallbackOrOpts);
},
//Built-in Server-Sent Event(SSE) utility, bridged from app.Util.sse
sse: function(url/*sse's url*/, topics/*['...', '...']*/, coopEOrCallbackOrOpts){
return app.Util.sse(url, topics, coopEOrCallbackOrOpts);
},
//----------------config.rapidEventDelay wrapped util--------------------
//**Caveat**: if using cached version, pass `this` and other upper scope vars into fn as arguments, else
//these in fn will be cached forever and might no longer exist or point to the right thing when called...
throttle: function(fn, ms, cacheId){
ms = ms || app.config.rapidEventDelay;
fn = _.throttle(fn, ms);
if(!cacheId)
return fn;
//cached version (so you can call right after wrapping it)
this._tamedFns = this._tamedFns || {};
var key = fn + cacheId + '-throttle' + ms;
if(!this._tamedFns[key])
this._tamedFns[key] = fn;
return this._tamedFns[key];
},
debounce: function(fn, ms, cacheId){
ms = ms || app.config.rapidEventDelay;
fn = _.debounce(fn, ms);
if(!cacheId)
return fn;
//cached version (so you can call right after wrapping it)
this._tamedFns = this._tamedFns || {};
var key = fn + cacheId + '-debounce' + ms;
if(!this._tamedFns[key])
this._tamedFns[key] = fn;
return this._tamedFns[key];
},
//app wide e.preventDefault() util
preventDefaultE: function(e){
var $el = $(e.target);
//Caveat: this clumsy bit here is due to the in-ability to check on the 'action-*' attributes on e.target...
if($el.is('label') || $el.is('i') || $el.is('img') || $el.is('span') || $el.is('input') || $el.is('textarea') || $el.is('select') || ($el.is('a') && $el.attr('href')))
return;
e.preventDefault();
},
//wait until all targets fires e (asynchronously) then call the callback with targets (e.g [this.show(), ...], 'ready')
until: function(targets, e, callback){
targets = _.compact(targets);
cb = _.after(targets.length, function(){
callback(targets);
});
_.each(targets, function(t){
t.once(e, cb);
});
},
//----------------markdown-------------------
//options.marked, options.hljs
//https://guides.github.com/features/mastering-markdown/
//our addition:
// ^^^class class2 class3 ...
// ...
// ^^^
markdown: function(md, $anchor /*or options*/, options){
options = options || (!_.isjQueryObject($anchor) && $anchor) || {};
//render content
var html = marked(md, app.debug('marked options are', _.extend(app.config.marked, (options.marked && options.marked) || options, _.isjQueryObject($anchor) && $anchor.data('marked')))), hljs = window.hljs;
//highlight code (use ```language to specify type)
if(hljs){
hljs.configure(app.debug('hljs options are', _.extend(app.config.hljs, options.hljs, _.isjQueryObject($anchor) && $anchor.data('hljs'))));
var $html = $('<div>' + html + '</div>');
$html.find('pre code').each(function(){
hljs.highlightBlock(this);
});
html = $html.html();
}
if(_.isjQueryObject($anchor))
return $anchor.html(html).addClass('md-content');
return html;
},
//----------------notify/overlay/popover---------------------
notify: function(title /*or options*/, msg, type /*or otherOptions*/, otherOptions){
if(_.isString(title)){
if(_.isPlainObject(type)){
otherOptions = type;
type = undefined;
}
if(otherOptions && otherOptions.icon){
//theme awesome ({.icon, .more})
$.amaran(_.extend({
theme: 'awesome ' + (type || 'ok'),
//see http://ersu.me/article/amaranjs/amaranjs-themes for types
content: {
title: title,
message: msg,
info: otherOptions.more || ' ',
icon: otherOptions.icon
}
}, otherOptions));
} else {
//custom theme
$.amaran(_.extend({
content: {
themeName: 'stagejs',
title: title,
message: msg,
type: type || 'info',
},
themeTemplate: app.NOTIFYTPL
}, otherOptions));
}
}
else
$.amaran(title);
},
//overlay or popover
prompt: function(view, anchor, placement, options){
if(_.isFunction(view))
view = new view();
else if(_.isString(view))
view = app.get(view).create();
//is popover
if(_.isString(placement)){
options = options || {};
options.placement = placement;
return view.popover(anchor, options);
}
//is overlay
options = placement;
return view.overlay(anchor, options);
},
//----------------i18n-----------------------
i18n: function(key, ns){
if(key){
//insert translations to current locale
if(_.isPlainObject(key))
return I18N.insertTrans(key);
//return a translation for specified key, ns/module
return String(key).i18n(ns);
}
//otherwise, collect available strings (so far) into an i18n object.
return I18N.getResourceJSON(null, false);
},
//----------------debug----------------------
//bridge app.debug()
debug: function(){
return app.Util.debugHelper.debug.apply(null, arguments);
},
//bridge app.locate()
locate: function(name /*el or $el*/){
return app.Util.debugHelper.locate(name);
},
//bridge app.profile()
profile: function(name /*el or $el*/){
return app.Util.debugHelper.profile(name);
},
//bridge app.mark()
mark: function(name /*el or $el*/){
return app.Util.debugHelper.mark(name);
},
//bridge app.reload()
reload: function(name, override/*optional*/){
return app.Util.debugHelper.reload(name, override);
},
inject: {
js: function(){
return app.Util.inject.apply(null, arguments);
},
tpl: function(){
return app.Util.Tpl.remote.apply(app.Util.Tpl, arguments);
},
css: function(){
return loadCSS.apply(null, arguments);
}
},
detect: function(feature, provider/*optional*/){
if(!provider)
provider = Modernizr;
return app.extract(feature, provider) || false;
},
//--------3rd party lib pass-through---------
// js-cookie (former jquery-cookie)
//.set(), .get(), .remove()
cookie: Cookies,
// store.js (localStorage)
//.set(), .get(), .getAll(), .remove(), .clear()
store: store.enabled && store,
// validator.js (var type and val validation, e.g form editor validation)
validator: validator,
// moment.js (date and time)
moment: moment,
// URI.js (uri,query and hash in the url, e.g in app.param())
uri: URI,
// later.js (schedule repeated workers, e.g in app.poll())
later: later,
// faker.js (mock data generator, e.g in app.mock())
faker: faker,
});
//editor rules
app.editor.validator = app.editor.rule = function(name, fn){
if(!_.isString(name)) throw new Error('DEV::Validator:: You must specify a validator/rule name to use.');
return app.Core.Editor.addRule(name, fn);
};
//alias
app.page = app.context;
app.area = app.regional;
app.curtain = app.icing;
/**
* API summary
*/
app._apis = [
'ee', 'model', 'collection', 'mock',
//view registery
'view', 'widget', 'editor', 'editor.validator - @alias:editor.rule',
//global action locks
'lock', 'unlock', 'available',
//utils
'has', 'get', 'spray', 'coop', 'navigate', 'navPathArray', 'icing/curtain', 'i18n', 'param', 'animation', 'animateItems', 'throttle', 'debounce', 'preventDefaultE', 'until',
//com
'remote', 'download', 'upload', 'ws', 'poll', 'worker', 'sse',
//3rd-party lib short-cut
'extract', 'markdown', 'notify', 'prompt', //wraps
'cookie', 'store', 'moment', 'uri', 'validator', 'later', 'faker', //direct refs
//supportive
'debug', 'detect', 'reload', 'locate', 'profile', 'mark', 'nameToPath', 'pathToName', 'inject.js', 'inject.tpl', 'inject.css',
//@deprecated
'create - @deprecated', 'regional - @deprecated', 'context - @alias:page - @deprecated'
];
/**
* Statics
*/
//animation done events used in Animate.css
//Caveat: if you use $el.one(app.ADE) but still got 2+ callback calls, the browser is firing the default and prefixed events at the same time...
//use $el.anyone() to fix the problem in using $el.one()
app.ADE = 'animationend webkitAnimationEnd MSAnimationEnd oAnimationEnd transitionend webkitTransitionEnd oTransitionEnd MSTransitionEnd';
//notification template
app.NOTIFYTPL = Handlebars.compile('<div class="alert alert-dismissable alert-{{type}}"><button data-dismiss="alert" class="close" type="button">×</button><strong>{{title}}</strong> {{{message}}}</div>');
})(Application); |
// Base64 encoder/decoder with UTF-8 support
//
// Copyright (c) 2011 Vitaly Puzrin
// Copyright (c) 2011 Aleksey V Zapparov
//
// Author: Aleksey V Zapparov AKA ixti (http://www.ixti.net/)
//
// 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.
// Based on original artworks of base64 encoder/decoder by [Mozilla][1]
// [1]: http://lxr.mozilla.org/mozilla/source/extensions/xml-rpc/src/nsXmlRpcClient.js
'use strict';
/* eslint-env browser */
/* eslint-disable no-bitwise */
function noop() {}
var logger = { warn: noop, error: noop },
padding = '=',
chrTable = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz' +
'0123456789+/',
binTable = [
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63,
52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, 0, -1, -1,
-1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1,
-1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1
];
if (window.console) {
logger = window.console;
logger.warn = logger.warn || logger.error || logger.log || noop;
logger.error = logger.error || logger.warn || logger.log || noop;
}
// internal helpers //////////////////////////////////////////////////////////
function utf8Encode(str) {
var bytes = [], offset = 0, length, char;
str = encodeURI(str);
length = str.length;
while (offset < length) {
char = str.charAt(offset);
offset += 1;
if (char !== '%') {
bytes.push(char.charCodeAt(0));
} else {
char = str.charAt(offset) + str.charAt(offset + 1);
bytes.push(parseInt(char, 16));
offset += 2;
}
}
return bytes;
}
function utf8Decode(bytes) {
var chars = [], offset = 0, length = bytes.length, c1, c2, c3;
while (offset < length) {
c1 = bytes[offset];
c2 = bytes[offset + 1];
c3 = bytes[offset + 2];
if (c1 < 128) {
chars.push(String.fromCharCode(c1));
offset += 1;
} else if (191 < c1 && c1 < 224) {
chars.push(String.fromCharCode(((c1 & 31) << 6) | (c2 & 63)));
offset += 2;
} else {
chars.push(String.fromCharCode(((c1 & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63)));
offset += 3;
}
}
return chars.join('');
}
// public api ////////////////////////////////////////////////////////////////
function encode(str) {
var result = '',
bytes = utf8Encode(str),
length = bytes.length,
i;
// Convert every three bytes to 4 ascii characters.
for (i = 0; i < (length - 2); i += 3) {
result += chrTable[bytes[i] >> 2];
result += chrTable[((bytes[i] & 0x03) << 4) + (bytes[i + 1] >> 4)];
result += chrTable[((bytes[i + 1] & 0x0f) << 2) + (bytes[i + 2] >> 6)];
result += chrTable[bytes[i + 2] & 0x3f];
}
// Convert the remaining 1 or 2 bytes, pad out to 4 characters.
if (length % 3) {
i = length - (length % 3);
result += chrTable[bytes[i] >> 2];
if ((length % 3) === 2) {
result += chrTable[((bytes[i] & 0x03) << 4) + (bytes[i + 1] >> 4)];
result += chrTable[(bytes[i + 1] & 0x0f) << 2];
result += padding;
} else {
result += chrTable[(bytes[i] & 0x03) << 4];
result += padding + padding;
}
}
return result;
}
function decode(data) {
var value, code, idx = 0,
bytes = [],
leftbits = 0, // number of bits decoded, but yet to be appended
leftdata = 0; // bits decoded, but yet to be appended
// Convert one by one.
for (idx = 0; idx < data.length; idx += 1) {
code = data.charCodeAt(idx);
value = binTable[code & 0x7F];
if (value === -1) {
// Skip illegal characters and whitespace
logger.warn('Illegal characters (code=' + code + ') in position ' + idx);
} else {
// Collect data into leftdata, update bitcount
leftdata = (leftdata << 6) | value;
leftbits += 6;
// If we have 8 or more bits, append 8 bits to the result
if (leftbits >= 8) {
leftbits -= 8;
// Append if not padding.
if (padding !== data.charAt(idx)) {
bytes.push((leftdata >> leftbits) & 0xFF);
}
leftdata &= (1 << leftbits) - 1;
}
}
}
// If there are any bits left, the base64 string was corrupted
if (leftbits) {
logger.error('Corrupted base64 string');
return null;
}
return utf8Decode(bytes);
}
exports.encode = encode;
exports.decode = decode;
|
module.exports = require("npm:[email protected]/dist/acorn"); |
import actionTypes from '../../client/actions/types';
const defaultState = {
data: {},
errors: 'Not Found',
};
export default function domainDetailReducer(state = defaultState, action = {}) {
switch (action.type) {
case actionTypes.getDomainDetail:
return Object.assign({}, state, {
data: action.data.domain,
errors: action.errors,
});
default:
return state;
}
}
|
// This is a manifest file that'll be compiled into including all the files listed below.
// Add new JavaScript/Coffee code in separate files in this directory and they'll automatically
// be included in the compiled file accessible from http://example.com/assets/application.js
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// the compiled file.
//
//= require jquery
//= require jquery_ujs
//= require_tree .
|
/**
* Copyright 2014 Pacific Controls Software Services LLC (PCSS). All Rights Reserved.
*
* This software is the property of Pacific Controls Software Services LLC and its
* suppliers. The intellectual and technical concepts contained herein are proprietary
* to PCSS. Dissemination of this information or reproduction of this material is
* strictly forbidden unless prior written permission is obtained from Pacific
* Controls Software Services.
*
* PCSS MAKES NO REPRESENTATION OR WARRANTIES ABOUT THE SUITABILITY OF THE SOFTWARE,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF
* MERCHANTANILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGMENT. PCSS SHALL
* NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING
* OR DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES.
*/
/**
* Version : 1.0
* User : pcseg306
* Function : Service for Super/client Admin Notification Functions
*/
gxMainApp.factory("adminFunctionsService", function($http,$rootScope,gxAPIServiceWrapper){
var _notificationArray = [];
var _resultPromise;
var _getNotificationArray = function() {
_resultPromise = gxAPIServiceWrapper.get("models/superAdmin/dummySuperAdminNotification.json");
console.log(_resultPromise);
return _resultPromise;
}
return{
notificationArray: _notificationArray,
getNotificationArray: _getNotificationArray,
resultPromise : _resultPromise
};
}); |
define(function(require) {
var test = require('../../../test')
var count = 0
require.async('./a', function(a) {
test.assert(a.name === 'a', 'load CMD module file')
done()
})
require.async('./b.js', function() {
test.assert(global.SPECS_MODULES_ASYNC === true, 'load normal script file')
global.SPECS_MODULES_ASYNC = undefined
done()
})
require.async(['./c1', './c2'], function(c1, c2) {
test.assert(c1.name === 'c1', c1.name)
test.assert(c2.name === 'c2', c2.name)
done()
})
function done() {
if (++count === 3) {
test.next()
}
}
});
|
const fs = require('fs');
const path = require('path');
const cleanCss = require('../../index.js');
module.exports = {
name : 'basic test',
this : function () {
const str = fs.readFileSync(path.resolve('test/styles/basic.dirty.scss'), 'utf8');
const clean = cleanCss({
css : str
});
return clean;
},
isEqual : function () {
return fs.readFileSync(path.resolve('test/styles/basic.clean.scss'), 'utf8');
}
}; |
angular.module('starter.controllers', [])
// A simple controller that fetches a list of data from a service
.controller('PetIndexCtrl', function($scope, PetService) {
// "Pets" is a service returning mock data (services.js)
$scope.pets = PetService.all();
})
// A simple controller that shows a tapped item's data
.controller('PetDetailCtrl', function($scope, $stateParams, PetService) {
// "Pets" is a service returning mock data (services.js)
$scope.pet = PetService.get($stateParams.petId);
})
// getting fake favor data
.controller('FavorIndexCtrl', function($scope, FavorService) {
$scope.favors = FavorService.all();
})
// A simple controller that shows a tapped item's data
.controller('FavorDetailCtrl', function($scope, $stateParams, FavorService) {
// "Pets" is a service returning mock data (services.js)
$scope.favor = FavorService.get($stateParams.favorId);
});
|
// Copyright 2011, 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.
var kDefaultNumberOfResampleRanges = 11;
function WaveTable(name, context) {
this.name = name;
this.context = context;
this.sampleRate = context.sampleRate;
this.url = "wave-tables/" + this.name;
this.waveTableSize = 4096; // hard-coded for now
this.buffer = 0;
this.numberOfResampleRanges = kDefaultNumberOfResampleRanges;
}
WaveTable.prototype.getWaveDataForPitch = function(pitchFrequency) {
var nyquist = 0.5 * this.sampleRate;
var lowestNumPartials = this.getNumberOfPartialsForRange(0);
var lowestFundamental = nyquist / lowestNumPartials;
// Find out pitch range
var ratio = pitchFrequency / lowestFundamental;
var pitchRange = ratio == 0.0 ? 0 : Math.floor(Math.log(ratio) / Math.LN2);
if (pitchRange < 0)
pitchRange = 0;
// Too bad, we'll alias if pitch is greater than around 5KHz :)
if (pitchRange >= this.numberOfResampleRanges)
pitchRange = this.numberOfResampleRanges - 1;
return this.buffers[pitchRange];
}
WaveTable.prototype.getNumberOfPartialsForRange = function(j) {
// goes from 1024 -> 4 @ 44.1KHz (and do same for 48KHz)
// goes from 2048 -> 8 @ 96KHz
var npartials = Math.pow(2, 1 + this.numberOfResampleRanges - j);
if (this.getSampleRate() > 48000.0)
npartials *= 2; // high sample rate allows more harmonics at given fundamental
return npartials;
}
WaveTable.prototype.getWaveTableSize = function() {
return this.waveTableSize;
}
WaveTable.prototype.getSampleRate = function() {
return this.sampleRate;
}
WaveTable.prototype.getRateScale = function() {
return this.getWaveTableSize() / this.getSampleRate();
}
WaveTable.prototype.getNumberOfResampleRanges = function() {
this.numberOfResampleRanges;
}
WaveTable.prototype.getName = function() {
return this.name;
}
WaveTable.prototype.load = function(callback) {
var request = new XMLHttpRequest();
request.open("GET", this.url, true);
var wave = this;
request.onload = function() {
// Get the frequency-domain waveform data.
var f = eval('(' + request.responseText + ')');
// Copy into more efficient Float32Arrays.
var n = f.real.length;
frequencyData = { "real": new Float32Array(n), "imag": new Float32Array(n) };
wave.frequencyData = frequencyData;
for (var i = 0; i < n; ++i) {
frequencyData.real[i] = f.real[i];
frequencyData.imag[i] = f.imag[i];
}
wave.createBuffers();
if (callback)
callback(wave);
};
request.onerror = function() {
alert("error loading: " + wave.url);
};
request.send();
}
WaveTable.prototype.print = function() {
var f = this.frequencyData;
var info = document.getElementById("info");
var s = "";
for (var i = 0; i < 2048; ++i) {
s += "{" + f.real[i] + ", " + f.imag[i] + "}, <br>";
}
info.innerHTML = s;
}
WaveTable.prototype.printBuffer = function(buffer) {
var info = document.getElementById("info");
var s = "";
for (var i = 0; i < 4096; ++i) {
s += buffer[i] + "<br>";
}
info.innerHTML = s;
}
// WaveTable.prototype.createBuffers = function() {
// var f = this.frequencyData;
//
// var n = 4096;
//
// var fft = new FFT(n, 44100);
//
// // Copy from loaded frequency data and scale.
// for (var i = 0; i < n / 2; ++i) {
// fft.real[i] = 4096 * f.real[i];
// fft.imag[i] = 4096 * f.imag[i];
// }
//
// // Now do inverse FFT
// this.data = fft.inverse();
// var data = this.data;
//
// this.buffer = context.createBuffer(1, data.length, 44100);
//
// // Copy data to the buffer.
// var p = this.buffer.getChannelData(0);
// for (var i = 0; i < data.length; ++i) {
// p[i] = data[i];
// }
// }
// Convert into time-domain wave tables.
// We actually create several of them for non-aliasing playback at different playback rates.
WaveTable.prototype.createBuffers = function() {
// resample ranges
//
// let's divide up versions of our waves based on the maximum fundamental frequency we're
// resampling at. Let's use fundamental frequencies based on dividing Nyquist by powers of two.
// For example for 44.1KHz sample-rate we have:
//
// ranges
// ----------------------------------
// 21Hz, 43Hz, 86Hz, 172Hz, 344Hz, 689Hz, 1378Hz, 2756Hz, 5512Hz, 11025Hz, 22050Hz <-- 44.1KHz
// 23Hz, 47Hz, 94Hz, 187Hz, 375Hz, 750Hz, 1500Hz, 3000Hz, 6000Hz, 12000Hz, 24000Hz, 48000Hz <-- 96KHz
//
// and number of partials:
//
// 1024, 512, 256, 128, 64, 32, 16, 8, 4, 2, 1
// 2048, 1024, 512, 256, 128, 64, 32, 16, 8, 4, 2, 1
//
// But it's probably OK if we skip the very highest fundamental frequencies and only
// go up to 5512Hz, so we have a total of 9 resample ranges
//
// 0 1 2 3 4 5 6 7 8
// The FFT size needs to be at least 2048 @ 44.1KHz and 4096 @ 96KHz
//
// So let's try to use FFT size of 4096 all the time and pull out the harmonics we want
//
this.buffers = new Array();
var finalScale = 1.0;
for (var j = 0; j < this.numberOfResampleRanges; ++j) {
var n = this.waveTableSize;
var frame = new FFT(n, this.sampleRate);
// Copy from loaded frequency data and scale.
var f = this.frequencyData;
var scale = n;
for (var i = 0; i < n / 2; ++i) {
frame.real[i] = scale * f.real[i];
frame.imag[i] = scale * f.imag[i];
}
var realP = frame.real;
var imagP = frame.imag;
// Find the starting bin where we should start clearing out
// (we need to clear out the highest frequencies to band-limit the waveform)
var fftSize = n;
var halfSize = fftSize / 2;
var npartials = this.getNumberOfPartialsForRange(j);
// Now, go through and cull out the aliasing harmonics...
for (var i = npartials + 1; i < halfSize; i++) {
realP[i] = 0.0;
imagP[i] = 0.0;
}
// Clear packed-nyquist if necessary
if (npartials < halfSize)
imagP[0] = 0.0;
// Clear any DC-offset
realP[0] = 0.0;
// For the first resample range, find power and compute scale.
if (j == 0) {
var power = 0;
for (var i = 1; i < halfSize; ++i) {
x = realP[i];
y = imagP[i];
power += x * x + y * y;
}
power = Math.sqrt(power) / fftSize;
finalScale = 0.5 / power;
// window.console.log("power = " + power);
}
// Great, now do inverse FFT into our wavetable...
var data = frame.inverse();
// Create mono AudioBuffer.
var buffer = this.context.createBuffer(1, data.length, this.sampleRate);
// Copy data to the buffer.
var p = buffer.getChannelData(0);
for (var i = 0; i < data.length; ++i) {
p[i] = finalScale * data[i];
}
this.buffers[j] = buffer;
}
}
WaveTable.prototype.displayWaveData = function() {
var data = this.data;
var n = data.length;
var s = "";
for (var i = 0; i < n; ++i) {
s += data[i].toFixed(3) + "<br> ";
}
var info = document.getElementById("info");
info.innerHTML = s;
}
|
/**
* Created by maomao on 2020/4/20.
*/
Java.perform(function() {
var cn = "android.telephony.SubscriptionManager";
var target = Java.use(cn);
if (target) {
target.addOnSubscriptionsChangedListener.overloads[0].implementation = function(dest) {
var myArray=new Array()
myArray[0] = "SENSITIVE" //INTERESTED & SENSITIVE
myArray[1] = cn + "." + "addOnSubscriptionsChangedListener";
myArray[2] = Java.use("android.util.Log").getStackTraceString(Java.use("java.lang.Exception").$new()).split('\n\tat');
send(myArray);
return this.addOnSubscriptionsChangedListener.overloads[0].apply(this, arguments);
};
// target.addOnSubscriptionsChangedListener.overloads[1].implementation = function(dest) {
// var myArray=new Array()
// myArray[0] = "SENSITIVE" //INTERESTED & SENSITIVE
// myArray[1] = cn + "." + "addOnSubscriptionsChangedListener";
// myArray[2] = Java.use("android.util.Log").getStackTraceString(Java.use("java.lang.Exception").$new()).split('\n\tat');
// send(myArray);
// return this.addOnSubscriptionsChangedListener.overloads[1].apply(this, arguments);
// };
target.getActiveSubscriptionInfo.overloads[0].implementation = function(dest) {
var myArray=new Array()
myArray[0] = "SENSITIVE" //INTERESTED & SENSITIVE
myArray[1] = cn + "." + "getActiveSubscriptionInfo";
myArray[2] = Java.use("android.util.Log").getStackTraceString(Java.use("java.lang.Exception").$new()).split('\n\tat');
send(myArray);
return this.getActiveSubscriptionInfo.overloads[0].apply(this, arguments);
};
// target.getActiveSubscriptionInfo.overloads[1].implementation = function(dest) {
// var myArray=new Array()
// myArray[0] = "SENSITIVE" //INTERESTED & SENSITIVE
// myArray[1] = cn + "." + "getActiveSubscriptionInfo";
// myArray[2] = Java.use("android.util.Log").getStackTraceString(Java.use("java.lang.Exception").$new()).split('\n\tat');
// send(myArray);
// return this.getActiveSubscriptionInfo.overloads[1].apply(this, arguments);
// };
target.getActiveSubscriptionInfoCount.implementation = function(dest) {
var myArray=new Array()
myArray[0] = "SENSITIVE" //INTERESTED & SENSITIVE
myArray[1] = cn + "." + "getActiveSubscriptionInfoCount";
myArray[2] = Java.use("android.util.Log").getStackTraceString(Java.use("java.lang.Exception").$new()).split('\n\tat');
send(myArray);
return this.getActiveSubscriptionInfoCount.apply(this, arguments);
};
target.getActiveSubscriptionInfoForSimSlotIndex.implementation = function(dest) {
var myArray=new Array()
myArray[0] = "SENSITIVE" //INTERESTED & SENSITIVE
myArray[1] = cn + "." + "getActiveSubscriptionInfoForSimSlotIndex";
myArray[2] = Java.use("android.util.Log").getStackTraceString(Java.use("java.lang.Exception").$new()).split('\n\tat');
send(myArray);
return this.getActiveSubscriptionInfoForSimSlotIndex.apply(this, arguments);
};
target.getActiveSubscriptionInfoList.implementation = function(dest) {
var myArray=new Array()
myArray[0] = "SENSITIVE" //INTERESTED & SENSITIVE
myArray[1] = cn + "." + "getActiveSubscriptionInfoList";
myArray[2] = Java.use("android.util.Log").getStackTraceString(Java.use("java.lang.Exception").$new()).split('\n\tat');
send(myArray);
return this.getActiveSubscriptionInfoList.apply(this, arguments);
};
}
}); |
"use strict";
const chalk = require("chalk");
const readline = require("readline");
/**
* Fill screen with blank lines, move to "0" afterwards and clear screen afterwards.
* Note that it is still possible to "scroll back" afterwards.
*
* Function performs nothing in case the stdout is NOT a TTY.
*/
exports.cls = function() {
if (process.stdout.isTTY) {
const blank = "\n".repeat(process.stdout.rows);
console.log(blank);
readline.cursorTo(process.stdout, 0, 0);
readline.clearScreenDown(process.stdout);
}
};
/**
* A less soft version of `cls` above which completely clears out the screen,
* without leaving the option to scroll up again.
*
* Function performs nothing in case the stdout is NOT a TTY.
*/
exports.hardCls = function() {
if (process.stdout.isTTY) {
process.stdout.write(
process.platform === "win32" ? "\x1Bc" : "\x1B[2J\x1B[3J\x1B[H"
);
}
};
exports.formatFirstLineMessage = function(text) {
return chalk.bgWhite.black(text);
};
|
const assert = require('assert')
const crypto = require('crypto')
const { createRequest } = require("../util/util")
describe('测试搜索是否正常', () => {
it('获取到的数据的 name 应该和搜索关键词一致', done => {
const keywords = "海阔天空"
const type = 1
const limit = 30
const data = 's=' + keywords + '&limit=' + limit + '&type=' + type + '&offset=0'
createRequest('/api/search/pc/', 'POST', data)
.then(result => {
console.log(JSON.parse(result).result.songs[0].mp3Url)
assert(JSON.parse(result).result.songs[0].name === '海阔天空')
done()
})
.catch(err => {
done(err)
})
})
}) |
export default function collapseDuplicateDeclarations() {
return (root) => {
root.walkRules((node) => {
let seen = new Map()
let droppable = new Set([])
node.walkDecls((decl) => {
// This could happen if we have nested selectors. In that case the
// parent will loop over all its declarations but also the declarations
// of nested rules. With this we ensure that we are shallowly checking
// declarations.
if (decl.parent !== node) {
return
}
if (seen.has(decl.prop)) {
droppable.add(seen.get(decl.prop))
}
seen.set(decl.prop, decl)
})
for (let decl of droppable) {
decl.remove()
}
})
}
}
|
module.exports = {
"env": {
"browser": true,
"commonjs": true,
"es6": true,
"jasmine" : true
},
"extends": "eslint:recommended",
"parserOptions": {
"sourceType": "module"
},
"rules": {
"no-mixed-spaces-and-tabs": [2, "smart-tabs"],
"linebreak-style": [
"error",
"unix"
],
"quotes": [
"error",
"single"
],
"semi": [
"error",
"always"
]
}
}; |
version https://git-lfs.github.com/spec/v1
oid sha256:42fcecf8fdabe110af986ac81bb56b598f5a3fa59c6d0c4cc8b80daa2dca0473
size 1121
|
$(document).ready(function(){
var Previewer = {
preview: function(content, output) {
$.ajax({
type: 'POST',
url: "/govspeak",
data: { govspeak: content.val() },
dataType: 'json'
}).success(function(data){
output.html(data['govspeak']);
});
}
};
$("[data-preview]").each(function(){
var source_field = $($(this).data('preview-for'));
var render_area = $(this);
source_field.keyup(function() {
Previewer.preview(source_field, render_area);
})
});
$('textarea').autosize();
});
|
/**
* @author Richard Davey <[email protected]>
* @copyright 2020 Photon Storm Ltd.
* @license {@link https://opensource.org/licenses/MIT|MIT License}
*/
/**
* @namespace Phaser.Structs
*/
module.exports = {
List: require('./List'),
Map: require('./Map'),
ProcessQueue: require('./ProcessQueue'),
RTree: require('./RTree'),
Set: require('./Set'),
Size: require('./Size')
};
|
YUI.add("yuidoc-meta", function(Y) {
Y.YUIDoc = { meta: {
"classes": [
"Audio"
],
"modules": [
"gallery-audio"
],
"allModules": [
{
"displayName": "gallery-audio",
"name": "gallery-audio"
}
]
} };
}); |
'use strict';
var fs = require('fs'),
util = require('util'),
Duplexify = require('duplexify'),
_ = require('lodash'),
su = require('bindings')('serialutil.node'),
fsu = require('./fsutil'),
pins = require('./pins'),
Dto = require('./dto'),
dto = new Dto(__dirname + '/../templates/uart.dts');
var DEFAULT_OPTIONS;
function onopen(uart, options) {
if (uart._rxfd !== -1 && uart._txfd !== -1) {
su.setRawMode(uart._rxfd);
uart.baudRate(options.baudRate);
uart.characterSize(options.characterSize);
uart.parity(options.parity);
uart.stopBits(options.stopBits);
setImmediate(function () {
uart.emit('open');
uart.emit('ready');
});
}
}
function onclose(uart) {
if (uart._rxfd === -1 && uart._txfd === -1) {
setImmediate(function () {
uart.emit('close');
});
}
}
function createStreams(uart, options) {
uart._rxfd = -1;
uart._txfd = -1;
uart._rxstream = fs.createReadStream(uart.devPath, {
highWaterMark: options.highWaterMark,
encoding: options.encoding
});
uart._txstream = fs.createWriteStream(uart.devPath, {
highWaterMark: options.highWaterMark,
encoding: options.encoding,
flags: 'r+'
});
uart._rxstream.once('open', function (rxfd) {
uart._rxfd = rxfd;
onopen(uart, options);
});
uart._txstream.once('open', function (txfd) {
uart._txfd = txfd;
onopen(uart, options);
});
uart._rxstream.once('close', function () {
uart._rxfd = -1;
onclose(uart);
});
uart._txstream.once('close', function () {
uart._txfd = -1;
onclose(uart);
});
// TODO - test error handling
uart.setReadable(uart._rxstream);
uart.setWritable(uart._txstream);
}
function waitForUart(uart, options) {
fsu.waitForFile(uart.devPath, function (err, devPath) {
if (err) {
return uart.emit('error', err);
}
createStreams(uart, options);
});
}
function Uart(uartDef, options) {
var badPin,
config;
if (!(this instanceof Uart)) {
return new Uart(uartDef);
}
options = options ? _.defaults(options, DEFAULT_OPTIONS) : DEFAULT_OPTIONS;
// Consider calling Duplexify with the allowHalfOpen option set to false.
// It's super-class (Duplex) will then ensure that this.end is called when
// the read stream fires the 'end' event. (see:
// https://github.com/joyent/node/blob/v0.10.25/lib/_stream_duplex.js)
Duplexify.call(this, null, null);
if (typeof uartDef === 'string') {
this.uartDef = null;
this.devPath = uartDef;
this.name = null;
waitForUart(this, options);
} else {
if (uartDef.txPin.uart === undefined) {
badPin = new Error(uartDef.txPin + ' doesn\'t support uarts');
} else if (uartDef.rxPin.uart === undefined) {
badPin = new Error(uartDef.rxPin + ' doesn\'t support uarts');
}
if (badPin) {
setImmediate(function () {
this.emit('error', badPin);
}.bind(this));
return;
}
this.uartDef = uartDef;
this.devPath = '/dev/ttyO' + uartDef.id;
this.name = 'bot_uart' + uartDef.id;
config = {
txHeader: this.uartDef.txPin.name.toUpperCase().replace('_', '.'),
rxHeader: this.uartDef.rxPin.name.toUpperCase().replace('_', '.'),
hardwareIp: 'uart' + this.uartDef.id,
name: this.name,
rxMuxOffset: '0x' + this.uartDef.rxPin.muxOffset.toString(16),
rxMuxValue: '0x' + this.uartDef.rxPin.uart.muxValue.toString(16),
txMuxOffset: '0x' + this.uartDef.txPin.muxOffset.toString(16),
txMuxValue: '0x' + this.uartDef.txPin.uart.muxValue.toString(16),
targetUart: 'uart' + (this.uartDef.id + 1),
partNumber: this.name
};
dto.install(config, function (err) {
if (err) {
return this.emit('error', err);
}
waitForUart(this, options);
}.bind(this));
}
}
module.exports = Uart;
util.inherits(Uart, Duplexify);
Uart.B0 = su.B0;
Uart.B50 = su.B50;
Uart.B75 = su.B75;
Uart.B110 = su.B110;
Uart.B134 = su.B134;
Uart.B150 = su.B150;
Uart.B200 = su.B200;
Uart.B300 = su.B300;
Uart.B600 = su.B600;
Uart.B1200 = su.B1200;
Uart.B1800 = su.B1800;
Uart.B2400 = su.B2400;
Uart.B4800 = su.B4800;
Uart.B9600 = su.B9600;
Uart.B19200 = su.B19200;
Uart.B38400 = su.B38400;
Uart.B57600 = su.B57600;
Uart.B115200 = su.B115200;
Uart.B230400 = su.B230400;
Uart.B460800 = su.B460800;
Uart.B500000 = su.B500000;
Uart.B576000 = su.B576000;
Uart.B921600 = su.B921600;
Uart.B1000000 = su.B1000000;
Uart.B1152000 = su.B1152000;
Uart.B1500000 = su.B1500000;
Uart.B2000000 = su.B2000000;
Uart.B2500000 = su.B2500000;
Uart.B3000000 = su.B3000000;
Uart.B3500000 = su.B3500000;
Uart.B4000000 = su.B4000000;
Uart.PARITY_NONE = su.PARITY_NONE;
Uart.PARITY_ODD = su.PARITY_ODD;
Uart.PARITY_EVEN = su.PARITY_EVEN;
Uart.UART1 = {
id: 1,
txPin: pins.p9_24,
rxPin: pins.p9_26
};
Uart.UART2 = {
id: 2,
txPin: pins.p9_21,
rxPin: pins.p9_22
};
Uart.UART4 = {
id: 4,
txPin: pins.p9_13,
rxPin: pins.p9_11
};
DEFAULT_OPTIONS = {
baudRate: Uart.B38400,
characterSize: 8,
parity: Uart.PARITY_NONE,
stopBits: 1,
highWaterMark: 512,
encoding: null
};
Object.freeze(DEFAULT_OPTIONS);
Uart.prototype.baudRate = function (rate) {
if (rate === undefined) {
return su.getBaudRate(this._rxfd);
}
su.setBaudRate(this._rxfd, rate);
};
Uart.prototype.characterSize = function (size) {
if (size === undefined) {
return su.getCharacterSize(this._rxfd);
}
su.setCharacterSize(this._rxfd, size);
};
Uart.prototype.parity = function (type) {
if (type === undefined) {
return su.getParity(this._rxfd);
}
su.setParity(this._rxfd, type);
};
Uart.prototype.stopBits = function (count) {
if (count === undefined) {
return su.getStopBits(this._rxfd);
}
su.setStopBits(this._rxfd, count);
};
Uart.prototype.close = function () {
this.removeAllListeners('data'); // Is this a good idea? Should the user be doing this?
// TODO: the following is a bit of a hack.
// Here \n EOF is faked for this._rxfd inorder to close the read stream.
// It's faked three times as the uart may receive a character between
// \n and EOF and the stream will not be closed. Faking three times
// increases the chances of it working!
su.setCanonical(this._rxfd, true);
su.fakeInput(this._rxfd, '\n'.charCodeAt(0));
su.fakeInput(this._rxfd, 4); // fake eof
su.fakeInput(this._rxfd, '\n'.charCodeAt(0));
su.fakeInput(this._rxfd, 4); // fake eof
su.fakeInput(this._rxfd, '\n'.charCodeAt(0));
su.fakeInput(this._rxfd, 4); // fake eof
};
|
'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 _react = require('react');
var _react2 = _interopRequireDefault(_react);
var _reactIconBase = require('react-icon-base');
var _reactIconBase2 = _interopRequireDefault(_reactIconBase);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var FaHouzz = function FaHouzz(props) {
return _react2.default.createElement(
_reactIconBase2.default,
_extends({ viewBox: '0 0 40 40' }, props),
_react2.default.createElement(
'g',
null,
_react2.default.createElement('path', { d: 'm19.9 26.6l11.5-6.6v13.2l-11.5 6.6v-13.2z m-11.4-6.6v13.2l11.4-6.6z m11.4-19.8v13.2l-11.4 6.6v-13.2z m0 13.2l11.5-6.6v13.2z' })
)
);
};
exports.default = FaHouzz;
module.exports = exports['default']; |
'use strict';
var convert = require('./convert'),
func = convert('findLastIndexFrom', require('../findLastIndex'));
func.placeholder = require('./placeholder');
module.exports = func;
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uLy4uLy4uLy4uL2NsaWVudC9saWIvbG9kYXNoL2ZwL2ZpbmRMYXN0SW5kZXhGcm9tLmpzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7O0FBQUEsSUFBSSxVQUFVLFFBQVEsV0FBUixDQUFkO0lBQ0ksT0FBTyxRQUFRLG1CQUFSLEVBQTZCLFFBQVEsa0JBQVIsQ0FBN0IsQ0FEWDs7QUFHQSxLQUFLLFdBQUwsR0FBbUIsUUFBUSxlQUFSLENBQW5CO0FBQ0EsT0FBTyxPQUFQLEdBQWlCLElBQWpCIiwiZmlsZSI6ImZpbmRMYXN0SW5kZXhGcm9tLmpzIiwic291cmNlc0NvbnRlbnQiOlsidmFyIGNvbnZlcnQgPSByZXF1aXJlKCcuL2NvbnZlcnQnKSxcbiAgICBmdW5jID0gY29udmVydCgnZmluZExhc3RJbmRleEZyb20nLCByZXF1aXJlKCcuLi9maW5kTGFzdEluZGV4JykpO1xuXG5mdW5jLnBsYWNlaG9sZGVyID0gcmVxdWlyZSgnLi9wbGFjZWhvbGRlcicpO1xubW9kdWxlLmV4cG9ydHMgPSBmdW5jO1xuIl19 |
/*
* 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';
/**
* Person object.
*
*/
class PersonResult {
/**
* Create a PersonResult.
* @member {string} personId personId of the target face list.
* @member {array} [persistedFaceIds] persistedFaceIds of registered faces in
* the person. These persistedFaceIds are returned from Person - Add a Person
* Face, and will not expire.
* @member {string} [name] Person's display name.
* @member {string} [userData] User-provided data attached to this person.
*/
constructor() {
}
/**
* Defines the metadata of PersonResult
*
* @returns {object} metadata of PersonResult
*
*/
mapper() {
return {
required: false,
serializedName: 'PersonResult',
type: {
name: 'Composite',
className: 'PersonResult',
modelProperties: {
personId: {
required: true,
serializedName: 'personId',
type: {
name: 'String'
}
},
persistedFaceIds: {
required: false,
serializedName: 'persistedFaceIds',
type: {
name: 'Sequence',
element: {
required: false,
serializedName: 'StringElementType',
type: {
name: 'String'
}
}
}
},
name: {
required: false,
serializedName: 'name',
type: {
name: 'String'
}
},
userData: {
required: false,
serializedName: 'userData',
type: {
name: 'String'
}
}
}
}
};
}
}
module.exports = PersonResult;
|
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = function (fn /*, ...args*/) {
var args = (0, _slice2.default)(arguments, 1);
return function () /*callArgs*/{
var callArgs = (0, _slice2.default)(arguments);
return fn.apply(null, args.concat(callArgs));
};
};
var _slice = require('./internal/slice');
var _slice2 = _interopRequireDefault(_slice);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
;
/**
* Creates a continuation function with some arguments already applied.
*
* Useful as a shorthand when combined with other control flow functions. Any
* arguments passed to the returned function are added to the arguments
* originally passed to apply.
*
* @name apply
* @static
* @memberOf module:Utils
* @method
* @category Util
* @param {Function} fn - The function you want to eventually apply all
* arguments to. Invokes with (arguments...).
* @param {...*} arguments... - Any number of arguments to automatically apply
* when the continuation is called.
* @returns {Function} the partially-applied function
* @example
*
* // using apply
* async.parallel([
* async.apply(fs.writeFile, 'testfile1', 'test1'),
* async.apply(fs.writeFile, 'testfile2', 'test2')
* ]);
*
*
* // the same process without using apply
* async.parallel([
* function(callback) {
* fs.writeFile('testfile1', 'test1', callback);
* },
* function(callback) {
* fs.writeFile('testfile2', 'test2', callback);
* }
* ]);
*
* // It's possible to pass any number of additional arguments when calling the
* // continuation:
*
* node> var fn = async.apply(sys.puts, 'one');
* node> fn('two', 'three');
* one
* two
* three
*/
module.exports = exports['default']; |
'use strict';
var path = require('path');
var helpers = require('yeoman-generator').test;
var assert = require('yeoman-assert');
describe('test framework', function () {
describe('mocha', function () {
before(function (done) {
helpers.run(path.join(__dirname, '../app'))
.inDir(path.join(__dirname, '.tmp'))
.withOptions({
'skip-install': true,
'test-framework': 'mocha'
})
.withPrompts({features: []})
.on('end', done);
});
it('adds the Grunt plugin', function () {
assert.fileContent('package.json', '"grunt-mocha"');
});
it('adds the Grunt task', function () {
assert.fileContent('Gruntfile.js', 'mocha');
});
it('uses the ESLint environment', function () {
assert.fileContent('package.json', '"mocha"');
});
});
describe('jasmine', function () {
before(function (done) {
helpers.run(path.join(__dirname, '../app'))
.inDir(path.join(__dirname, '.tmp'))
.withOptions({
'skip-install': true,
'test-framework': 'jasmine'
})
.withPrompts({features: []})
.on('end', done);
});
it('adds the Grunt plugin', function () {
assert.fileContent('package.json', '"grunt-contrib-jasmine"');
});
it('adds the Grunt task', function () {
assert.fileContent('Gruntfile.js', 'jasmine');
});
it('uses the ESLint environment', function () {
assert.fileContent('package.json', '"jasmine"');
});
});
});
|
/*jshint maxstatements:false*/
define(function (require, exports) {
"use strict";
var moment = require("moment"),
Promise = require("bluebird"),
_ = brackets.getModule("thirdparty/lodash"),
CodeInspection = brackets.getModule("language/CodeInspection"),
CommandManager = brackets.getModule("command/CommandManager"),
Commands = brackets.getModule("command/Commands"),
Dialogs = brackets.getModule("widgets/Dialogs"),
DocumentManager = brackets.getModule("document/DocumentManager"),
EditorManager = brackets.getModule("editor/EditorManager"),
FileUtils = brackets.getModule("file/FileUtils"),
FileViewController = brackets.getModule("project/FileViewController"),
KeyBindingManager = brackets.getModule("command/KeyBindingManager"),
LanguageManager = brackets.getModule("language/LanguageManager"),
FileSystem = brackets.getModule("filesystem/FileSystem"),
Menus = brackets.getModule("command/Menus"),
FindInFiles = brackets.getModule("search/FindInFiles"),
PanelManager = brackets.getModule("view/PanelManager"),
ProjectManager = brackets.getModule("project/ProjectManager"),
StringUtils = brackets.getModule("utils/StringUtils"),
Svn = require("src/svn/Svn"),
Events = require("./Events"),
EventEmitter = require("./EventEmitter"),
Preferences = require("./Preferences"),
ErrorHandler = require("./ErrorHandler"),
ExpectedError = require("./ExpectedError"),
Main = require("./Main"),
GutterManager = require("./GutterManager"),
Strings = require("../strings"),
Utils = require("src/Utils"),
SettingsDialog = require("./SettingsDialog"),
PANEL_COMMAND_ID = "brackets-git.panel";
var svnPanelTemplate = require("text!templates/svn-panel.html"),
gitPanelResultsTemplate = require("text!templates/git-panel-results.html"),
gitAuthorsDialogTemplate = require("text!templates/authors-dialog.html"),
gitCommitDialogTemplate = require("text!templates/git-commit-dialog.html"),
gitDiffDialogTemplate = require("text!templates/git-diff-dialog.html"),
questionDialogTemplate = require("text!templates/git-question-dialog.html");
var showFileWhiteList = /^\.gitignore$/;
var gitPanel = null,
$gitPanel = $(null),
gitPanelDisabled = null,
gitPanelMode = null,
showingUntracked = true,
$tableContainer = $(null);
/**
* Reloads the Document's contents from disk, discarding any unsaved changes in the editor.
*
* @param {!Document} doc
* @return {Promise} Resolved after editor has been refreshed; rejected if unable to load the
* file's new content. Errors are logged but no UI is shown.
*/
function _reloadDoc(doc) {
return Promise.cast(FileUtils.readAsText(doc.file))
.then(function (text) {
doc.refreshText(text, new Date());
})
.catch(function (err) {
ErrorHandler.logError("Error reloading contents of " + doc.file.fullPath);
ErrorHandler.logError(err);
});
}
function lintFile(filename) {
return CodeInspection.inspectFile(FileSystem.getFileForPath(Utils.getProjectRoot() + filename));
}
function _makeDialogBig($dialog) {
var $wrapper = $dialog.parents(".modal-wrapper").first();
if ($wrapper.length === 0) { return; }
// We need bigger commit dialog
var minWidth = 500,
minHeight = 300,
maxWidth = $wrapper.width(),
maxHeight = $wrapper.height(),
desiredWidth = maxWidth / 2,
desiredHeight = maxHeight / 2;
if (desiredWidth < minWidth) { desiredWidth = minWidth; }
if (desiredHeight < minHeight) { desiredHeight = minHeight; }
$dialog
.width(desiredWidth)
.children(".modal-body")
.css("max-height", desiredHeight)
.end();
return { width: desiredWidth, height: desiredHeight };
}
function _showCommitDialog(stagedDiff, lintResults, prefilledMessage) {
// Flatten the error structure from various providers
lintResults.forEach(function (lintResult) {
lintResult.errors = [];
if (Array.isArray(lintResult.result)) {
lintResult.result.forEach(function (resultSet) {
if (!resultSet.result || !resultSet.result.errors) { return; }
var providerName = resultSet.provider.name;
resultSet.result.errors.forEach(function (e) {
lintResult.errors.push((e.pos.line + 1) + ": " + e.message + " (" + providerName + ")");
});
});
} else {
ErrorHandler.logError("[brackets-git] lintResults contain object in unexpected format: " + JSON.stringify(lintResult));
}
lintResult.hasErrors = lintResult.errors.length > 0;
});
// Filter out only results with errors to show
lintResults = _.filter(lintResults, function (lintResult) {
return lintResult.hasErrors;
});
// Open the dialog
var compiledTemplate = Mustache.render(gitCommitDialogTemplate, {
Strings: Strings,
hasLintProblems: lintResults.length > 0,
lintResults: lintResults
}),
dialog = Dialogs.showModalDialogUsingTemplate(compiledTemplate),
$dialog = dialog.getElement();
// We need bigger commit dialog
_makeDialogBig($dialog);
// Show nicely colored commit diff
$dialog.find(".commit-diff").append(Utils.formatDiff(stagedDiff));
function getCommitMessageElement() {
var r = $dialog.find("[name='commit-message']:visible");
if (r.length !== 1) {
r = $dialog.find("[name='commit-message']");
for (var i = 0; i < r.length; i++) {
if ($(r[i]).css("display") !== "none") {
return $(r[i]);
}
}
}
return r;
}
var $commitMessageCount = $dialog.find("input[name='commit-message-count']");
// Add event to count characters in commit message
var recalculateMessageLength = function () {
var val = getCommitMessageElement().val().trim(),
length = val.length;
if (val.indexOf("\n")) {
// longest line
length = Math.max.apply(null, val.split("\n").map(function (l) { return l.length; }));
}
$commitMessageCount
.val(length)
.toggleClass("over50", length > 50 && length <= 100)
.toggleClass("over100", length > 100);
};
var usingTextArea = false;
// commit message handling
function switchCommitMessageElement() {
usingTextArea = !usingTextArea;
var findStr = "[name='commit-message']",
currentValue = $dialog.find(findStr + ":visible").val();
$dialog.find(findStr).toggle();
$dialog.find(findStr + ":visible")
.val(currentValue)
.focus();
recalculateMessageLength();
}
$dialog.find("button.primary").on("click", function (e) {
var $commitMessage = getCommitMessageElement();
if ($commitMessage.val().trim().length === 0) {
e.stopPropagation();
$commitMessage.addClass("invalid");
} else {
$commitMessage.removeClass("invalid");
}
});
$dialog.find("button.extendedCommit").on("click", function () {
switchCommitMessageElement();
// this value will be set only when manually triggered
Preferences.set("useTextAreaForCommitByDefault", usingTextArea);
});
function prefillMessage(msg) {
if (msg.indexOf("\n") !== -1 && !usingTextArea) {
switchCommitMessageElement();
}
$dialog.find("[name='commit-message']:visible").val(msg);
recalculateMessageLength();
}
if (Preferences.get("useTextAreaForCommitByDefault")) {
switchCommitMessageElement();
}
if (prefilledMessage) {
prefillMessage(prefilledMessage.trim());
}
// Add focus to commit message input
getCommitMessageElement().focus();
$dialog.find("[name='commit-message']")
.on("keyup", recalculateMessageLength)
.on("change", recalculateMessageLength);
recalculateMessageLength();
dialog.done(function (buttonId) {
if (buttonId === "ok") {
// this event won't launch when commit-message is empty so its safe to assume that it is not
var commitMessage = getCommitMessageElement().val();
// if commit message is extended and has a newline, put an empty line after first line to separate subject and body
var s = commitMessage.split("\n");
if (s.length > 1 && s[1].trim() !== "") {
s.splice(1, 0, "");
}
commitMessage = s.join("\n");
// now we are going to be paranoid and we will check if some mofo didn't change our diff
_getStagedDiff().then(function (diff) {
if (diff === stagedDiff) {
return Svn.commit(commitMessage);
} else {
throw new Error("Index was changed while commit dialog was shown!");
}
}).catch(function (err) {
ErrorHandler.showError(err, "Git Commit failed");
}).finally(function () {
EventEmitter.emit(Events.GIT_COMMITED);
refresh();
});
} else {
// this will trigger refreshing where appropriate
Svn.status();
}
});
}
function _showAuthors(file, blame, fromLine, toLine) {
var linesTotal = blame.length;
var blameStats = blame.reduce(function (stats, lineInfo) {
var name = lineInfo.author + " " + lineInfo["author-mail"];
if (stats[name]) {
stats[name] += 1;
} else {
stats[name] = 1;
}
return stats;
}, {});
blameStats = _.reduce(blameStats, function (arr, val, key) {
arr.push({
authorName: key,
lines: val,
percentage: Math.round(val / (linesTotal / 100))
});
return arr;
}, []);
blameStats = _.sortBy(blameStats, "lines").reverse();
if (fromLine || toLine) {
file += " (" + Strings.LINES + " " + fromLine + "-" + toLine + ")";
}
var compiledTemplate = Mustache.render(gitAuthorsDialogTemplate, {
file: file,
blameStats: blameStats,
Strings: Strings
});
Dialogs.showModalDialogUsingTemplate(compiledTemplate);
}
function _getCurrentFilePath(editor) {
var projectRoot = Utils.getProjectRoot(),
document = editor ? editor.document : DocumentManager.getCurrentDocument(),
filePath = document.file.fullPath;
if (filePath.indexOf(projectRoot) === 0) {
filePath = filePath.substring(projectRoot.length);
}
return filePath;
}
function handleAuthorsSelection() {
var editor = EditorManager.getActiveEditor(),
filePath = _getCurrentFilePath(editor),
currentSelection = editor.getSelection(),
fromLine = currentSelection.start.line + 1,
toLine = currentSelection.end.line + 1;
// fix when nothing is selected on that line
if (currentSelection.end.ch === 0) { toLine = toLine - 1; }
var isSomethingSelected = currentSelection.start.line !== currentSelection.end.line ||
currentSelection.start.ch !== currentSelection.end.ch;
if (!isSomethingSelected) {
ErrorHandler.showError(new ExpectedError("Nothing is selected!"));
return;
}
Svn.getBlame(filePath, fromLine, toLine).then(function (blame) {
return _showAuthors(filePath, blame, fromLine, toLine);
}).catch(function (err) {
ErrorHandler.showError(err, "Git Blame failed");
});
}
function handleAuthorsFile() {
var filePath = _getCurrentFilePath();
Svn.getBlame(filePath).then(function (blame) {
return _showAuthors(filePath, blame);
}).catch(function (err) {
ErrorHandler.showError(err, "Git Blame failed");
});
}
function handleGitDiff(file) {
Svn.diffFileNice(file).then(function (diff) {
// show the dialog with the diff
var compiledTemplate = Mustache.render(gitDiffDialogTemplate, { file: file, Strings: Strings }),
dialog = Dialogs.showModalDialogUsingTemplate(compiledTemplate),
$dialog = dialog.getElement();
_makeDialogBig($dialog);
$dialog.find(".commit-diff").append(Utils.formatDiff(diff));
}).catch(function (err) {
ErrorHandler.showError(err, "SVN Diff failed");
});
}
function handleGitUndo(file) {
var compiledTemplate = Mustache.render(questionDialogTemplate, {
title: Strings.UNDO_CHANGES,
question: StringUtils.format(Strings.Q_UNDO_CHANGES, _.escape(file)),
Strings: Strings
});
Dialogs.showModalDialogUsingTemplate(compiledTemplate).done(function (buttonId) {
if (buttonId === "ok") {
Svn.discardFileChanges(file).then(function () {
var currentProjectRoot = Utils.getProjectRoot();
DocumentManager.getAllOpenDocuments().forEach(function (doc) {
if (doc.file.fullPath === currentProjectRoot + file) {
_reloadDoc(doc);
}
});
refresh();
}).catch(function (err) {
ErrorHandler.showError(err, "Git Checkout failed");
});
}
});
}
function handleGitDelete(file) {
var compiledTemplate = Mustache.render(questionDialogTemplate, {
title: Strings.DELETE_FILE,
question: StringUtils.format(Strings.Q_DELETE_FILE, _.escape(file)),
Strings: Strings
});
Dialogs.showModalDialogUsingTemplate(compiledTemplate).done(function (buttonId) {
if (buttonId === "ok") {
FileSystem.resolve(Utils.getProjectRoot() + file, function (err, fileEntry) {
if (err) {
ErrorHandler.showError(err, "Could not resolve file");
return;
}
Promise.cast(ProjectManager.deleteItem(fileEntry))
.then(function () {
refresh();
})
.catch(function (err) {
ErrorHandler.showError(err, "File deletion failed");
});
});
}
});
}
function handleGlobalUpdate(){
var files = [];
return handleSvnUpdate(files);
}
function handleSvnUpdate(files){
if(!_.isArray(files)) return;
return Svn.updateFile(files).then(function(stdout){
refresh();
});
}
/**
* strips trailing whitespace from all the diffs and adds \n to the end
*/
function stripWhitespaceFromFile(filename, clearWholeFile) {
return new Promise(function (resolve, reject) {
var fullPath = Utils.getProjectRoot() + filename,
removeBom = Preferences.get("removeByteOrderMark"),
normalizeLineEndings = Preferences.get("normalizeLineEndings");
var _cleanLines = function (lineNumbers) {
// clean the file
var fileEntry = FileSystem.getFileForPath(fullPath);
return FileUtils.readAsText(fileEntry).then(function (text) {
if (removeBom) {
// remove BOM - \ufeff
text = text.replace(/\ufeff/g, "");
}
if (normalizeLineEndings) {
// normalizes line endings
text = text.replace(/\r\n/g, "\n");
}
// process lines
var lines = text.split("\n");
if (lineNumbers) {
lineNumbers.forEach(function (lineNumber) {
lines[lineNumber] = lines[lineNumber].replace(/\s+$/, "");
});
} else {
lines.forEach(function (ln, lineNumber) {
lines[lineNumber] = lines[lineNumber].replace(/\s+$/, "");
});
}
// add empty line to the end, i've heard that git likes that for some reason
if (Preferences.get("addEndlineToTheEndOfFile")) {
var lastLineNumber = lines.length - 1;
if (lines[lastLineNumber].length > 0) {
lines[lastLineNumber] = lines[lastLineNumber].replace(/\s+$/, "");
}
if (lines[lastLineNumber].length > 0) {
lines.push("");
}
}
//-
text = lines.join("\n");
return Promise.cast(FileUtils.writeText(fileEntry, text))
.catch(function (err) {
ErrorHandler.logError("Wasn't able to clean whitespace from file: " + fullPath);
resolve();
throw err;
})
.then(function () {
// refresh the file if it's open in the background
DocumentManager.getAllOpenDocuments().forEach(function (doc) {
if (doc.file.fullPath === fullPath) {
_reloadDoc(doc);
}
});
// diffs were cleaned in this file
resolve();
});
});
};
if (clearWholeFile) {
_cleanLines(null);
} else {
Svn.diffFile(filename).then(function (diff) {
if (!diff) { return resolve(); }
var modified = [],
changesets = diff.split("\n").filter(function (l) { return l.match(/^@@/) !== null; });
// collect line numbers to clean
changesets.forEach(function (line) {
var i,
m = line.match(/^@@ -([,0-9]+) \+([,0-9]+) @@/),
s = m[2].split(","),
from = parseInt(s[0], 10),
to = from - 1 + (parseInt(s[1], 10) || 1);
for (i = from; i <= to; i++) { modified.push(i > 0 ? i - 1 : 0); }
});
_cleanLines(modified);
}).catch(function (ex) {
// This error will bubble up to preparing commit dialog so just log here
ErrorHandler.logError(ex);
reject(ex);
});
}
});
}
function _getStagedDiff() {
return Svn.getDiffOfStagedFiles().then(function (diff) {
if (!diff) {
return Svn.getListOfStagedFiles().then(function (filesList) {
return Strings.DIFF_FAILED_SEE_FILES + "\n\n" + filesList;
});
}
return diff;
});
}
// whatToDo gets values "continue" "skip" "abort"
function handleRebase(whatToDo) {
Svn.rebase(whatToDo).then(function () {
EventEmitter.emit(Events.REFRESH_ALL);
}).catch(function (err) {
ErrorHandler.showError(err, "Rebase " + whatToDo + " failed");
});
}
function abortMerge() {
Svn.discardAllChanges().then(function () {
EventEmitter.emit(Events.REFRESH_ALL);
}).catch(function (err) {
ErrorHandler.showError(err, "Merge abort failed");
});
}
function findConflicts() {
FindInFiles.doSearch(/^<<<<<<<\s|^=======\s|^>>>>>>>\s/gm);
}
function commitMerge() {
Utils.loadPathContent(Utils.getProjectRoot() + "/.git/MERGE_MSG").then(function (msg) {
handleGitCommit(msg);
}).catch(function (err) {
ErrorHandler.showError(err, "Merge commit failed");
});
}
function handleGitCommit(prefilledMessage) {
var codeInspectionEnabled = Preferences.get("useCodeInspection");
var stripWhitespace = Preferences.get("stripWhitespaceFromCommits");
// Disable button (it will be enabled when selecting files after reset)
Utils.setLoading($gitPanel.find(".git-commit"));
// First reset staged files, then add selected files to the index.
Svn.status().then(function (files) {
files = _.filter(files, function (file) {
return file.status.indexOf(Svn.FILE_STATUS.MODIFIED) !== -1;
});
if (files.length === 0) {
return ErrorHandler.showError(new Error("Commit button should have been disabled"), "Nothing staged to commit");
}
var lintResults = [],
promises = [];
files.forEach(function (fileObj) {
var queue = Promise.resolve();
var isDeleted = fileObj.status.indexOf(Svn.FILE_STATUS.DELETED) !== -1,
updateIndex = isDeleted;
// strip whitespace if configured to do so and file was not deleted
if (stripWhitespace && !isDeleted) {
// strip whitespace only for recognized languages so binary files won't get corrupted
var langId = LanguageManager.getLanguageForPath(fileObj.file).getId();
if (["unknown", "binary", "image", "markdown"].indexOf(langId) === -1) {
queue = queue.then(function () {
var clearWholeFile = fileObj.status.indexOf(Svn.FILE_STATUS.UNTRACKED) !== -1 ||
fileObj.status.indexOf(Svn.FILE_STATUS.RENAMED) !== -1;
return stripWhitespaceFromFile(fileObj.file, clearWholeFile);
});
}
}
// do a code inspection for the file, if it was not deleted
if (codeInspectionEnabled && !isDeleted) {
queue = queue.then(function () {
return lintFile(fileObj.file).then(function (result) {
if (result) {
lintResults.push({
filename: fileObj.file,
result: result
});
}
});
});
}
promises.push(queue);
});
return Promise.all(promises).then(function () {
// All files are in the index now, get the diff and show dialog.
return _getStagedDiff().then(function (diff) {
return _showCommitDialog(diff, lintResults, prefilledMessage);
});
});
}).catch(function (err) {
ErrorHandler.showError(err, "Preparing commit dialog failed");
}).finally(function () {
Utils.unsetLoading($gitPanel.find(".git-commit"));
});
}
function refreshCurrentFile() {
var currentProjectRoot = Utils.getProjectRoot();
var currentDoc = DocumentManager.getCurrentDocument();
if (currentDoc) {
$gitPanel.find("tr").each(function () {
var currentFullPath = currentDoc.file.fullPath,
thisFile = $(this).attr("x-file");
$(this).toggleClass("selected", currentProjectRoot + thisFile === currentFullPath);
});
} else {
$gitPanel.find("tr").removeClass("selected");
}
}
function shouldShow(fileObj) {
if (showFileWhiteList.test(fileObj.name)) {
return true;
}
return ProjectManager.shouldShow(fileObj);
}
function _refreshTableContainer(files) {
if (!gitPanel.isVisible()) {
return;
}
// remove files that we should not show
files = _.filter(files, function (file) {
return shouldShow(file);
});
var allStaged = files.length > 0 && _.all(files, function (file) { return file.status.indexOf(Svn.FILE_STATUS.STAGED) !== -1; });
$gitPanel.find(".check-all").prop("checked", allStaged).prop("disabled", files.length === 0);
var $editedList = $tableContainer.find(".git-edited-list");
var visibleBefore = $editedList.length ? $editedList.is(":visible") : true;
$editedList.remove();
if (files.length === 0) {
$tableContainer.append($("<p class='git-edited-list nothing-to-commit' />").text(Strings.NOTHING_TO_COMMIT));
} else {
// if desired, remove untracked files from the results
if (showingUntracked === false) {
files = _.filter(files, function (file) {
return file.status.indexOf(Svn.FILE_STATUS.UNTRACKED) === -1;
});
}
// -
files.forEach(function (file) {
file.staged = file.status.indexOf(Svn.FILE_STATUS.STAGED) !== -1;
file.statusText = file.status.map(function (status) {
return Strings["FILE_" + status];
}).join(", ");
file.allowDiff = file.status.indexOf(Svn.FILE_STATUS.UNTRACKED) === -1 &&
file.status.indexOf(Svn.FILE_STATUS.RENAMED) === -1 &&
file.status.indexOf(Svn.FILE_STATUS.DELETED) === -1;
file.allowDelete = file.status.indexOf(Svn.FILE_STATUS.UNTRACKED) !== -1;
file.allowUndo = !file.allowDelete && file.status.indexOf(Svn.FILE_STATUS.MODIFIED) !== -1;
file.allowUpdate = file.status.indexOf(Svn.FILE_STATUS.OUTOFDATE) !== -1;
file.allowAdd = file.status.indexOf(Svn.FILE_STATUS.UNTRACKED) > -1;
});
$tableContainer.append(Mustache.render(gitPanelResultsTemplate, {
files: files,
Strings: Strings
}));
refreshCurrentFile();
}
$tableContainer.find(".git-edited-list").toggle(visibleBefore);
}
function refresh() {
// set the history panel to false and remove the class that show the button history active when refresh
$gitPanel.find(".git-history-toggle").removeClass("active").attr("title", Strings.TOOLTIP_SHOW_HISTORY);
$gitPanel.find(".git-file-history").removeClass("active").attr("title", Strings.TOOLTIP_SHOW_FILE_HISTORY);
if (gitPanelMode === "not-repo") {
$tableContainer.empty();
return Promise.resolve();
}
$tableContainer.find("#git-history-list").remove();
$tableContainer.find(".git-edited-list").show();
var p1 = Svn.status(true);
//- push button
//var $pushBtn = $gitPanel.find(".git-push");
// var p2 = Svn.getCommitsAhead().then(function (commits) {
// $pushBtn.children("span").remove();
// if (commits.length > 0) {
// $pushBtn.append($("<span/>").text(" (" + commits.length + ")"));
// }
// }).catch(function () {
// $pushBtn.children("span").remove();
// });
// FUTURE: who listens for this?
return Promise.all([p1]);
}
function toggle(bool) {
if (gitPanelDisabled === true) {
return;
}
if (typeof bool !== "boolean") {
bool = !gitPanel.isVisible();
}
Preferences.persist("panelEnabled", bool);
Main.$icon.toggleClass("on", bool);
gitPanel.setVisible(bool);
// Mark menu item as enabled/disabled.
CommandManager.get(PANEL_COMMAND_ID).setChecked(bool);
if (bool) {
refresh();
}
}
function handleToggleUntracked() {
showingUntracked = !showingUntracked;
$gitPanel
.find(".git-toggle-untracked")
.text(showingUntracked ? Strings.HIDE_UNTRACKED : Strings.SHOW_UNTRACKED);
refresh();
}
function commitCurrentFile() {
return Promise.cast(CommandManager.execute("file.save"))
.then(function () {
return Svn.resetIndex();
})
.then(function () {
var currentProjectRoot = Utils.getProjectRoot();
var currentDoc = DocumentManager.getCurrentDocument();
if (currentDoc) {
var relativePath = currentDoc.file.fullPath.substring(currentProjectRoot.length);
return Svn.stage(relativePath).then(function () {
return handleGitCommit();
});
}
});
}
function commitAllFiles() {
return Promise.cast(CommandManager.execute("file.saveAll"))
.then(function () {
return Svn.resetIndex();
})
.then(function () {
return Svn.stageAll().then(function () {
return handleGitCommit();
});
});
}
// Disable "commit" button if there aren't staged files to commit
function _toggleCommitButton(files) {
var anyStaged = _.any(files, function (file) { return file.status.indexOf(Svn.FILE_STATUS.STAGED) !== -1; });
$gitPanel.find(".git-commit").prop("disabled", !anyStaged);
}
EventEmitter.on(Events.GIT_STATUS_RESULTS, function (results) {
_refreshTableContainer(results);
_toggleCommitButton(results);
});
function undoLastLocalCommit() {
Svn.undoLastLocalCommit()
.catch(function (err) {
ErrorHandler.showError(err, "Impossible to undo last commit");
})
.finally(function () {
refresh();
});
}
var lastCheckOneClicked = null;
function attachDefaultTableHandlers() {
$tableContainer = $gitPanel.find(".table-container")
.off()
.on("click", ".check-one", function (e) {
e.stopPropagation();
var $tr = $(this).closest("tr"),
file = $tr.attr("x-file"),
status = $tr.attr("x-status"),
isChecked = $(this).is(":checked");
if (e.shiftKey) {
// do something if we press shift. Right now? Nothing.
}
lastCheckOneClicked = file;
})
.on("dblclick", ".check-one", function (e) {
e.stopPropagation();
})
.on("click", ".btn-git-diff", function (e) {
e.stopPropagation();
handleGitDiff($(e.target).closest("tr").attr("x-file"));
})
.on("click", ".btn-git-undo", function (e) {
e.stopPropagation();
handleGitUndo($(e.target).closest("tr").attr("x-file"));
})
.on("click", ".btn-git-delete", function (e) {
e.stopPropagation();
handleGitDelete($(e.target).closest("tr").attr("x-file"));
})
.on("click", ".btn-svn-add", function(e) {
e.stopPropagation();
handleSvnAdd($(e.target).closest("tr").attr("x-file"));
})
.on("click", ".btn-svn-update", function (e) {
e.stopPropagation();
handleSvnUpdate([$(e.target).closest("tr").attr("x-file")]);
})
.on("click", ".modified-file", function (e) {
var $this = $(e.currentTarget);
if ($this.attr("x-status") === Svn.FILE_STATUS.DELETED) {
return;
}
CommandManager.execute(Commands.FILE_OPEN, {
fullPath: Utils.getProjectRoot() + $this.attr("x-file")
});
})
.on("dblclick", ".modified-file", function (e) {
var $this = $(e.currentTarget);
if ($this.attr("x-status") === Svn.FILE_STATUS.DELETED) {
return;
}
FileViewController.addToWorkingSetAndSelect(Utils.getProjectRoot() + $this.attr("x-file"));
});
}
function discardAllChanges() {
return Utils.askQuestion(Strings.RESET_LOCAL_REPO, Strings.RESET_LOCAL_REPO_CONFIRM, { booleanResponse: true })
.then(function (response) {
if (response) {
return Svn.discardAllChanges().catch(function (err) {
ErrorHandler.showError(err, "Reset of local repository failed");
}).then(function () {
refresh();
});
}
});
}
function init() {
// Add panel
var panelHtml = Mustache.render(svnPanelTemplate, {
enableAdvancedFeatures: Preferences.get("enableAdvancedFeatures"),
showBashButton: Preferences.get("showBashButton"),
showReportBugButton: Preferences.get("showReportBugButton"),
S: Strings
});
var $panelHtml = $(panelHtml);
$panelHtml.find(".git-available, .git-not-available").hide();
gitPanel = PanelManager.createBottomPanel("brackets-git.panel", $panelHtml, 100);
$gitPanel = gitPanel.$panel;
$gitPanel
.on("click", ".close", toggle)
.on("click", ".check-all", function () {
$('.check-one').attr('checked',true);
})
.on("click", ".git-refresh", EventEmitter.emitFactory(Events.REFRESH_ALL))
.on("click", ".git-commit", EventEmitter.emitFactory(Events.HANDLE_GIT_COMMIT))
.on("click", ".git-commit-merge", commitMerge)
.on("click", ".svn-update", handleGlobalUpdate)
.on("click", ".git-find-conflicts", findConflicts)
.on("click", ".git-prev-gutter", GutterManager.goToPrev)
.on("click", ".git-next-gutter", GutterManager.goToNext)
.on("click", ".git-toggle-untracked", handleToggleUntracked)
.on("click", ".authors-selection", handleAuthorsSelection)
.on("click", ".authors-file", handleAuthorsFile)
.on("click", ".git-file-history", EventEmitter.emitFactory(Events.HISTORY_SHOW, "FILE"))
.on("click", ".git-history-toggle", EventEmitter.emitFactory(Events.HISTORY_SHOW, "GLOBAL"))
.on("click", ".git-bug", ErrorHandler.reportBug)
.on("click", ".git-settings", SettingsDialog.show)
.on("contextmenu", "tr", function (e) {
var $this = $(this);
if ($this.hasClass("history-commit")) { return; }
$this.click();
setTimeout(function () {
Menus.getContextMenu("git-panel-context-menu").open(e);
}, 1);
})
.on("click", ".git-bash", EventEmitter.emitFactory(Events.TERMINAL_OPEN))
.on("click", ".reset-all", discardAllChanges);
// Attaching table handlers
attachDefaultTableHandlers();
// Commit current and all shortcuts
var COMMIT_CURRENT_CMD = "brackets-git.commitCurrent",
COMMIT_ALL_CMD = "brackets-git.commitAll",
BASH_CMD = "brackets-git.launchBash",
PUSH_CMD = "brackets-git.push",
PULL_CMD = "brackets-git.pull",
GOTO_PREV_CHANGE = "brackets-git.gotoPrevChange",
GOTO_NEXT_CHANGE = "brackets-git.gotoNextChange";
// Add command to menu.
// Register command for opening bottom panel.
CommandManager.register(Strings.PANEL_COMMAND, PANEL_COMMAND_ID, toggle);
KeyBindingManager.addBinding(PANEL_COMMAND_ID, Preferences.get("panelShortcut"));
CommandManager.register(Strings.COMMIT_CURRENT_SHORTCUT, COMMIT_CURRENT_CMD, commitCurrentFile);
KeyBindingManager.addBinding(COMMIT_CURRENT_CMD, Preferences.get("commitCurrentShortcut"));
CommandManager.register(Strings.COMMIT_ALL_SHORTCUT, COMMIT_ALL_CMD, commitAllFiles);
KeyBindingManager.addBinding(COMMIT_ALL_CMD, Preferences.get("commitAllShortcut"));
CommandManager.register(Strings.LAUNCH_BASH_SHORTCUT, BASH_CMD, EventEmitter.emitFactory(Events.TERMINAL_OPEN));
KeyBindingManager.addBinding(BASH_CMD, Preferences.get("bashShortcut"));
CommandManager.register(Strings.PUSH_SHORTCUT, PUSH_CMD, EventEmitter.emitFactory(Events.HANDLE_PUSH));
KeyBindingManager.addBinding(PUSH_CMD, Preferences.get("pushShortcut"));
CommandManager.register(Strings.PULL_SHORTCUT, PULL_CMD, EventEmitter.emitFactory(Events.HANDLE_PULL));
KeyBindingManager.addBinding(PULL_CMD, Preferences.get("pullShortcut"));
CommandManager.register(Strings.GOTO_PREVIOUS_GIT_CHANGE, GOTO_PREV_CHANGE, GutterManager.goToPrev);
KeyBindingManager.addBinding(GOTO_PREV_CHANGE, Preferences.get("gotoPrevChangeShortcut"));
CommandManager.register(Strings.GOTO_NEXT_GIT_CHANGE, GOTO_NEXT_CHANGE, GutterManager.goToNext);
KeyBindingManager.addBinding(GOTO_NEXT_CHANGE, Preferences.get("gotoNextChangeShortcut"));
// Init moment - use the correct language
moment.lang(brackets.getLocale());
if(Svn.isWorkingCopy()){
enable();
}
// Show gitPanel when appropriate
if (Preferences.get("panelEnabled")) {
toggle(true);
}
}
function enable() {
EventEmitter.emit(Events.SVN_ENABLED);
// this function is called after every Branch.refresh
gitPanelMode = null;
//
$gitPanel.find(".git-available").show();
$gitPanel.find(".git-not-available").hide();
//
Main.$icon.removeClass("warning").removeAttr("title");
gitPanelDisabled = false;
// after all is enabled
refresh();
}
function disable(cause) {
EventEmitter.emit(Events.GIT_DISABLED, cause);
gitPanelMode = cause;
// causes: not-repo
if (gitPanelMode === "not-repo") {
$gitPanel.find(".git-available").hide();
$gitPanel.find(".git-not-available").show();
} else {
Main.$icon.addClass("warning").attr("title", cause);
toggle(false);
gitPanelDisabled = true;
}
refresh();
}
// Event listeners
EventEmitter.on(Events.BRACKETS_CURRENT_DOCUMENT_CHANGE, function () {
if (!gitPanel) { return; }
refreshCurrentFile();
});
EventEmitter.on(Events.BRACKETS_DOCUMENT_SAVED, function () {
if (!gitPanel) { return; }
refresh();
});
EventEmitter.on(Events.REBASE_MERGE_MODE, function (rebaseEnabled, mergeEnabled) {
$gitPanel.find(".git-rebase").toggle(rebaseEnabled);
$gitPanel.find(".git-merge").toggle(mergeEnabled);
$gitPanel.find("button.git-commit").toggle(!rebaseEnabled && !mergeEnabled);
});
EventEmitter.on(Events.HANDLE_GIT_COMMIT, function () {
handleGitCommit();
});
exports.init = init;
exports.refresh = refresh;
exports.toggle = toggle;
exports.enable = enable;
exports.disable = disable;
exports.getPanel = function () { return $gitPanel; };
});
|
var Path = require('path');
var Hapi = require('hapi');
var server = new Hapi.Server();
var port = process.env.PORT || 5000;
server.connection({ port: port });
server.views({
engines: {
html: require('handlebars')
},
path: Path.join(__dirname, 'views')
});
server.route([
{ path: '/',
method: 'GET',
config: {
auth: false,
handler: function(request, reply) {
reply.view("index");
}
}
},
{
method: 'GET',
path: '/public/{param*}',
handler: {
directory: {
path: Path.normalize(__dirname + '/public')
}
}
}
]);
server.start(function(){
console.log('Static Server Listening on : http://127.0.0.1:' +port);
});
module.exports = server; |
/**
* Module dependencies.
*/
var api = require('lib/db-api');
var config = require('lib/config');
var express = require('express');
var jwt = require('lib/jwt');
var passport = require('passport');
var log = require('debug')('democracyos:auth:facebook:routes');
var User = require('lib/models').User;
var fbSignedParser = require('fb-signed-parser');
/**
* Expose auth app
*/
var app = module.exports = express();
/*
* Facebook Auth routes
*/
app.get('/auth/facebook',
passport.authenticate('facebook', {
scope: config.auth.facebook.permissions
})
);
app.get('/auth/facebook/callback',
passport.authenticate('facebook', { failureRedirect: '/' }),
function(req, res) {
// After successful authentication
// redirect to homepage.
log('Log in user %s', req.user.id);
var token = jwt.encodeToken(api.user.expose.confidential(req.user), config.jwtSecret);
return res.cookie('token', token.token, { expires: new Date(token.expires), httpOnly: true }).redirect('/');
}
);
app.post('/auth/facebook/deauthorize', function(req, res) {
log('Parsing call to "/auth/facebook/deauthorize".');
res.send(200);
var signedRequest = req.params.signed_request;
if (!signedRequest) return log('"signed_request" param not found.');
var data = fbSignedParser.parse(signedRequest, config.auth.facebook.clientSecret);
if (!data || !data.user || !data.user.id) {
return log('Invalid "signed_request" data: ', data);
}
setTimeout(function(){
deauthorizeUser(data.user.id)
}, 0);
});
function deauthorizeUser(userFacebookId) {
log('Deauthorizing user with facebook id "%s".', userFacebookId);
var profile = {
id: userFacebookId,
provider: 'facebook'
};
User.findByProvider(profile, function (err, user) {
if (err) {
return log('Error looking for user with facebook id "%s".', userFacebookId);
}
if (!user) {
return log('User with facebook id "%s" not found.', userFacebookId);
}
user.set('profiles.facebook.deauthorized', true);
return user.save(function(err){
if (err) return log(err);
log('Facebook login for user "%s" deauthorized.', user.id);
});
});
}
|
// © 2000 NEOSYS Software Ltd. All Rights Reserved.//**Start Encode**
function form_postinit() {
//enable/disable password changing button
neosyssetexpression('button_password', 'disabled', '!gusers_authorisation_update&&gkey!=gusername')
//force retrieval of own record
if (gro.dictitem('USER_ID').defaultvalue)
window.setTimeout('focuson("USER_NAME")', 100)
gwhatsnew = neosysgetcookie(glogincode, 'NEOSYS2', 'wn').toLowerCase()
if (gwhatsnew) {
if (window.location.href.toString().slice(0, 5) == 'file:') gwhatsnew = 'file:///' + gwhatsnew
else gwhatsnew = '..' + gwhatsnew.slice(gwhatsnew.indexOf('\\data\\'))
neosyssetcookie(glogincode, 'NEOSYS2', '', 'wn')
neosyssetcookie(glogincode, 'NEOSYS2', gwhatsnew, 'wn2')
window.setTimeout('windowopen(gwhatsnew)', 1000)
//windowopen(gwhatsnew)
}
$$('button_password').onclick = user_setpassword
return true
}
//just to avoid confirmation
function form_prewrite() {
return true
}
//in authorisation.js and users.htm
var gtasks_newpassword
function form_postwrite() {
//if change own password then login with the new one
//otherwise cannot continue/unlock document so the lock hangs
if (gtasks_newpassword) db.login(gusername, gtasks_newpassword)
gtasks_newpassword = false
//to avoid need full login to get new font/colors
neosyssetcookie(glogincode, 'NEOSYS2', gds.getx('SCREEN_BODY_COLOR'), 'fc')
neosyssetcookie(glogincode, 'NEOSYS2', gds.getx('SCREEN_FONT'), 'ff')
neosyssetcookie(glogincode, 'NEOSYS2', gds.getx('SCREEN_FONT_SIZE'), 'fs')
return true
}
function users_postdisplay() {
var signatureimageelement = document.getElementById('signature_image')
if (signatureimageelement) {
signatureimageelement.src = ''
signatureimageelement.height = 0
signatureimageelement.width = 0
signatureimageelement.src = '../images/'+gdataset+'SHARP/UPLOAD/USERS/' + gkey.neosysconvert(' ', '') + '_signature.jpg'
}
//show only first five lines
form_filter('refilter', 'LOGIN_DATE', '', 4)
var reminderdays = 6
var passwordexpires = gds.getx('PASSWORD_EXPIRY_DATE')
$passwordexpiryelement = $$('passwordexpiryelement')
$passwordexpiryelement.innerHTML = ''
if (passwordexpires) {
var expirydays = (neosysint(passwordexpires) - neosysdate())
if (expirydays <= reminderdays)
$passwordexpiryelement.innerHTML = '<font color=red> Password expires in ' + expirydays + ' days.</font>'
}
return true
}
function form_postread() {
window.setTimeout('users_postdisplay()', 10)
return true
}
function users_upload_signature() {
//return openwindow('EXECUTE\r\MEDIA\r\OPENMATERIAL',scheduleno+'.'+materialletter)
/*
params=new Object()
params.scheduleno=scheduleno
params.materialletter=materialletter
neosysshowmodaldialog('../NEOSYS/upload.htm',params)
*/
//images are not stored per dataset at the moment so that they can be
//nor are they stored per file or per key so that they can be easily saved into a shared folder instead of going by web upload
params = {}
params.database = gdataset
params.filename = 'USERS'
params.key = gkey.neosysconvert(' ', '') + '_signature'
params.versionno = ''//newarchiveno
params.updateallowed = true
params.deleteallowed = true
//params.allowimages = true
//we only allow one image type merely so that the signature file name
//is always know and doesnt need saving in the user file
//and no possibility of uploading two image files with different extensions
params.allowablefileextensions = 'jpg'
var targetfilename = neosysshowmodaldialog('../NEOSYS/upload.htm', params)
window.setTimeout('users_postdisplay()', 1)
if (!targetfilename)
return false
return true
}
function user_signature_onload(el) {
el.removeAttribute("width")
el.removeAttribute("height")
}
|
/**
* @fileoverview added by tsickle
* @suppress {checkTypes,extraRequire,uselessCode} checked by tsc
*/
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* @module
* @description
* Entry point for all public APIs of this package.
*/
export { AnimationDriver, ɵAnimation, ɵAnimationStyleNormalizer, ɵNoopAnimationStyleNormalizer, ɵWebAnimationsStyleNormalizer, ɵAnimationDriver, ɵNoopAnimationDriver, ɵAnimationEngine, ɵCssKeyframesDriver, ɵCssKeyframesPlayer, ɵcontainsElement, ɵinvokeQuery, ɵmatchesElement, ɵvalidateStyleProperty, ɵWebAnimationsDriver, ɵsupportsWebAnimations, ɵWebAnimationsPlayer, ɵallowPreviousPlayerStylesMerge } from './src/browser';
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoicHVibGljX2FwaS5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uLy4uLy4uLy4uL3BhY2thZ2VzL2FuaW1hdGlvbnMvYnJvd3Nlci9wdWJsaWNfYXBpLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7Ozs7Ozs7Ozs7Ozs7Ozs7QUFhQSx1WkFBYyxlQUFlLENBQUMiLCJzb3VyY2VzQ29udGVudCI6WyIvKipcbiAqIEBsaWNlbnNlXG4gKiBDb3B5cmlnaHQgR29vZ2xlIEluYy4gQWxsIFJpZ2h0cyBSZXNlcnZlZC5cbiAqXG4gKiBVc2Ugb2YgdGhpcyBzb3VyY2UgY29kZSBpcyBnb3Zlcm5lZCBieSBhbiBNSVQtc3R5bGUgbGljZW5zZSB0aGF0IGNhbiBiZVxuICogZm91bmQgaW4gdGhlIExJQ0VOU0UgZmlsZSBhdCBodHRwczovL2FuZ3VsYXIuaW8vbGljZW5zZVxuICovXG5cbi8qKlxuICogQG1vZHVsZVxuICogQGRlc2NyaXB0aW9uXG4gKiBFbnRyeSBwb2ludCBmb3IgYWxsIHB1YmxpYyBBUElzIG9mIHRoaXMgcGFja2FnZS5cbiAqL1xuZXhwb3J0ICogZnJvbSAnLi9zcmMvYnJvd3Nlcic7XG4iXX0= |
'use strict';
const path = require('path'),
mongoose = require('mongoose'),
Promise = require('bluebird'),
errorHandler = require(path.resolve('./modules/core/server/controllers/errors.server.controller')),
_ = require('lodash');
mongoose.Promise = Promise;
const User = mongoose.model('User');
const Project = mongoose.model('Project');
/**
* Patch Update User Fields
*/
exports.patchUser = (req, res) => {
_.extend(req.model, req.body)
.save()
.then(updatedUser => {
res.jsonp(updatedUser);
})
.catch(err => {
console.error('ERROR on patch update for user `err`:\n', err);
res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
});
};
/**
* Return list of projects by contributor - query param `publishedOnly`, if true, returns only published projects
*
* @param req
* @param req.query.publishedOnly
* @param res
*/
exports.getContributorProjects = (req, res) => {
const projectIdsArray = [];
const projectsArray = [];
req.model.associatedProjects.map(assocProjId => { projectIdsArray.push(assocProjId); });
Project.find({
'_id': { $in: projectIdsArray }
})
.then(projects => {
if (req.query.publishedOnly===true) {
projects.map(project => {
if(project.status[0]==='published') {
projectsArray.push(project);
}
});
projects = projectsArray;
}
res.jsonp(projects);
})
.catch(err => {
console.error('error:\n', err);
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
});
};
|
/*jshint unused:false*/
var chai = require('chai'),
expect = chai.expect;
var request = require('supertest');
module.exports = function() {
'use strict';
this.Then(/^The JSON is returned by issuing a "GET" at the specified uri:$/, function(json, callback) {
request(this.serverLocation)
.get('/hello')
.expect('Content-Type', /json/)
.expect(200)
.end(function(error, res) {
if(error) {
expect(false).to.equal(true, error);
}
else {
expect(res.body).to.deep.equal(JSON.parse(json));
}
callback();
});
});
}; |
/* global sinon, setup, teardown */
/**
* __init.test.js is run before every test case.
*/
window.debug = true;
var AScene = require('aframe').AScene;
beforeEach(function () {
this.sinon = sinon.sandbox.create();
// Stub to not create a WebGL context since Travis CI runs headless.
this.sinon.stub(AScene.prototype, 'attachedCallback');
});
afterEach(function () {
// Clean up any attached elements.
['canvas', 'a-assets', 'a-scene'].forEach(function (tagName) {
var els = document.querySelectorAll(tagName);
for (var i = 0; i < els.length; i++) {
els[i].parentNode.removeChild(els[i]);
}
});
AScene.scene = null;
this.sinon.restore();
});
|
"use strict";
var mathUtils = require("./math-utils");
exports.shuffle = function(array) {
var len = array.length;
for ( var i=0; i<len; i++ ) {
var rand = mathUtils.randomInt(0,len-1);
var temp = array[i];
array[i] = array[rand];
array[rand] = temp;
}
}; |
/* eslint quote-props: ["error", "consistent"] */
// Japanese Hirajoshi scale
// 1-4-2-1-4
// Gb G B Db D Gb
export default {
'a': { instrument: 'piano', note: 'a4' },
'b': { instrument: 'piano', note: 'eb3' },
'c': { instrument: 'piano', note: 'd6' },
'd': { instrument: 'piano', note: 'eb4' },
'e': { instrument: 'piano', note: 'd4' },
'f': { instrument: 'piano', note: 'bb5' },
'g': { instrument: 'piano', note: 'd7' },
'h': { instrument: 'piano', note: 'g3' },
'i': { instrument: 'piano', note: 'g5' },
'j': { instrument: 'piano', note: 'bb6' },
'k': { instrument: 'piano', note: 'eb6' },
'l': { instrument: 'piano', note: 'bb4' },
'm': { instrument: 'piano', note: 'a6' },
'n': { instrument: 'piano', note: 'a5' },
'o': { instrument: 'piano', note: 'd5' },
'p': { instrument: 'piano', note: 'a2' },
'q': { instrument: 'piano', note: 'bb2' },
'r': { instrument: 'piano', note: 'a3' },
's': { instrument: 'piano', note: 'd3' },
't': { instrument: 'piano', note: 'g4' },
'u': { instrument: 'piano', note: 'g6' },
'v': { instrument: 'piano', note: 'bb3' },
'w': { instrument: 'piano', note: 'eb5' },
'x': { instrument: 'piano', note: 'eb2' },
'y': { instrument: 'piano', note: 'g2' },
'z': { instrument: 'piano', note: 'eb7' },
'A': { instrument: 'celesta', note: 'a4' },
'B': { instrument: 'celesta', note: 'eb3' },
'C': { instrument: 'celesta', note: 'd6' },
'D': { instrument: 'celesta', note: 'eb4' },
'E': { instrument: 'celesta', note: 'd4' },
'F': { instrument: 'celesta', note: 'bb4' },
'G': { instrument: 'celesta', note: 'd2' },
'H': { instrument: 'celesta', note: 'g3' },
'I': { instrument: 'celesta', note: 'g5' },
'J': { instrument: 'celesta', note: 'bb6' },
'K': { instrument: 'celesta', note: 'eb6' },
'L': { instrument: 'celesta', note: 'bb5' },
'M': { instrument: 'celesta', note: 'a6' },
'N': { instrument: 'celesta', note: 'a5' },
'O': { instrument: 'celesta', note: 'd5' },
'P': { instrument: 'celesta', note: 'a7' },
'Q': { instrument: 'celesta', note: 'bb7' },
'R': { instrument: 'celesta', note: 'a3' },
'S': { instrument: 'celesta', note: 'd3' },
'T': { instrument: 'celesta', note: 'g4' },
'U': { instrument: 'celesta', note: 'g6' },
'V': { instrument: 'celesta', note: 'bb3' },
'W': { instrument: 'celesta', note: 'eb5' },
'X': { instrument: 'celesta', note: 'eb7' },
'Y': { instrument: 'celesta', note: 'g7' },
'Z': { instrument: 'celesta', note: 'eb2' },
'$': { instrument: 'swell', note: 'eb3' },
',': { instrument: 'swell', note: 'eb3' },
'/': { instrument: 'swell', note: 'bb3' },
'\\': { instrument: 'swell', note: 'eb3' },
':': { instrument: 'swell', note: 'g3' },
';': { instrument: 'swell', note: 'bb3' },
'-': { instrument: 'swell', note: 'bb3' },
'+': { instrument: 'swell', note: 'g3' },
'|': { instrument: 'swell', note: 'bb3' },
'{': { instrument: 'swell', note: 'bb3' },
'}': { instrument: 'swell', note: 'eb3' },
'[': { instrument: 'swell', note: 'g3' },
']': { instrument: 'swell', note: 'bb3' },
'%': { instrument: 'swell', note: 'bb3' },
'&': { instrument: 'swell', note: 'eb3' },
'*': { instrument: 'swell', note: 'eb3' },
'^': { instrument: 'swell', note: 'bb3' },
'#': { instrument: 'swell', note: 'g3' },
'!': { instrument: 'swell', note: 'g3' },
'@': { instrument: 'swell', note: 'eb3' },
'(': { instrument: 'swell', note: 'g3' },
')': { instrument: 'swell', note: 'eb3' },
'=': { instrument: 'swell', note: 'eb3' },
'~': { instrument: 'swell', note: 'g3' },
'`': { instrument: 'swell', note: 'eb3' },
'_': { instrument: 'swell', note: 'g3' },
'"': { instrument: 'swell', note: 'eb3' },
"'": { instrument: 'swell', note: 'bb3' },
'<': { instrument: 'swell', note: 'g3' },
'>': { instrument: 'swell', note: 'g3' },
'.': { instrument: 'swell', note: 'g3' },
'?': { instrument: 'swell', note: 'bb3' },
'0': { instrument: 'fluteorgan', note: 'd3' },
'1': { instrument: 'fluteorgan', note: 'eb3' },
'2': { instrument: 'fluteorgan', note: 'g3' },
'3': { instrument: 'fluteorgan', note: 'a3' },
'4': { instrument: 'fluteorgan', note: 'bb3' },
'5': { instrument: 'fluteorgan', note: 'd2' },
'6': { instrument: 'fluteorgan', note: 'eb2' },
'7': { instrument: 'fluteorgan', note: 'g2' },
'8': { instrument: 'fluteorgan', note: 'a2' },
'9': { instrument: 'fluteorgan', note: 'bb2' },
's1': { instrument: 'swell', note: 'eb3' },
's2': { instrument: 'swell', note: 'g3' },
's3': { instrument: 'swell', note: 'bb3' }
};
|
// ==========================================================================
// Project: SproutCore Metal
// Copyright: ©2011 Strobe Inc. and contributors.
// License: Licensed under MIT license (see license.js)
// ==========================================================================
require('sproutcore-metal');
function isEnumerable(obj, keyName) {
var keys = [];
for(var key in obj) {
if (obj.hasOwnProperty(key)) keys.push(key);
}
return keys.indexOf(keyName)>=0;
}
module("SC.platform.defineProperty()");
test("defining a simple property", function() {
var obj = {};
SC.platform.defineProperty(obj, 'foo', {
enumerable: true,
writable: true,
value: 'FOO'
});
equals(obj.foo, 'FOO', 'should have added property');
obj.foo = "BAR";
equals(obj.foo, 'BAR', 'writable defined property should be writable');
equals(isEnumerable(obj, 'foo'), true, 'foo should be enumerable');
});
test('defining a read only property', function() {
var obj = {};
SC.platform.defineProperty(obj, 'foo', {
enumerable: true,
writable: false,
value: 'FOO'
});
equals(obj.foo, 'FOO', 'should have added property');
obj.foo = "BAR";
if (SC.platform.defineProperty.isSimulated) {
equals(obj.foo, 'BAR', 'simulated defineProperty should silently work');
} else {
equals(obj.foo, 'FOO', 'real defined property should not be writable');
}
});
test('defining a non enumerable property', function() {
var obj = {};
SC.platform.defineProperty(obj, 'foo', {
enumerable: false,
writable: true,
value: 'FOO'
});
if (SC.platform.defineProperty.isSimulated) {
equals(isEnumerable(obj, 'foo'), true, 'simulated defineProperty will leave properties enumerable');
} else {
equals(isEnumerable(obj, 'foo'), false, 'real defineProperty will make property not-enumerable');
}
});
test('defining a getter/setter', function() {
var obj = {}, getCnt = 0, setCnt = 0, v = 'FOO';
var desc = {
enumerable: true,
get: function() { getCnt++; return v; },
set: function(val) { setCnt++; v = val; }
};
if (SC.platform.hasPropertyAccessors) {
SC.platform.defineProperty(obj, 'foo', desc);
equals(obj.foo, 'FOO', 'should return getter');
equals(getCnt, 1, 'should have invoked getter');
obj.foo = 'BAR';
equals(obj.foo, 'BAR', 'setter should have worked');
equals(setCnt, 1, 'should have invoked setter');
} else {
raises(function() {
SC.platform.defineProperty(obj, 'foo', desc);
}, Error, 'should throw exception if getters/setters not supported');
}
});
test('defining getter/setter along with writable', function() {
var obj ={};
raises(function() {
SC.platform.defineProperty(obj, 'foo', {
enumerable: true,
get: function() {},
set: function() {},
writable: true
});
}, Error, 'defining writable and get/set should throw exception');
});
test('defining getter/setter along with value', function() {
var obj ={};
raises(function() {
SC.platform.defineProperty(obj, 'foo', {
enumerable: true,
get: function() {},
set: function() {},
value: 'FOO'
});
}, Error, 'defining value and get/set should throw exception');
});
|
var Promise = require('ember-cli/lib/ext/promise');
module.exports = {
normalizeEntityName: function() {},
afterInstall: function() {
var addonContext = this;
return this.addBowerPackageToProject('jquery-ui', '1.10.1')
.then(function() {
return addonContext.addBowerPackageToProject('jquery-mousewheel', '~3.1.4');
})
.then(function() {
return addonContext.addBowerPackageToProject('taras/antiscroll', '92505e0e0d0ef9383630df509883bce558215b22');
});
}
};
|
Date.CultureInfo = {
/* Culture Name */
name: "fr-FR",
englishName: "French (France)",
nativeName: "français (France)",
/* Day Name Strings */
dayNames: ["dimanche", "lundi", "mardi", "mercredi", "jeudi", "vendredi", "samedi"],
abbreviatedDayNames: ["dim.", "lun.", "mar.", "mer.", "jeu.", "ven.", "sam."],
shortestDayNames: ["di", "lu", "ma", "me", "je", "ve", "sa"],
firstLetterDayNames: ["d", "l", "m", "m", "j", "v", "s"],
/* Month Name Strings */
monthNames: ["janvier", "février", "mars", "avril", "mai", "juin", "juillet", "août", "septembre", "octobre", "novembre", "décembre"],
abbreviatedMonthNames: ["janv.", "févr.", "mars", "avr.", "mai", "juin", "juil.", "août", "sept.", "oct.", "nov.", "déc."],
/* AM/PM Designators */
amDesignator: "",
pmDesignator: "",
firstDayOfWeek: 1,
twoDigitYearMax: 2029,
/**
* The dateElementOrder is based on the order of the
* format specifiers in the formatPatterns.DatePattern.
*
* Example:
<pre>
shortDatePattern dateElementOrder
------------------ ----------------
"M/d/yyyy" "mdy"
"dd/MM/yyyy" "dmy"
"yyyy-MM-dd" "ymd"
</pre>
*
* The correct dateElementOrder is required by the parser to
* determine the expected order of the date elements in the
* string being parsed.
*/
dateElementOrder: "dmy",
/* Standard date and time format patterns */
formatPatterns: {
shortDate: "dd/MM/yyyy",
longDate: "dddd d MMMM yyyy",
shortTime: "HH:mm",
longTime: "HH:mm:ss",
fullDateTime: "dddd d MMMM yyyy HH:mm:ss",
sortableDateTime: "yyyy-MM-ddTHH:mm:ss",
universalSortableDateTime: "yyyy-MM-dd HH:mm:ssZ",
rfc1123: "ddd, dd MMM yyyy HH:mm:ss GMT",
monthDay: "d MMMM",
yearMonth: "MMMM yyyy"
},
/**
* NOTE: If a string format is not parsing correctly, but
* you would expect it parse, the problem likely lies below.
*
* The following regex patterns control most of the string matching
* within the parser.
*
* The Month name and Day name patterns were automatically generated
* and in general should be (mostly) correct.
*
* Beyond the month and day name patterns are natural language strings.
* Example: "next", "today", "months"
*
* These natural language string may NOT be correct for this culture.
* If they are not correct, please translate and edit this file
* providing the correct regular expression pattern.
*
* If you modify this file, please post your revised CultureInfo file
* to the Datejs Forum located at http://www.datejs.com/forums/.
*
* Please mark the subject of the post with [CultureInfo]. Example:
* Subject: [CultureInfo] Translated "da-DK" Danish(Denmark)
*
* We will add the modified patterns to the master source files.
*
* As well, please review the list of "Future Strings" section below.
*/
regexPatterns: {
jan: /^janv(\.|ier)?/i,
feb: /^févr(\.|ier)?/i,
mar: /^mars/i,
apr: /^avr(\.|il)?/i,
may: /^mai/i,
jun: /^juin/i,
jul: /^juil(\.|let)?/i,
aug: /^août/i,
sep: /^sept(\.|embre)?/i,
oct: /^oct(\.|obre)?/i,
nov: /^nov(\.|embre)?/i,
dec: /^déc(\.|embre)?/i,
sun: /^di(\.|m|m\.|anche)?/i,
mon: /^lu(\.|n|n\.|di)?/i,
tue: /^ma(\.|r|r\.|di)?/i,
wed: /^me(\.|r|r\.|credi)?/i,
thu: /^je(\.|u|u\.|di)?/i,
fri: /^ve(\.|n|n\.|dredi)?/i,
sat: /^sa(\.|m|m\.|edi)?/i,
future: /^next/i,
past: /^last|past|prev(ious)?/i,
add: /^(\+|aft(er)?|from|hence)/i,
subtract: /^(\-|bef(ore)?|ago)/i,
yesterday: /^yes(terday)?/i,
today: /^t(od(ay)?)?/i,
tomorrow: /^tom(orrow)?/i,
now: /^n(ow)?/i,
millisecond: /^ms|milli(second)?s?/i,
second: /^sec(ond)?s?/i,
minute: /^mn|min(ute)?s?/i,
hour: /^h(our)?s?/i,
week: /^w(eek)?s?/i,
month: /^m(onth)?s?/i,
day: /^d(ay)?s?/i,
year: /^y(ear)?s?/i,
shortMeridian: /^(a|p)/i,
longMeridian: /^(a\.?m?\.?|p\.?m?\.?)/i,
timezone: /^((e(s|d)t|c(s|d)t|m(s|d)t|p(s|d)t)|((gmt)?\s*(\+|\-)\s*\d\d\d\d?)|gmt|utc)/i,
ordinalSuffix: /^\s*(st|nd|rd|th)/i,
timeContext: /^\s*(\:|a(?!u|p)|p)/i
},
timezones: [{name:"UTC", offset:"-000"}, {name:"GMT", offset:"-000"}, {name:"EST", offset:"-0500"}, {name:"EDT", offset:"-0400"}, {name:"CST", offset:"-0600"}, {name:"CDT", offset:"-0500"}, {name:"MST", offset:"-0700"}, {name:"MDT", offset:"-0600"}, {name:"PST", offset:"-0800"}, {name:"PDT", offset:"-0700"}]
};
/********************
** Future Strings **
********************
*
* The following list of strings may not be currently being used, but
* may be incorporated into the Datejs library later.
*
* We would appreciate any help translating the strings below.
*
* If you modify this file, please post your revised CultureInfo file
* to the Datejs Forum located at http://www.datejs.com/forums/.
*
* Please mark the subject of the post with [CultureInfo]. Example:
* Subject: [CultureInfo] Translated "da-DK" Danish(Denmark)b
*
* English Name Translated
* ------------------ -----------------
* about about
* ago ago
* date date
* time time
* calendar calendar
* show show
* hourly hourly
* daily daily
* weekly weekly
* bi-weekly bi-weekly
* fortnight fortnight
* monthly monthly
* bi-monthly bi-monthly
* quarter quarter
* quarterly quarterly
* yearly yearly
* annual annual
* annually annually
* annum annum
* again again
* between between
* after after
* from now from now
* repeat repeat
* times times
* per per
* min (abbrev minute) min
* morning morning
* noon noon
* night night
* midnight midnight
* mid-night mid-night
* evening evening
* final final
* future future
* spring spring
* summer summer
* fall fall
* winter winter
* end of end of
* end end
* long long
* short short
*/ |
///////////////////////
/// UTILS ///
///////////////////////
var u = {};
u.distance = function (p1, p2) {
var dx = p2.x - p1.x;
var dy = p2.y - p1.y;
return Math.sqrt((dx * dx) + (dy * dy));
};
u.angle = function(p1, p2) {
var dx = p2.x - p1.x;
var dy = p2.y - p1.y;
return u.degrees(Math.atan2(dy, dx));
};
u.findCoord = function(p, d, a) {
var b = {x: 0, y: 0};
a = u.radians(a);
b.x = p.x - d * Math.cos(a);
b.y = p.y - d * Math.sin(a);
return b;
};
u.radians = function(a) {
return a * (Math.PI / 180);
};
u.degrees = function(a) {
return a * (180 / Math.PI);
};
u.bindEvt = function (el, type, handler) {
if (el.addEventListener) {
el.addEventListener(type, handler, false);
} else if (el.attachEvent) {
el.attachEvent(type, handler);
}
};
u.unbindEvt = function (el, type, handler) {
if (el.removeEventListener) {
el.removeEventListener(type, handler);
} else if (el.detachEvent) {
el.detachEvent(type, handler);
}
};
u.trigger = function (el, type, data) {
var evt = new CustomEvent(type, data);
el.dispatchEvent(evt);
};
u.prepareEvent = function (evt) {
evt.preventDefault();
return isTouch ? evt.changedTouches : evt;
};
u.getScroll = function () {
var x = (window.pageXOffset !== undefined) ?
window.pageXOffset :
(document.documentElement || document.body.parentNode || document.body)
.scrollLeft;
var y = (window.pageYOffset !== undefined) ?
window.pageYOffset :
(document.documentElement || document.body.parentNode || document.body)
.scrollTop;
return {
x: x,
y: y
};
};
u.applyPosition = function (el, pos) {
if (pos.x && pos.y) {
el.style.left = pos.x + 'px';
el.style.top = pos.y + 'px';
} else if (pos.top || pos.right || pos.bottom || pos.left) {
el.style.top = pos.top;
el.style.right = pos.right;
el.style.bottom = pos.bottom;
el.style.left = pos.left;
}
};
u.getTransitionStyle = function (property, values, time) {
var obj = u.configStylePropertyObject(property);
for (var i in obj) {
if (obj.hasOwnProperty(i)) {
if (typeof values === 'string') {
obj[i] = values + ' ' + time;
} else {
var st = '';
for (var j = 0, max = values.length; j < max; j += 1) {
st += values[j] + ' ' + time + ', ';
}
obj[i] = st.slice(0, -2);
}
}
}
return obj;
};
u.getVendorStyle = function (property, value) {
var obj = u.configStylePropertyObject(property);
for (var i in obj) {
if (obj.hasOwnProperty(i)) {
obj[i] = value;
}
}
return obj;
};
u.configStylePropertyObject = function (prop) {
var obj = {};
obj[prop] = '';
var vendors = ['webkit', 'Moz', 'o'];
vendors.forEach(function (vendor) {
obj[vendor + prop.charAt(0).toUpperCase() + prop.slice(1)] = '';
});
return obj;
};
u.extend = function (objA, objB) {
for (var i in objB) {
if (objB.hasOwnProperty(i)) {
objA[i] = objB[i];
}
}
};
|
const core = require('brigadehub-core')
var pkg = require('./package.json')
var brigade = require('./brigade')()[0]
const bhConfig = {
dotenv: require('./dotenv')(),
info: '[Brigadehub]',
version: pkg.version,
brigade: brigade
}
core(bhConfig)
|
/**
* @license Angular v4.0.3
* (c) 2010-2017 Google, Inc. https://angular.io/
* License: MIT
*/
import { Compiler, ComponentFactoryResolver, Directive, ElementRef, EventEmitter, Inject, Injector, NgModule, NgZone, ReflectiveInjector, SimpleChange, Testability, Version } from '@angular/core';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* @module
* @description
* Entry point for all public APIs of the common package.
*/
/**
* \@stable
*/
const VERSION = new Version('4.0.3');
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* @return {?}
*/
function noNg() {
throw new Error('AngularJS v1.x is not loaded!');
}
let angular = ({
bootstrap: noNg,
module: noNg,
element: noNg,
version: noNg,
resumeBootstrap: noNg,
getTestability: noNg
});
try {
if (window.hasOwnProperty('angular')) {
angular = ((window)).angular;
}
}
catch (e) {
}
/**
* Resets the AngularJS library.
*
* Used when angularjs is loaded lazily, and not available on `window`.
*
* \@stable
* @param {?} ng
* @return {?}
*/
/**
* Returns the current version of the AngularJS library.
*
* \@stable
* @return {?}
*/
const bootstrap = (e, modules, config) => angular.bootstrap(e, modules, config);
const module$1 = (prefix, dependencies) => angular.module(prefix, dependencies);
const element = (e) => angular.element(e);
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
const $COMPILE = '$compile';
const $CONTROLLER = '$controller';
const $HTTP_BACKEND = '$httpBackend';
const $INJECTOR = '$injector';
const $PARSE = '$parse';
const $ROOT_SCOPE = '$rootScope';
const $SCOPE = '$scope';
const $TEMPLATE_CACHE = '$templateCache';
const $$TESTABILITY = '$$testability';
const COMPILER_KEY = '$$angularCompiler';
const INJECTOR_KEY = '$$angularInjector';
const NG_ZONE_KEY = '$$angularNgZone';
const REQUIRE_INJECTOR = '?^^' + INJECTOR_KEY;
const REQUIRE_NG_MODEL = '?ngModel';
/**
* A `PropertyBinding` represents a mapping between a property name
* and an attribute name. It is parsed from a string of the form
* `"prop: attr"`; or simply `"propAndAttr" where the property
* and attribute have the same identifier.
*/
class PropertyBinding {
/**
* @param {?} prop
* @param {?} attr
*/
constructor(prop, attr) {
this.prop = prop;
this.attr = attr;
this.parseBinding();
}
/**
* @return {?}
*/
parseBinding() {
this.bracketAttr = `[${this.attr}]`;
this.parenAttr = `(${this.attr})`;
this.bracketParenAttr = `[(${this.attr})]`;
const /** @type {?} */ capitalAttr = this.attr.charAt(0).toUpperCase() + this.attr.substr(1);
this.onAttr = `on${capitalAttr}`;
this.bindAttr = `bind${capitalAttr}`;
this.bindonAttr = `bindon${capitalAttr}`;
}
}
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* @param {?} e
* @return {?}
*/
function onError(e) {
// TODO: (misko): We seem to not have a stack trace here!
if (console.error) {
console.error(e, e.stack);
}
else {
// tslint:disable-next-line:no-console
console.log(e, e.stack);
}
throw e;
}
/**
* @param {?} name
* @return {?}
*/
function controllerKey(name) {
return '$' + name + 'Controller';
}
/**
* @param {?} node
* @return {?}
*/
/**
* @param {?} component
* @return {?}
*/
function getComponentName(component) {
// Return the name of the component or the first line of its stringified version.
return ((component)).overriddenName || component.name || component.toString().split('\n')[0];
}
class Deferred {
constructor() {
this.promise = new Promise((res, rej) => {
this.resolve = res;
this.reject = rej;
});
}
}
/**
* @param {?} component
* @return {?} Whether the passed-in component implements the subset of the
* `ControlValueAccessor` interface needed for AngularJS `ng-model`
* compatibility.
*/
function supportsNgModel(component) {
return typeof component.writeValue === 'function' &&
typeof component.registerOnChange === 'function';
}
/**
* Glue the AngularJS `NgModelController` (if it exists) to the component
* (if it implements the needed subset of the `ControlValueAccessor` interface).
* @param {?} ngModel
* @param {?} component
* @return {?}
*/
function hookupNgModel(ngModel, component) {
if (ngModel && supportsNgModel(component)) {
ngModel.$render = () => { component.writeValue(ngModel.$viewValue); };
component.registerOnChange(ngModel.$setViewValue.bind(ngModel));
}
}
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
const INITIAL_VALUE = {
__UNINITIALIZED__: true
};
class DowngradeComponentAdapter {
/**
* @param {?} id
* @param {?} element
* @param {?} attrs
* @param {?} scope
* @param {?} ngModel
* @param {?} parentInjector
* @param {?} $injector
* @param {?} $compile
* @param {?} $parse
* @param {?} componentFactory
*/
constructor(id, element, attrs, scope, ngModel, parentInjector, $injector, $compile, $parse, componentFactory) {
this.id = id;
this.element = element;
this.attrs = attrs;
this.scope = scope;
this.ngModel = ngModel;
this.parentInjector = parentInjector;
this.$injector = $injector;
this.$compile = $compile;
this.$parse = $parse;
this.componentFactory = componentFactory;
this.inputChangeCount = 0;
this.inputChanges = null;
this.componentRef = null;
this.component = null;
this.changeDetector = null;
this.element[0].id = id;
this.componentScope = scope.$new();
}
/**
* @return {?}
*/
compileContents() {
const /** @type {?} */ compiledProjectableNodes = [];
const /** @type {?} */ projectableNodes = this.groupProjectableNodes();
const /** @type {?} */ linkFns = projectableNodes.map(nodes => this.$compile(nodes));
this.element.empty();
linkFns.forEach(linkFn => {
linkFn(this.scope, (clone) => {
compiledProjectableNodes.push(clone);
this.element.append(clone);
});
});
return compiledProjectableNodes;
}
/**
* @param {?} projectableNodes
* @return {?}
*/
createComponent(projectableNodes) {
const /** @type {?} */ childInjector = ReflectiveInjector.resolveAndCreate([{ provide: $SCOPE, useValue: this.componentScope }], this.parentInjector);
this.componentRef =
this.componentFactory.create(childInjector, projectableNodes, this.element[0]);
this.changeDetector = this.componentRef.changeDetectorRef;
this.component = this.componentRef.instance;
hookupNgModel(this.ngModel, this.component);
}
/**
* @return {?}
*/
setupInputs() {
const /** @type {?} */ attrs = this.attrs;
const /** @type {?} */ inputs = this.componentFactory.inputs || [];
for (let /** @type {?} */ i = 0; i < inputs.length; i++) {
const /** @type {?} */ input = new PropertyBinding(inputs[i].propName, inputs[i].templateName);
let /** @type {?} */ expr = null;
if (attrs.hasOwnProperty(input.attr)) {
const /** @type {?} */ observeFn = (prop => {
let /** @type {?} */ prevValue = INITIAL_VALUE;
return (currValue) => {
if (prevValue === INITIAL_VALUE) {
prevValue = currValue;
}
this.updateInput(prop, prevValue, currValue);
prevValue = currValue;
};
})(input.prop);
attrs.$observe(input.attr, observeFn);
}
else if (attrs.hasOwnProperty(input.bindAttr)) {
expr = ((attrs) /** TODO #9100 */)[input.bindAttr];
}
else if (attrs.hasOwnProperty(input.bracketAttr)) {
expr = ((attrs) /** TODO #9100 */)[input.bracketAttr];
}
else if (attrs.hasOwnProperty(input.bindonAttr)) {
expr = ((attrs) /** TODO #9100 */)[input.bindonAttr];
}
else if (attrs.hasOwnProperty(input.bracketParenAttr)) {
expr = ((attrs) /** TODO #9100 */)[input.bracketParenAttr];
}
if (expr != null) {
const /** @type {?} */ watchFn = (prop => (currValue, prevValue) => this.updateInput(prop, prevValue, currValue))(input.prop);
this.componentScope.$watch(expr, watchFn);
}
}
const /** @type {?} */ prototype = this.componentFactory.componentType.prototype;
if (prototype && ((prototype)).ngOnChanges) {
// Detect: OnChanges interface
this.inputChanges = {};
this.componentScope.$watch(() => this.inputChangeCount, () => {
const /** @type {?} */ inputChanges = this.inputChanges;
this.inputChanges = {};
((this.component)).ngOnChanges(inputChanges);
});
}
this.componentScope.$watch(() => this.changeDetector && this.changeDetector.detectChanges());
}
/**
* @return {?}
*/
setupOutputs() {
const /** @type {?} */ attrs = this.attrs;
const /** @type {?} */ outputs = this.componentFactory.outputs || [];
for (let /** @type {?} */ j = 0; j < outputs.length; j++) {
const /** @type {?} */ output = new PropertyBinding(outputs[j].propName, outputs[j].templateName);
let /** @type {?} */ expr = null;
let /** @type {?} */ assignExpr = false;
const /** @type {?} */ bindonAttr = output.bindonAttr ? output.bindonAttr.substring(0, output.bindonAttr.length - 6) : null;
const /** @type {?} */ bracketParenAttr = output.bracketParenAttr ?
`[(${output.bracketParenAttr.substring(2, output.bracketParenAttr.length - 8)})]` :
null;
if (attrs.hasOwnProperty(output.onAttr)) {
expr = ((attrs) /** TODO #9100 */)[output.onAttr];
}
else if (attrs.hasOwnProperty(output.parenAttr)) {
expr = ((attrs) /** TODO #9100 */)[output.parenAttr];
}
else if (attrs.hasOwnProperty(bindonAttr)) {
expr = ((attrs) /** TODO #9100 */)[bindonAttr];
assignExpr = true;
}
else if (attrs.hasOwnProperty(bracketParenAttr)) {
expr = ((attrs) /** TODO #9100 */)[bracketParenAttr];
assignExpr = true;
}
if (expr != null && assignExpr != null) {
const /** @type {?} */ getter = this.$parse(expr);
const /** @type {?} */ setter = getter.assign;
if (assignExpr && !setter) {
throw new Error(`Expression '${expr}' is not assignable!`);
}
const /** @type {?} */ emitter = (this.component[output.prop]);
if (emitter) {
emitter.subscribe({
next: assignExpr ?
((setter) => (v /** TODO #9100 */) => setter(this.scope, v))(setter) :
((getter) => (v /** TODO #9100 */) => getter(this.scope, { $event: v }))(getter)
});
}
else {
throw new Error(`Missing emitter '${output.prop}' on component '${getComponentName(this.componentFactory.componentType)}'!`);
}
}
}
}
/**
* @return {?}
*/
registerCleanup() {
this.element.bind('$destroy', () => {
this.componentScope.$destroy();
this.componentRef.destroy();
});
}
/**
* @return {?}
*/
getInjector() { return this.componentRef && this.componentRef.injector; }
/**
* @param {?} prop
* @param {?} prevValue
* @param {?} currValue
* @return {?}
*/
updateInput(prop, prevValue, currValue) {
if (this.inputChanges) {
this.inputChangeCount++;
this.inputChanges[prop] = new SimpleChange(prevValue, currValue, prevValue === currValue);
}
this.component[prop] = currValue;
}
/**
* @return {?}
*/
groupProjectableNodes() {
let /** @type {?} */ ngContentSelectors = this.componentFactory.ngContentSelectors;
return groupNodesBySelector(ngContentSelectors, this.element.contents());
}
}
/**
* Group a set of DOM nodes into `ngContent` groups, based on the given content selectors.
* @param {?} ngContentSelectors
* @param {?} nodes
* @return {?}
*/
function groupNodesBySelector(ngContentSelectors, nodes) {
const /** @type {?} */ projectableNodes = [];
let /** @type {?} */ wildcardNgContentIndex;
for (let /** @type {?} */ i = 0, /** @type {?} */ ii = ngContentSelectors.length; i < ii; ++i) {
projectableNodes[i] = [];
}
for (let /** @type {?} */ j = 0, /** @type {?} */ jj = nodes.length; j < jj; ++j) {
const /** @type {?} */ node = nodes[j];
const /** @type {?} */ ngContentIndex = findMatchingNgContentIndex(node, ngContentSelectors);
if (ngContentIndex != null) {
projectableNodes[ngContentIndex].push(node);
}
}
return projectableNodes;
}
/**
* @param {?} element
* @param {?} ngContentSelectors
* @return {?}
*/
function findMatchingNgContentIndex(element, ngContentSelectors) {
const /** @type {?} */ ngContentIndices = [];
let /** @type {?} */ wildcardNgContentIndex;
for (let /** @type {?} */ i = 0; i < ngContentSelectors.length; i++) {
const /** @type {?} */ selector = ngContentSelectors[i];
if (selector === '*') {
wildcardNgContentIndex = i;
}
else {
if (matchesSelector(element, selector)) {
ngContentIndices.push(i);
}
}
}
ngContentIndices.sort();
if (wildcardNgContentIndex !== undefined) {
ngContentIndices.push(wildcardNgContentIndex);
}
return ngContentIndices.length ? ngContentIndices[0] : null;
}
let _matches;
/**
* @param {?} el
* @param {?} selector
* @return {?}
*/
function matchesSelector(el, selector) {
if (!_matches) {
const /** @type {?} */ elProto = (Element.prototype);
_matches = elProto.matches || elProto.matchesSelector || elProto.mozMatchesSelector ||
elProto.msMatchesSelector || elProto.oMatchesSelector || elProto.webkitMatchesSelector;
}
return el.nodeType === Node.ELEMENT_NODE ? _matches.call(el, selector) : false;
}
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
let downgradeCount = 0;
/**
* \@whatItDoes
*
* *Part of the [upgrade/static](/docs/ts/latest/api/#!?query=upgrade%2Fstatic)
* library for hybrid upgrade apps that support AoT compilation*
*
* Allows an Angular component to be used from AngularJS.
*
* \@howToUse
*
* Let's assume that you have an Angular component called `ng2Heroes` that needs
* to be made available in AngularJS templates.
*
* {\@example upgrade/static/ts/module.ts region="ng2-heroes"}
*
* We must create an AngularJS [directive](https://docs.angularjs.org/guide/directive)
* that will make this Angular component available inside AngularJS templates.
* The `downgradeComponent()` function returns a factory function that we
* can use to define the AngularJS directive that wraps the "downgraded" component.
*
* {\@example upgrade/static/ts/module.ts region="ng2-heroes-wrapper"}
*
* \@description
*
* A helper function that returns a factory function to be used for registering an
* AngularJS wrapper directive for "downgrading" an Angular component.
*
* The parameter contains information about the Component that is being downgraded:
*
* * `component: Type<any>`: The type of the Component that will be downgraded
*
* \@experimental
* @param {?} info
* @return {?}
*/
function downgradeComponent(info) {
const /** @type {?} */ idPrefix = `NG2_UPGRADE_${downgradeCount++}_`;
let /** @type {?} */ idCount = 0;
const /** @type {?} */ directiveFactory = function ($compile, $injector, $parse) {
return {
restrict: 'E',
terminal: true,
require: [REQUIRE_INJECTOR, REQUIRE_NG_MODEL],
link: (scope, element, attrs, required) => {
// We might have to compile the contents asynchronously, because this might have been
// triggered by `UpgradeNg1ComponentAdapterBuilder`, before the Angular templates have
// been compiled.
const /** @type {?} */ parentInjector = required[0] || $injector.get(INJECTOR_KEY);
const /** @type {?} */ ngModel = required[1];
const /** @type {?} */ downgradeFn = (injector) => {
const /** @type {?} */ componentFactoryResolver = injector.get(ComponentFactoryResolver);
const /** @type {?} */ componentFactory = componentFactoryResolver.resolveComponentFactory(info.component);
if (!componentFactory) {
throw new Error('Expecting ComponentFactory for: ' + getComponentName(info.component));
}
const /** @type {?} */ id = idPrefix + (idCount++);
const /** @type {?} */ injectorPromise = new ParentInjectorPromise$1(element);
const /** @type {?} */ facade = new DowngradeComponentAdapter(id, element, attrs, scope, ngModel, injector, $injector, $compile, $parse, componentFactory);
const /** @type {?} */ projectableNodes = facade.compileContents();
facade.createComponent(projectableNodes);
facade.setupInputs();
facade.setupOutputs();
facade.registerCleanup();
injectorPromise.resolve(facade.getInjector());
};
if (parentInjector instanceof ParentInjectorPromise$1) {
parentInjector.then(downgradeFn);
}
else {
downgradeFn(parentInjector);
}
}
};
};
// bracket-notation because of closure - see #14441
directiveFactory['$inject'] = [$COMPILE, $INJECTOR, $PARSE];
return directiveFactory;
}
/**
* Synchronous promise-like object to wrap parent injectors,
* to preserve the synchronous nature of Angular 1's $compile.
*/
class ParentInjectorPromise$1 {
/**
* @param {?} element
*/
constructor(element) {
this.element = element;
this.injectorKey = controllerKey(INJECTOR_KEY);
this.callbacks = [];
// Store the promise on the element.
element.data(this.injectorKey, this);
}
/**
* @param {?} callback
* @return {?}
*/
then(callback) {
if (this.injector) {
callback(this.injector);
}
else {
this.callbacks.push(callback);
}
}
/**
* @param {?} injector
* @return {?}
*/
resolve(injector) {
this.injector = injector;
// Store the real injector on the element.
this.element.data(this.injectorKey, injector);
// Release the element to prevent memory leaks.
this.element = null;
// Run the queued callbacks.
this.callbacks.forEach(callback => callback(injector));
this.callbacks.length = 0;
}
}
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* \@whatItDoes
*
* *Part of the [upgrade/static](/docs/ts/latest/api/#!?query=upgrade%2Fstatic)
* library for hybrid upgrade apps that support AoT compilation*
*
* Allow an Angular service to be accessible from AngularJS.
*
* \@howToUse
*
* First ensure that the service to be downgraded is provided in an {\@link NgModule}
* that will be part of the upgrade application. For example, let's assume we have
* defined `HeroesService`
*
* {\@example upgrade/static/ts/module.ts region="ng2-heroes-service"}
*
* and that we have included this in our upgrade app {\@link NgModule}
*
* {\@example upgrade/static/ts/module.ts region="ng2-module"}
*
* Now we can register the `downgradeInjectable` factory function for the service
* on an AngularJS module.
*
* {\@example upgrade/static/ts/module.ts region="downgrade-ng2-heroes-service"}
*
* Inside an AngularJS component's controller we can get hold of the
* downgraded service via the name we gave when downgrading.
*
* {\@example upgrade/static/ts/module.ts region="example-app"}
*
* \@description
*
* Takes a `token` that identifies a service provided from Angular.
*
* Returns a [factory function](https://docs.angularjs.org/guide/di) that can be
* used to register the service on an AngularJS module.
*
* The factory function provides access to the Angular service that
* is identified by the `token` parameter.
*
* \@experimental
* @param {?} token
* @return {?}
*/
function downgradeInjectable(token) {
const /** @type {?} */ factory = function (i) { return i.get(token); };
((factory)).$inject = [INJECTOR_KEY];
return factory;
}
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
const CAMEL_CASE = /([A-Z])/g;
const INITIAL_VALUE$1 = {
__UNINITIALIZED__: true
};
const NOT_SUPPORTED = 'NOT_SUPPORTED';
class UpgradeNg1ComponentAdapterBuilder {
/**
* @param {?} name
*/
constructor(name) {
this.name = name;
this.inputs = [];
this.inputsRename = [];
this.outputs = [];
this.outputsRename = [];
this.propertyOutputs = [];
this.checkProperties = [];
this.propertyMap = {};
this.linkFn = null;
this.directive = null;
this.$controller = null;
const selector = name.replace(CAMEL_CASE, (all /** TODO #9100 */, next) => '-' + next.toLowerCase());
const self = this;
this.type =
Directive({ selector: selector, inputs: this.inputsRename, outputs: this.outputsRename })
.Class({
constructor: [
new Inject($SCOPE), ElementRef,
function (scope, elementRef) {
return new UpgradeNg1ComponentAdapter(self.linkFn, scope, self.directive, elementRef, self.$controller, self.inputs, self.outputs, self.propertyOutputs, self.checkProperties, self.propertyMap);
}
],
ngOnInit: function () { },
ngOnChanges: function () { },
ngDoCheck: function () { },
ngOnDestroy: function () { },
});
}
/**
* @param {?} injector
* @return {?}
*/
extractDirective(injector) {
const /** @type {?} */ directives = injector.get(this.name + 'Directive');
if (directives.length > 1) {
throw new Error('Only support single directive definition for: ' + this.name);
}
const /** @type {?} */ directive = directives[0];
if (directive.replace)
this.notSupported('replace');
if (directive.terminal)
this.notSupported('terminal');
const /** @type {?} */ link = directive.link;
if (typeof link == 'object') {
if (((link)).post)
this.notSupported('link.post');
}
return directive;
}
/**
* @param {?} feature
* @return {?}
*/
notSupported(feature) {
throw new Error(`Upgraded directive '${this.name}' does not support '${feature}'.`);
}
/**
* @return {?}
*/
extractBindings() {
const /** @type {?} */ btcIsObject = typeof this.directive.bindToController === 'object';
if (btcIsObject && Object.keys(this.directive.scope).length) {
throw new Error(`Binding definitions on scope and controller at the same time are not supported.`);
}
const /** @type {?} */ context = (btcIsObject) ? this.directive.bindToController : this.directive.scope;
if (typeof context == 'object') {
for (const /** @type {?} */ name in context) {
if (((context)).hasOwnProperty(name)) {
let /** @type {?} */ localName = context[name];
const /** @type {?} */ type = localName.charAt(0);
const /** @type {?} */ typeOptions = localName.charAt(1);
localName = typeOptions === '?' ? localName.substr(2) : localName.substr(1);
localName = localName || name;
const /** @type {?} */ outputName = 'output_' + name;
const /** @type {?} */ outputNameRename = outputName + ': ' + name;
const /** @type {?} */ outputNameRenameChange = outputName + ': ' + name + 'Change';
const /** @type {?} */ inputName = 'input_' + name;
const /** @type {?} */ inputNameRename = inputName + ': ' + name;
switch (type) {
case '=':
this.propertyOutputs.push(outputName);
this.checkProperties.push(localName);
this.outputs.push(outputName);
this.outputsRename.push(outputNameRenameChange);
this.propertyMap[outputName] = localName;
this.inputs.push(inputName);
this.inputsRename.push(inputNameRename);
this.propertyMap[inputName] = localName;
break;
case '@':
// handle the '<' binding of angular 1.5 components
case '<':
this.inputs.push(inputName);
this.inputsRename.push(inputNameRename);
this.propertyMap[inputName] = localName;
break;
case '&':
this.outputs.push(outputName);
this.outputsRename.push(outputNameRename);
this.propertyMap[outputName] = localName;
break;
default:
let /** @type {?} */ json = JSON.stringify(context);
throw new Error(`Unexpected mapping '${type}' in '${json}' in '${this.name}' directive.`);
}
}
}
}
}
/**
* @param {?} compile
* @param {?} templateCache
* @param {?} httpBackend
* @return {?}
*/
compileTemplate(compile, templateCache, httpBackend) {
if (this.directive.template !== undefined) {
this.linkFn = compileHtml(isFunction(this.directive.template) ? this.directive.template() :
this.directive.template);
}
else if (this.directive.templateUrl) {
const /** @type {?} */ url = isFunction(this.directive.templateUrl) ? this.directive.templateUrl() :
this.directive.templateUrl;
const /** @type {?} */ html = templateCache.get(url);
if (html !== undefined) {
this.linkFn = compileHtml(html);
}
else {
return new Promise((resolve, err) => {
httpBackend('GET', url, null, (status /** TODO #9100 */, response /** TODO #9100 */) => {
if (status == 200) {
resolve(this.linkFn = compileHtml(templateCache.put(url, response)));
}
else {
err(`GET ${url} returned ${status}: ${response}`);
}
});
});
}
}
else {
throw new Error(`Directive '${this.name}' is not a component, it is missing template.`);
}
return null;
/**
* @param {?} html
* @return {?}
*/
function compileHtml(html /** TODO #9100 */) {
const /** @type {?} */ div = document.createElement('div');
div.innerHTML = html;
return compile(div.childNodes);
}
}
/**
* Upgrade ng1 components into Angular.
* @param {?} exportedComponents
* @param {?} injector
* @return {?}
*/
static resolve(exportedComponents, injector) {
const /** @type {?} */ promises = [];
const /** @type {?} */ compile = injector.get($COMPILE);
const /** @type {?} */ templateCache = injector.get($TEMPLATE_CACHE);
const /** @type {?} */ httpBackend = injector.get($HTTP_BACKEND);
const /** @type {?} */ $controller = injector.get($CONTROLLER);
for (const /** @type {?} */ name in exportedComponents) {
if (((exportedComponents)).hasOwnProperty(name)) {
const /** @type {?} */ exportedComponent = exportedComponents[name];
exportedComponent.directive = exportedComponent.extractDirective(injector);
exportedComponent.$controller = $controller;
exportedComponent.extractBindings();
const /** @type {?} */ promise = exportedComponent.compileTemplate(compile, templateCache, httpBackend);
if (promise)
promises.push(promise);
}
}
return Promise.all(promises);
}
}
class UpgradeNg1ComponentAdapter {
/**
* @param {?} linkFn
* @param {?} scope
* @param {?} directive
* @param {?} elementRef
* @param {?} $controller
* @param {?} inputs
* @param {?} outputs
* @param {?} propOuts
* @param {?} checkProperties
* @param {?} propertyMap
*/
constructor(linkFn, scope, directive, elementRef, $controller, inputs, outputs, propOuts, checkProperties, propertyMap) {
this.linkFn = linkFn;
this.directive = directive;
this.$controller = $controller;
this.inputs = inputs;
this.outputs = outputs;
this.propOuts = propOuts;
this.checkProperties = checkProperties;
this.propertyMap = propertyMap;
this.controllerInstance = null;
this.destinationObj = null;
this.checkLastValues = [];
this.$element = null;
this.element = elementRef.nativeElement;
this.componentScope = scope.$new(!!directive.scope);
this.$element = element(this.element);
const controllerType = directive.controller;
if (directive.bindToController && controllerType) {
this.controllerInstance = this.buildController(controllerType);
this.destinationObj = this.controllerInstance;
}
else {
this.destinationObj = this.componentScope;
}
for (let i = 0; i < inputs.length; i++) {
this /** TODO #9100 */[inputs[i]] = null;
}
for (let j = 0; j < outputs.length; j++) {
const emitter = this /** TODO #9100 */[outputs[j]] = new EventEmitter();
this.setComponentProperty(outputs[j], ((emitter /** TODO #9100 */) => (value /** TODO #9100 */) => emitter.emit(value))(emitter));
}
for (let k = 0; k < propOuts.length; k++) {
this /** TODO #9100 */[propOuts[k]] = new EventEmitter();
this.checkLastValues.push(INITIAL_VALUE$1);
}
}
/**
* @return {?}
*/
ngOnInit() {
if (!this.directive.bindToController && this.directive.controller) {
this.controllerInstance = this.buildController(this.directive.controller);
}
if (this.controllerInstance && isFunction(this.controllerInstance.$onInit)) {
this.controllerInstance.$onInit();
}
let /** @type {?} */ link = this.directive.link;
if (typeof link == 'object')
link = ((link)).pre;
if (link) {
const /** @type {?} */ attrs = NOT_SUPPORTED;
const /** @type {?} */ transcludeFn = NOT_SUPPORTED;
const /** @type {?} */ linkController = this.resolveRequired(this.$element, this.directive.require);
((this.directive.link))(this.componentScope, this.$element, attrs, linkController, transcludeFn);
}
const /** @type {?} */ childNodes = [];
let /** @type {?} */ childNode;
while (childNode = this.element.firstChild) {
this.element.removeChild(childNode);
childNodes.push(childNode);
}
this.linkFn(this.componentScope, (clonedElement, scope) => {
for (let /** @type {?} */ i = 0, /** @type {?} */ ii = clonedElement.length; i < ii; i++) {
this.element.appendChild(clonedElement[i]);
}
}, {
parentBoundTranscludeFn: (scope /** TODO #9100 */, cloneAttach /** TODO #9100 */) => { cloneAttach(childNodes); }
});
if (this.controllerInstance && isFunction(this.controllerInstance.$postLink)) {
this.controllerInstance.$postLink();
}
}
/**
* @param {?} changes
* @return {?}
*/
ngOnChanges(changes) {
const /** @type {?} */ ng1Changes = {};
Object.keys(changes).forEach(name => {
const /** @type {?} */ change = changes[name];
this.setComponentProperty(name, change.currentValue);
ng1Changes[this.propertyMap[name]] = change;
});
if (isFunction(this.destinationObj.$onChanges)) {
this.destinationObj.$onChanges(ng1Changes);
}
}
/**
* @return {?}
*/
ngDoCheck() {
const /** @type {?} */ destinationObj = this.destinationObj;
const /** @type {?} */ lastValues = this.checkLastValues;
const /** @type {?} */ checkProperties = this.checkProperties;
for (let /** @type {?} */ i = 0; i < checkProperties.length; i++) {
const /** @type {?} */ value = destinationObj[checkProperties[i]];
const /** @type {?} */ last = lastValues[i];
if (value !== last) {
if (typeof value == 'number' && isNaN(value) && typeof last == 'number' && isNaN(last)) {
}
else {
const /** @type {?} */ eventEmitter = ((this) /** TODO #9100 */)[this.propOuts[i]];
eventEmitter.emit(lastValues[i] = value);
}
}
}
if (this.controllerInstance && isFunction(this.controllerInstance.$doCheck)) {
this.controllerInstance.$doCheck();
}
}
/**
* @return {?}
*/
ngOnDestroy() {
if (this.controllerInstance && isFunction(this.controllerInstance.$onDestroy)) {
this.controllerInstance.$onDestroy();
}
}
/**
* @param {?} name
* @param {?} value
* @return {?}
*/
setComponentProperty(name, value) {
this.destinationObj[this.propertyMap[name]] = value;
}
/**
* @param {?} controllerType
* @return {?}
*/
buildController(controllerType /** TODO #9100 */) {
const /** @type {?} */ locals = { $scope: this.componentScope, $element: this.$element };
const /** @type {?} */ controller = this.$controller(controllerType, locals, null, this.directive.controllerAs);
this.$element.data(controllerKey(this.directive.name), controller);
return controller;
}
/**
* @param {?} $element
* @param {?} require
* @return {?}
*/
resolveRequired($element, require) {
if (!require) {
return undefined;
}
else if (typeof require == 'string') {
let /** @type {?} */ name = (require);
let /** @type {?} */ isOptional = false;
let /** @type {?} */ startParent = false;
let /** @type {?} */ searchParents = false;
if (name.charAt(0) == '?') {
isOptional = true;
name = name.substr(1);
}
if (name.charAt(0) == '^') {
searchParents = true;
name = name.substr(1);
}
if (name.charAt(0) == '^') {
startParent = true;
name = name.substr(1);
}
const /** @type {?} */ key = controllerKey(name);
if (startParent)
$element = $element.parent();
const /** @type {?} */ dep = searchParents ? $element.inheritedData(key) : $element.data(key);
if (!dep && !isOptional) {
throw new Error(`Can not locate '${require}' in '${this.directive.name}'.`);
}
return dep;
}
else if (require instanceof Array) {
const /** @type {?} */ deps = [];
for (let /** @type {?} */ i = 0; i < require.length; i++) {
deps.push(this.resolveRequired($element, require[i]));
}
return deps;
}
throw new Error(`Directive '${this.directive.name}' require syntax unrecognized: ${this.directive.require}`);
}
}
/**
* @param {?} value
* @return {?}
*/
function isFunction(value) {
return typeof value === 'function';
}
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
let upgradeCount = 0;
/**
* Use `UpgradeAdapter` to allow AngularJS and Angular to coexist in a single application.
*
* The `UpgradeAdapter` allows:
* 1. creation of Angular component from AngularJS component directive
* (See [UpgradeAdapter#upgradeNg1Component()])
* 2. creation of AngularJS directive from Angular component.
* (See [UpgradeAdapter#downgradeNg2Component()])
* 3. Bootstrapping of a hybrid Angular application which contains both of the frameworks
* coexisting in a single application.
*
* ## Mental Model
*
* When reasoning about how a hybrid application works it is useful to have a mental model which
* describes what is happening and explains what is happening at the lowest level.
*
* 1. There are two independent frameworks running in a single application, each framework treats
* the other as a black box.
* 2. Each DOM element on the page is owned exactly by one framework. Whichever framework
* instantiated the element is the owner. Each framework only updates/interacts with its own
* DOM elements and ignores others.
* 3. AngularJS directives always execute inside AngularJS framework codebase regardless of
* where they are instantiated.
* 4. Angular components always execute inside Angular framework codebase regardless of
* where they are instantiated.
* 5. An AngularJS component can be upgraded to an Angular component. This creates an
* Angular directive, which bootstraps the AngularJS component directive in that location.
* 6. An Angular component can be downgraded to an AngularJS component directive. This creates
* an AngularJS directive, which bootstraps the Angular component in that location.
* 7. Whenever an adapter component is instantiated the host element is owned by the framework
* doing the instantiation. The other framework then instantiates and owns the view for that
* component. This implies that component bindings will always follow the semantics of the
* instantiation framework. The syntax is always that of Angular syntax.
* 8. AngularJS is always bootstrapped first and owns the bottom most view.
* 9. The new application is running in Angular zone, and therefore it no longer needs calls to
* `$apply()`.
*
* ### Example
*
* ```
* const adapter = new UpgradeAdapter(forwardRef(() => MyNg2Module), myCompilerOptions);
* const module = angular.module('myExample', []);
* module.directive('ng2Comp', adapter.downgradeNg2Component(Ng2Component));
*
* module.directive('ng1Hello', function() {
* return {
* scope: { title: '=' },
* template: 'ng1[Hello {{title}}!](<span ng-transclude></span>)'
* };
* });
*
*
* \@Component({
* selector: 'ng2-comp',
* inputs: ['name'],
* template: 'ng2[<ng1-hello [title]="name">transclude</ng1-hello>](<ng-content></ng-content>)',
* directives:
* })
* class Ng2Component {
* }
*
* \@NgModule({
* declarations: [Ng2Component, adapter.upgradeNg1Component('ng1Hello')],
* imports: [BrowserModule]
* })
* class MyNg2Module {}
*
*
* document.body.innerHTML = '<ng2-comp name="World">project</ng2-comp>';
*
* adapter.bootstrap(document.body, ['myExample']).ready(function() {
* expect(document.body.textContent).toEqual(
* "ng2[ng1[Hello World!](transclude)](project)");
* });
*
* ```
*
* \@stable
*/
class UpgradeAdapter {
/**
* @param {?} ng2AppModule
* @param {?=} compilerOptions
*/
constructor(ng2AppModule, compilerOptions) {
this.ng2AppModule = ng2AppModule;
this.compilerOptions = compilerOptions;
this.idPrefix = `NG2_UPGRADE_${upgradeCount++}_`;
this.downgradedComponents = [];
/**
* An internal map of ng1 components which need to up upgraded to ng2.
*
* We can't upgrade until injector is instantiated and we can retrieve the component metadata.
* For this reason we keep a list of components to upgrade until ng1 injector is bootstrapped.
*
* \@internal
*/
this.ng1ComponentsToBeUpgraded = {};
this.upgradedProviders = [];
this.moduleRef = null;
if (!ng2AppModule) {
throw new Error('UpgradeAdapter cannot be instantiated without an NgModule of the Angular app.');
}
}
/**
* Allows Angular Component to be used from AngularJS.
*
* Use `downgradeNg2Component` to create an AngularJS Directive Definition Factory from
* Angular Component. The adapter will bootstrap Angular component from within the
* AngularJS template.
*
* ## Mental Model
*
* 1. The component is instantiated by being listed in AngularJS template. This means that the
* host element is controlled by AngularJS, but the component's view will be controlled by
* Angular.
* 2. Even thought the component is instantiated in AngularJS, it will be using Angular
* syntax. This has to be done, this way because we must follow Angular components do not
* declare how the attributes should be interpreted.
* 3. `ng-model` is controlled by AngularJS and communicates with the downgraded Angular component
* by way of the `ControlValueAccessor` interface from \@angular/forms. Only components that
* implement this interface are eligible.
*
* ## Supported Features
*
* - Bindings:
* - Attribute: `<comp name="World">`
* - Interpolation: `<comp greeting="Hello {{name}}!">`
* - Expression: `<comp [name]="username">`
* - Event: `<comp (close)="doSomething()">`
* - ng-model: `<comp ng-model="name">`
* - Content projection: yes
*
* ### Example
*
* ```
* const adapter = new UpgradeAdapter(forwardRef(() => MyNg2Module));
* const module = angular.module('myExample', []);
* module.directive('greet', adapter.downgradeNg2Component(Greeter));
*
* \@Component({
* selector: 'greet',
* template: '{{salutation}} {{name}}! - <ng-content></ng-content>'
* })
* class Greeter {
* \@Input() salutation: string;
* \@Input() name: string;
* }
*
* \@NgModule({
* declarations: [Greeter],
* imports: [BrowserModule]
* })
* class MyNg2Module {}
*
* document.body.innerHTML =
* 'ng1 template: <greet salutation="Hello" [name]="world">text</greet>';
*
* adapter.bootstrap(document.body, ['myExample']).ready(function() {
* expect(document.body.textContent).toEqual("ng1 template: Hello world! - text");
* });
* ```
* @param {?} component
* @return {?}
*/
downgradeNg2Component(component) {
this.downgradedComponents.push(component);
return downgradeComponent({ component });
}
/**
* Allows AngularJS Component to be used from Angular.
*
* Use `upgradeNg1Component` to create an Angular component from AngularJS Component
* directive. The adapter will bootstrap AngularJS component from within the Angular
* template.
*
* ## Mental Model
*
* 1. The component is instantiated by being listed in Angular template. This means that the
* host element is controlled by Angular, but the component's view will be controlled by
* AngularJS.
*
* ## Supported Features
*
* - Bindings:
* - Attribute: `<comp name="World">`
* - Interpolation: `<comp greeting="Hello {{name}}!">`
* - Expression: `<comp [name]="username">`
* - Event: `<comp (close)="doSomething()">`
* - Transclusion: yes
* - Only some of the features of
* [Directive Definition Object](https://docs.angularjs.org/api/ng/service/$compile) are
* supported:
* - `compile`: not supported because the host element is owned by Angular, which does
* not allow modifying DOM structure during compilation.
* - `controller`: supported. (NOTE: injection of `$attrs` and `$transclude` is not supported.)
* - `controllerAs`: supported.
* - `bindToController`: supported.
* - `link`: supported. (NOTE: only pre-link function is supported.)
* - `name`: supported.
* - `priority`: ignored.
* - `replace`: not supported.
* - `require`: supported.
* - `restrict`: must be set to 'E'.
* - `scope`: supported.
* - `template`: supported.
* - `templateUrl`: supported.
* - `terminal`: ignored.
* - `transclude`: supported.
*
*
* ### Example
*
* ```
* const adapter = new UpgradeAdapter(forwardRef(() => MyNg2Module));
* const module = angular.module('myExample', []);
*
* module.directive('greet', function() {
* return {
* scope: {salutation: '=', name: '=' },
* template: '{{salutation}} {{name}}! - <span ng-transclude></span>'
* };
* });
*
* module.directive('ng2', adapter.downgradeNg2Component(Ng2Component));
*
* \@Component({
* selector: 'ng2',
* template: 'ng2 template: <greet salutation="Hello" [name]="world">text</greet>'
* })
* class Ng2Component {
* }
*
* \@NgModule({
* declarations: [Ng2Component, adapter.upgradeNg1Component('greet')],
* imports: [BrowserModule]
* })
* class MyNg2Module {}
*
* document.body.innerHTML = '<ng2></ng2>';
*
* adapter.bootstrap(document.body, ['myExample']).ready(function() {
* expect(document.body.textContent).toEqual("ng2 template: Hello world! - text");
* });
* ```
* @param {?} name
* @return {?}
*/
upgradeNg1Component(name) {
if (((this.ng1ComponentsToBeUpgraded)).hasOwnProperty(name)) {
return this.ng1ComponentsToBeUpgraded[name].type;
}
else {
return (this.ng1ComponentsToBeUpgraded[name] = new UpgradeNg1ComponentAdapterBuilder(name))
.type;
}
}
/**
* Registers the adapter's AngularJS upgrade module for unit testing in AngularJS.
* Use this instead of `angular.mock.module()` to load the upgrade module into
* the AngularJS testing injector.
*
* ### Example
*
* ```
* const upgradeAdapter = new UpgradeAdapter(MyNg2Module);
*
* // configure the adapter with upgrade/downgrade components and services
* upgradeAdapter.downgradeNg2Component(MyComponent);
*
* let upgradeAdapterRef: UpgradeAdapterRef;
* let $compile, $rootScope;
*
* // We must register the adapter before any calls to `inject()`
* beforeEach(() => {
* upgradeAdapterRef = upgradeAdapter.registerForNg1Tests(['heroApp']);
* });
*
* beforeEach(inject((_$compile_, _$rootScope_) => {
* $compile = _$compile_;
* $rootScope = _$rootScope_;
* }));
*
* it("says hello", (done) => {
* upgradeAdapterRef.ready(() => {
* const element = $compile("<my-component></my-component>")($rootScope);
* $rootScope.$apply();
* expect(element.html()).toContain("Hello World");
* done();
* })
* });
*
* ```
*
* @param {?=} modules any AngularJS modules that the upgrade module should depend upon
* @return {?} an {\@link UpgradeAdapterRef}, which lets you register a `ready()` callback to
* run assertions once the Angular components are ready to test through AngularJS.
*/
registerForNg1Tests(modules) {
const /** @type {?} */ windowNgMock = ((window))['angular'].mock;
if (!windowNgMock || !windowNgMock.module) {
throw new Error('Failed to find \'angular.mock.module\'.');
}
this.declareNg1Module(modules);
windowNgMock.module(this.ng1Module.name);
const /** @type {?} */ upgrade = new UpgradeAdapterRef();
this.ng2BootstrapDeferred.promise.then((ng1Injector) => { ((upgrade))._bootstrapDone(this.moduleRef, ng1Injector); }, onError);
return upgrade;
}
/**
* Bootstrap a hybrid AngularJS / Angular application.
*
* This `bootstrap` method is a direct replacement (takes same arguments) for AngularJS
* [`bootstrap`](https://docs.angularjs.org/api/ng/function/angular.bootstrap) method. Unlike
* AngularJS, this bootstrap is asynchronous.
*
* ### Example
*
* ```
* const adapter = new UpgradeAdapter(MyNg2Module);
* const module = angular.module('myExample', []);
* module.directive('ng2', adapter.downgradeNg2Component(Ng2));
*
* module.directive('ng1', function() {
* return {
* scope: { title: '=' },
* template: 'ng1[Hello {{title}}!](<span ng-transclude></span>)'
* };
* });
*
*
* \@Component({
* selector: 'ng2',
* inputs: ['name'],
* template: 'ng2[<ng1 [title]="name">transclude</ng1>](<ng-content></ng-content>)'
* })
* class Ng2 {
* }
*
* \@NgModule({
* declarations: [Ng2, adapter.upgradeNg1Component('ng1')],
* imports: [BrowserModule]
* })
* class MyNg2Module {}
*
* document.body.innerHTML = '<ng2 name="World">project</ng2>';
*
* adapter.bootstrap(document.body, ['myExample']).ready(function() {
* expect(document.body.textContent).toEqual(
* "ng2[ng1[Hello World!](transclude)](project)");
* });
* ```
* @param {?} element
* @param {?=} modules
* @param {?=} config
* @return {?}
*/
bootstrap(element$$1, modules, config) {
this.declareNg1Module(modules);
const /** @type {?} */ upgrade = new UpgradeAdapterRef();
// Make sure resumeBootstrap() only exists if the current bootstrap is deferred
const /** @type {?} */ windowAngular = ((window) /** TODO #???? */)['angular'];
windowAngular.resumeBootstrap = undefined;
this.ngZone.run(() => { bootstrap(element$$1, [this.ng1Module.name], config); });
const /** @type {?} */ ng1BootstrapPromise = new Promise((resolve) => {
if (windowAngular.resumeBootstrap) {
const /** @type {?} */ originalResumeBootstrap = windowAngular.resumeBootstrap;
windowAngular.resumeBootstrap = function () {
windowAngular.resumeBootstrap = originalResumeBootstrap;
windowAngular.resumeBootstrap.apply(this, arguments);
resolve();
};
}
else {
resolve();
}
});
Promise.all([this.ng2BootstrapDeferred.promise, ng1BootstrapPromise]).then(([ng1Injector]) => {
element(element$$1).data(controllerKey(INJECTOR_KEY), this.moduleRef.injector);
this.moduleRef.injector.get(NgZone).run(() => { ((upgrade))._bootstrapDone(this.moduleRef, ng1Injector); });
}, onError);
return upgrade;
}
/**
* Allows AngularJS service to be accessible from Angular.
*
*
* ### Example
*
* ```
* class Login { ... }
* class Server { ... }
*
* \@Injectable()
* class Example {
* constructor(\@Inject('server') server, login: Login) {
* ...
* }
* }
*
* const module = angular.module('myExample', []);
* module.service('server', Server);
* module.service('login', Login);
*
* const adapter = new UpgradeAdapter(MyNg2Module);
* adapter.upgradeNg1Provider('server');
* adapter.upgradeNg1Provider('login', {asToken: Login});
*
* adapter.bootstrap(document.body, ['myExample']).ready((ref) => {
* const example: Example = ref.ng2Injector.get(Example);
* });
*
* ```
* @param {?} name
* @param {?=} options
* @return {?}
*/
upgradeNg1Provider(name, options) {
const /** @type {?} */ token = options && options.asToken || name;
this.upgradedProviders.push({
provide: token,
useFactory: ($injector) => $injector.get(name),
deps: [$INJECTOR]
});
}
/**
* Allows Angular service to be accessible from AngularJS.
*
*
* ### Example
*
* ```
* class Example {
* }
*
* const adapter = new UpgradeAdapter(MyNg2Module);
*
* const module = angular.module('myExample', []);
* module.factory('example', adapter.downgradeNg2Provider(Example));
*
* adapter.bootstrap(document.body, ['myExample']).ready((ref) => {
* const example: Example = ref.ng1Injector.get('example');
* });
*
* ```
* @param {?} token
* @return {?}
*/
downgradeNg2Provider(token) { return downgradeInjectable(token); }
/**
* Declare the AngularJS upgrade module for this adapter without bootstrapping the whole
* hybrid application.
*
* This method is automatically called by `bootstrap()` and `registerForNg1Tests()`.
*
* @param {?=} modules The AngularJS modules that this upgrade module should depend upon.
* @return {?} The AngularJS upgrade module that is declared by this method
*
* ### Example
*
* ```
* const upgradeAdapter = new UpgradeAdapter(MyNg2Module);
* upgradeAdapter.declareNg1Module(['heroApp']);
* ```
*/
declareNg1Module(modules = []) {
const /** @type {?} */ delayApplyExps = [];
let /** @type {?} */ original$applyFn;
let /** @type {?} */ rootScopePrototype;
let /** @type {?} */ rootScope;
const /** @type {?} */ upgradeAdapter = this;
const /** @type {?} */ ng1Module = this.ng1Module = module$1(this.idPrefix, modules);
const /** @type {?} */ platformRef = platformBrowserDynamic();
this.ngZone = new NgZone({ enableLongStackTrace: Zone.hasOwnProperty('longStackTraceZoneSpec') });
this.ng2BootstrapDeferred = new Deferred();
ng1Module.factory(INJECTOR_KEY, () => this.moduleRef.injector.get(Injector))
.constant(NG_ZONE_KEY, this.ngZone)
.factory(COMPILER_KEY, () => this.moduleRef.injector.get(Compiler))
.config([
'$provide', '$injector',
(provide, ng1Injector) => {
provide.decorator($ROOT_SCOPE, [
'$delegate',
function (rootScopeDelegate) {
// Capture the root apply so that we can delay first call to $apply until we
// bootstrap Angular and then we replay and restore the $apply.
rootScopePrototype = rootScopeDelegate.constructor.prototype;
if (rootScopePrototype.hasOwnProperty('$apply')) {
original$applyFn = rootScopePrototype.$apply;
rootScopePrototype.$apply = (exp) => delayApplyExps.push(exp);
}
else {
throw new Error('Failed to find \'$apply\' on \'$rootScope\'!');
}
return rootScope = rootScopeDelegate;
}
]);
if (ng1Injector.has($$TESTABILITY)) {
provide.decorator($$TESTABILITY, [
'$delegate',
function (testabilityDelegate) {
const /** @type {?} */ originalWhenStable = testabilityDelegate.whenStable;
// Cannot use arrow function below because we need the context
const /** @type {?} */ newWhenStable = function (callback) {
originalWhenStable.call(this, function () {
const /** @type {?} */ ng2Testability = upgradeAdapter.moduleRef.injector.get(Testability);
if (ng2Testability.isStable()) {
callback.apply(this, arguments);
}
else {
ng2Testability.whenStable(newWhenStable.bind(this, callback));
}
});
};
testabilityDelegate.whenStable = newWhenStable;
return testabilityDelegate;
}
]);
}
}
]);
ng1Module.run([
'$injector', '$rootScope',
(ng1Injector, rootScope) => {
UpgradeNg1ComponentAdapterBuilder.resolve(this.ng1ComponentsToBeUpgraded, ng1Injector)
.then(() => {
// At this point we have ng1 injector and we have lifted ng1 components into ng2, we
// now can bootstrap ng2.
const /** @type {?} */ DynamicNgUpgradeModule = NgModule({
providers: [
{ provide: $INJECTOR, useFactory: () => ng1Injector },
{ provide: $COMPILE, useFactory: () => ng1Injector.get($COMPILE) },
this.upgradedProviders
],
imports: [this.ng2AppModule],
entryComponents: this.downgradedComponents
}).Class({
constructor: function DynamicNgUpgradeModule() { },
ngDoBootstrap: function () { }
});
((platformRef))
._bootstrapModuleWithZone(DynamicNgUpgradeModule, this.compilerOptions, this.ngZone)
.then((ref) => {
this.moduleRef = ref;
this.ngZone.run(() => {
if (rootScopePrototype) {
rootScopePrototype.$apply = original$applyFn; // restore original $apply
while (delayApplyExps.length) {
rootScope.$apply(delayApplyExps.shift());
}
rootScopePrototype = null;
}
});
})
.then(() => this.ng2BootstrapDeferred.resolve(ng1Injector), onError)
.then(() => {
let /** @type {?} */ subscription = this.ngZone.onMicrotaskEmpty.subscribe({ next: () => rootScope.$digest() });
rootScope.$on('$destroy', () => { subscription.unsubscribe(); });
});
})
.catch((e) => this.ng2BootstrapDeferred.reject(e));
}
]);
return ng1Module;
}
}
/**
* Use `UpgradeAdapterRef` to control a hybrid AngularJS / Angular application.
*
* \@stable
*/
class UpgradeAdapterRef {
constructor() {
this._readyFn = null;
this.ng1RootScope = null;
this.ng1Injector = null;
this.ng2ModuleRef = null;
this.ng2Injector = null;
}
/**
* @param {?} ngModuleRef
* @param {?} ng1Injector
* @return {?}
*/
_bootstrapDone(ngModuleRef, ng1Injector) {
this.ng2ModuleRef = ngModuleRef;
this.ng2Injector = ngModuleRef.injector;
this.ng1Injector = ng1Injector;
this.ng1RootScope = ng1Injector.get($ROOT_SCOPE);
this._readyFn && this._readyFn(this);
}
/**
* Register a callback function which is notified upon successful hybrid AngularJS / Angular
* application has been bootstrapped.
*
* The `ready` callback function is invoked inside the Angular zone, therefore it does not
* require a call to `$apply()`.
* @param {?} fn
* @return {?}
*/
ready(fn) { this._readyFn = fn; }
/**
* Dispose of running hybrid AngularJS / Angular application.
* @return {?}
*/
dispose() {
this.ng1Injector.get($ROOT_SCOPE).$destroy();
this.ng2ModuleRef.destroy();
}
}
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* @module
* @description
* Entry point for all public APIs of the upgrade/dynamic package, allowing
* Angular 1 and Angular 2+ to run side by side in the same application.
*/
// This file only re-exports content of the `src` folder. Keep it that way.
/**
* Generated bundle index. Do not edit.
*/
export { VERSION, UpgradeAdapter, UpgradeAdapterRef };
//# sourceMappingURL=upgrade.js.map
|
var searchData=
[
['player',['player',['../classplayer.html#a4c43d838817775e2a2b0241d30de4abc',1,'player']]]
];
|
/* dtpicker javascript jQuery */
(function($) {
// 严格模式
'use strict';
// 控件类名
var pluginName = 'dtpicker';
var PluginClass=T.UI.Controls.DTPicker;
var pluginRef = 't-plugin-ref';
// 胶水代码
$.fn[pluginName] = function(options) {
if(typeof options === 'string'){
// 2. 调用API
var plugin = this.data(pluginRef);
if(!plugin || !plugin[options]){
throw '方法 ' + options + ' 不存在';
}
var result = plugin[options].apply(plugin, Array.prototype.slice.call(arguments, 1));
if(options === 'destroy'){
jqElement.removeData(pluginRef);
}
return result;
}
this.each(function () {
var jqElement=$(this);
var plugin = jqElement.data(pluginRef);
if(plugin === undefined){
// 1. 创建新对象
plugin=new PluginClass(this, $.extend(true, {}, options));
jqElement.data(pluginRef, plugin);
}
else{
// 3. 更新选项
plugin.updateOptions || plugin.updateOptions(options);
}
});
return this;
};
})(jQuery);
// (function($) {
// // 'use strict';
// var dateTimePicker = function (element, options) {
// /********************************************************************************
// *
// * Public API functions
// * =====================
// *
// * Important: Do not expose direct references to private objects or the options
// * object to the outer world. Always return a clone when returning values or make
// * a clone when setting a private variable.
// *
// ********************************************************************************/
// picker.toggle = toggle;
// picker.show = show;
// picker.hide = hide;
// picker.ignoreReadonly = function (ignoreReadonly) {
// if (arguments.length === 0) {
// return options.ignoreReadonly;
// }
// if (typeof ignoreReadonly !== 'boolean') {
// throw new TypeError('ignoreReadonly () expects a boolean parameter');
// }
// options.ignoreReadonly = ignoreReadonly;
// return picker;
// };
// picker.options = function (newOptions) {
// if (arguments.length === 0) {
// return $.extend(true, {}, options);
// }
// if (!(newOptions instanceof Object)) {
// throw new TypeError('options() options parameter should be an object');
// }
// $.extend(true, options, newOptions);
// $.each(options, function (key, value) {
// if (picker[key] !== undefined) {
// picker[key](value);
// } else {
// throw new TypeError('option ' + key + ' is not recognized!');
// }
// });
// return picker;
// };
// picker.date = function (newDate) {
// ///<signature helpKeyword="$.fn.datetimepicker.date">
// ///<summary>Returns the component's model current date, a moment object or null if not set.</summary>
// ///<returns type="Moment">date.clone()</returns>
// ///</signature>
// ///<signature>
// ///<summary>Sets the components model current moment to it. Passing a null value unsets the components model current moment. Parsing of the newDate parameter is made using moment library with the options.format and options.useStrict components configuration.</summary>
// ///<param name="newDate" locid="$.fn.datetimepicker.date_p:newDate">Takes string, Date, moment, null parameter.</param>
// ///</signature>
// if (arguments.length === 0) {
// if (unset) {
// return null;
// }
// return date.clone();
// }
// if (newDate !== null && typeof newDate !== 'string' && !moment.isMoment(newDate) && !(newDate instanceof Date)) {
// throw new TypeError('date() parameter must be one of [null, string, moment or Date]');
// }
// setValue(newDate === null ? null : parseInputDate(newDate));
// return picker;
// };
// picker.format = function (newFormat) {
// ///<summary>test su</summary>
// ///<param name="newFormat">info about para</param>
// ///<returns type="string|boolean">returns foo</returns>
// if (arguments.length === 0) {
// return options.format;
// }
// if ((typeof newFormat !== 'string') && ((typeof newFormat !== 'boolean') || (newFormat !== false))) {
// throw new TypeError('format() expects a sting or boolean:false parameter ' + newFormat);
// }
// options.format = newFormat;
// if (actualFormat) {
// initFormatting(); // reinit formatting
// }
// return picker;
// };
// picker.timeZone = function (newZone) {
// if (arguments.length === 0) {
// return options.timeZone;
// }
// options.timeZone = newZone;
// return picker;
// };
// picker.dayViewHeaderFormat = function (newFormat) {
// if (arguments.length === 0) {
// return options.dayViewHeaderFormat;
// }
// if (typeof newFormat !== 'string') {
// throw new TypeError('dayViewHeaderFormat() expects a string parameter');
// }
// options.dayViewHeaderFormat = newFormat;
// return picker;
// };
// picker.extraFormats = function (formats) {
// if (arguments.length === 0) {
// return options.extraFormats;
// }
// if (formats !== false && !(formats instanceof Array)) {
// throw new TypeError('extraFormats() expects an array or false parameter');
// }
// options.extraFormats = formats;
// if (parseFormats) {
// initFormatting(); // reinit formatting
// }
// return picker;
// };
// picker.disabledDates = function (dates) {
// ///<signature helpKeyword="$.fn.datetimepicker.disabledDates">
// ///<summary>Returns an array with the currently set disabled dates on the component.</summary>
// ///<returns type="array">options.disabledDates</returns>
// ///</signature>
// ///<signature>
// ///<summary>Setting this takes precedence over options.minDate, options.maxDate configuration. Also calling this function removes the configuration of
// ///options.enabledDates if such exist.</summary>
// ///<param name="dates" locid="$.fn.datetimepicker.disabledDates_p:dates">Takes an [ string or Date or moment ] of values and allows the user to select only from those days.</param>
// ///</signature>
// if (arguments.length === 0) {
// return (options.disabledDates ? $.extend({}, options.disabledDates) : options.disabledDates);
// }
// if (!dates) {
// options.disabledDates = false;
// update();
// return picker;
// }
// if (!(dates instanceof Array)) {
// throw new TypeError('disabledDates() expects an array parameter');
// }
// options.disabledDates = indexGivenDates(dates);
// options.enabledDates = false;
// update();
// return picker;
// };
// picker.enabledDates = function (dates) {
// ///<signature helpKeyword="$.fn.datetimepicker.enabledDates">
// ///<summary>Returns an array with the currently set enabled dates on the component.</summary>
// ///<returns type="array">options.enabledDates</returns>
// ///</signature>
// ///<signature>
// ///<summary>Setting this takes precedence over options.minDate, options.maxDate configuration. Also calling this function removes the configuration of options.disabledDates if such exist.</summary>
// ///<param name="dates" locid="$.fn.datetimepicker.enabledDates_p:dates">Takes an [ string or Date or moment ] of values and allows the user to select only from those days.</param>
// ///</signature>
// if (arguments.length === 0) {
// return (options.enabledDates ? $.extend({}, options.enabledDates) : options.enabledDates);
// }
// if (!dates) {
// options.enabledDates = false;
// update();
// return picker;
// }
// if (!(dates instanceof Array)) {
// throw new TypeError('enabledDates() expects an array parameter');
// }
// options.enabledDates = indexGivenDates(dates);
// options.disabledDates = false;
// update();
// return picker;
// };
// picker.daysOfWeekDisabled = function (daysOfWeekDisabled) {
// if (arguments.length === 0) {
// return options.daysOfWeekDisabled.splice(0);
// }
// if ((typeof daysOfWeekDisabled === 'boolean') && !daysOfWeekDisabled) {
// options.daysOfWeekDisabled = false;
// update();
// return picker;
// }
// if (!(daysOfWeekDisabled instanceof Array)) {
// throw new TypeError('daysOfWeekDisabled() expects an array parameter');
// }
// options.daysOfWeekDisabled = daysOfWeekDisabled.reduce(function (previousValue, currentValue) {
// currentValue = parseInt(currentValue, 10);
// if (currentValue > 6 || currentValue < 0 || isNaN(currentValue)) {
// return previousValue;
// }
// if (previousValue.indexOf(currentValue) === -1) {
// previousValue.push(currentValue);
// }
// return previousValue;
// }, []).sort();
// if (options.useCurrent && !options.keepInvalid) {
// var tries = 0;
// while (!isValid(date, 'd')) {
// date.add(1, 'd');
// if (tries === 7) {
// throw 'Tried 7 times to find a valid date';
// }
// tries++;
// }
// setValue(date);
// }
// update();
// return picker;
// };
// picker.maxDate = function (maxDate) {
// if (arguments.length === 0) {
// return options.maxDate ? options.maxDate.clone() : options.maxDate;
// }
// if ((typeof maxDate === 'boolean') && maxDate === false) {
// options.maxDate = false;
// update();
// return picker;
// }
// if (typeof maxDate === 'string') {
// if (maxDate === 'now' || maxDate === 'moment') {
// maxDate = getMoment();
// }
// }
// var parsedDate = parseInputDate(maxDate);
// if (!parsedDate.isValid()) {
// throw new TypeError('maxDate() Could not parse date parameter: ' + maxDate);
// }
// if (options.minDate && parsedDate.isBefore(options.minDate)) {
// throw new TypeError('maxDate() date parameter is before options.minDate: ' + parsedDate.format(actualFormat));
// }
// options.maxDate = parsedDate;
// if (options.useCurrent && !options.keepInvalid && date.isAfter(maxDate)) {
// setValue(options.maxDate);
// }
// if (viewDate.isAfter(parsedDate)) {
// viewDate = parsedDate.clone().subtract(options.stepping, 'm');
// }
// update();
// return picker;
// };
// picker.minDate = function (minDate) {
// if (arguments.length === 0) {
// return options.minDate ? options.minDate.clone() : options.minDate;
// }
// if ((typeof minDate === 'boolean') && minDate === false) {
// options.minDate = false;
// update();
// return picker;
// }
// if (typeof minDate === 'string') {
// if (minDate === 'now' || minDate === 'moment') {
// minDate = getMoment();
// }
// }
// var parsedDate = parseInputDate(minDate);
// if (!parsedDate.isValid()) {
// throw new TypeError('minDate() Could not parse date parameter: ' + minDate);
// }
// if (options.maxDate && parsedDate.isAfter(options.maxDate)) {
// throw new TypeError('minDate() date parameter is after options.maxDate: ' + parsedDate.format(actualFormat));
// }
// options.minDate = parsedDate;
// if (options.useCurrent && !options.keepInvalid && date.isBefore(minDate)) {
// setValue(options.minDate);
// }
// if (viewDate.isBefore(parsedDate)) {
// viewDate = parsedDate.clone().add(options.stepping, 'm');
// }
// update();
// return picker;
// };
// picker.defaultDate = function (defaultDate) {
// ///<signature helpKeyword="$.fn.datetimepicker.defaultDate">
// ///<summary>Returns a moment with the options.defaultDate option configuration or false if not set</summary>
// ///<returns type="Moment">date.clone()</returns>
// ///</signature>
// ///<signature>
// ///<summary>Will set the picker's inital date. If a boolean:false value is passed the options.defaultDate parameter is cleared.</summary>
// ///<param name="defaultDate" locid="$.fn.datetimepicker.defaultDate_p:defaultDate">Takes a string, Date, moment, boolean:false</param>
// ///</signature>
// if (arguments.length === 0) {
// return options.defaultDate ? options.defaultDate.clone() : options.defaultDate;
// }
// if (!defaultDate) {
// options.defaultDate = false;
// return picker;
// }
// if (typeof defaultDate === 'string') {
// if (defaultDate === 'now' || defaultDate === 'moment') {
// defaultDate = getMoment();
// }
// }
// var parsedDate = parseInputDate(defaultDate);
// if (!parsedDate.isValid()) {
// throw new TypeError('defaultDate() Could not parse date parameter: ' + defaultDate);
// }
// if (!isValid(parsedDate)) {
// throw new TypeError('defaultDate() date passed is invalid according to component setup validations');
// }
// options.defaultDate = parsedDate;
// if ((options.defaultDate && options.inline) || input.val().trim() === '') {
// setValue(options.defaultDate);
// }
// return picker;
// };
// picker.locale = function (locale) {
// if (arguments.length === 0) {
// return options.locale;
// }
// if (!moment.localeData(locale)) {
// throw new TypeError('locale() locale ' + locale + ' is not loaded from moment locales!');
// }
// options.locale = locale;
// date.locale(options.locale);
// viewDate.locale(options.locale);
// if (actualFormat) {
// initFormatting(); // reinit formatting
// }
// if (widget) {
// hide();
// show();
// }
// return picker;
// };
// picker.stepping = function (stepping) {
// if (arguments.length === 0) {
// return options.stepping;
// }
// stepping = parseInt(stepping, 10);
// if (isNaN(stepping) || stepping < 1) {
// stepping = 1;
// }
// options.stepping = stepping;
// return picker;
// };
// picker.useCurrent = function (useCurrent) {
// var useCurrentOptions = ['year', 'month', 'day', 'hour', 'minute'];
// if (arguments.length === 0) {
// return options.useCurrent;
// }
// if ((typeof useCurrent !== 'boolean') && (typeof useCurrent !== 'string')) {
// throw new TypeError('useCurrent() expects a boolean or string parameter');
// }
// if (typeof useCurrent === 'string' && useCurrentOptions.indexOf(useCurrent.toLowerCase()) === -1) {
// throw new TypeError('useCurrent() expects a string parameter of ' + useCurrentOptions.join(', '));
// }
// options.useCurrent = useCurrent;
// return picker;
// };
// picker.collapse = function (collapse) {
// if (arguments.length === 0) {
// return options.collapse;
// }
// if (typeof collapse !== 'boolean') {
// throw new TypeError('collapse() expects a boolean parameter');
// }
// if (options.collapse === collapse) {
// return picker;
// }
// options.collapse = collapse;
// if (widget) {
// hide();
// show();
// }
// return picker;
// };
// picker.icons = function (icons) {
// if (arguments.length === 0) {
// return $.extend({}, options.icons);
// }
// if (!(icons instanceof Object)) {
// throw new TypeError('icons() expects parameter to be an Object');
// }
// $.extend(options.icons, icons);
// if (widget) {
// hide();
// show();
// }
// return picker;
// };
// picker.tooltips = function (tooltips) {
// if (arguments.length === 0) {
// return $.extend({}, options.tooltips);
// }
// if (!(tooltips instanceof Object)) {
// throw new TypeError('tooltips() expects parameter to be an Object');
// }
// $.extend(options.tooltips, tooltips);
// if (widget) {
// hide();
// show();
// }
// return picker;
// };
// picker.useStrict = function (useStrict) {
// if (arguments.length === 0) {
// return options.useStrict;
// }
// if (typeof useStrict !== 'boolean') {
// throw new TypeError('useStrict() expects a boolean parameter');
// }
// options.useStrict = useStrict;
// return picker;
// };
// picker.sideBySide = function (sideBySide) {
// if (arguments.length === 0) {
// return options.sideBySide;
// }
// if (typeof sideBySide !== 'boolean') {
// throw new TypeError('sideBySide() expects a boolean parameter');
// }
// options.sideBySide = sideBySide;
// if (widget) {
// hide();
// show();
// }
// return picker;
// };
// picker.viewMode = function (viewMode) {
// if (arguments.length === 0) {
// return options.viewMode;
// }
// if (typeof viewMode !== 'string') {
// throw new TypeError('viewMode() expects a string parameter');
// }
// if (viewModes.indexOf(viewMode) === -1) {
// throw new TypeError('viewMode() parameter must be one of (' + viewModes.join(', ') + ') value');
// }
// options.viewMode = viewMode;
// currentViewMode = Math.max(viewModes.indexOf(viewMode), minViewModeNumber);
// showMode();
// return picker;
// };
// picker.toolbarPlacement = function (toolbarPlacement) {
// if (arguments.length === 0) {
// return options.toolbarPlacement;
// }
// if (typeof toolbarPlacement !== 'string') {
// throw new TypeError('toolbarPlacement() expects a string parameter');
// }
// if (toolbarPlacements.indexOf(toolbarPlacement) === -1) {
// throw new TypeError('toolbarPlacement() parameter must be one of (' + toolbarPlacements.join(', ') + ') value');
// }
// options.toolbarPlacement = toolbarPlacement;
// if (widget) {
// hide();
// show();
// }
// return picker;
// };
// picker.widgetPositioning = function (widgetPositioning) {
// if (arguments.length === 0) {
// return $.extend({}, options.widgetPositioning);
// }
// if (({}).toString.call(widgetPositioning) !== '[object Object]') {
// throw new TypeError('widgetPositioning() expects an object variable');
// }
// if (widgetPositioning.horizontal) {
// if (typeof widgetPositioning.horizontal !== 'string') {
// throw new TypeError('widgetPositioning() horizontal variable must be a string');
// }
// widgetPositioning.horizontal = widgetPositioning.horizontal.toLowerCase();
// if (horizontalModes.indexOf(widgetPositioning.horizontal) === -1) {
// throw new TypeError('widgetPositioning() expects horizontal parameter to be one of (' + horizontalModes.join(', ') + ')');
// }
// options.widgetPositioning.horizontal = widgetPositioning.horizontal;
// }
// if (widgetPositioning.vertical) {
// if (typeof widgetPositioning.vertical !== 'string') {
// throw new TypeError('widgetPositioning() vertical variable must be a string');
// }
// widgetPositioning.vertical = widgetPositioning.vertical.toLowerCase();
// if (verticalModes.indexOf(widgetPositioning.vertical) === -1) {
// throw new TypeError('widgetPositioning() expects vertical parameter to be one of (' + verticalModes.join(', ') + ')');
// }
// options.widgetPositioning.vertical = widgetPositioning.vertical;
// }
// update();
// return picker;
// };
// picker.calendarWeeks = function (calendarWeeks) {
// if (arguments.length === 0) {
// return options.calendarWeeks;
// }
// if (typeof calendarWeeks !== 'boolean') {
// throw new TypeError('calendarWeeks() expects parameter to be a boolean value');
// }
// options.calendarWeeks = calendarWeeks;
// update();
// return picker;
// };
// picker.showTodayButton = function (showTodayButton) {
// if (arguments.length === 0) {
// return options.showTodayButton;
// }
// if (typeof showTodayButton !== 'boolean') {
// throw new TypeError('showTodayButton() expects a boolean parameter');
// }
// options.showTodayButton = showTodayButton;
// if (widget) {
// hide();
// show();
// }
// return picker;
// };
// picker.showClear = function (showClear) {
// if (arguments.length === 0) {
// return options.showClear;
// }
// if (typeof showClear !== 'boolean') {
// throw new TypeError('showClear() expects a boolean parameter');
// }
// options.showClear = showClear;
// if (widget) {
// hide();
// show();
// }
// return picker;
// };
// picker.widgetParent = function (widgetParent) {
// if (arguments.length === 0) {
// return options.widgetParent;
// }
// if (typeof widgetParent === 'string') {
// widgetParent = $(widgetParent);
// }
// if (widgetParent !== null && (typeof widgetParent !== 'string' && !(widgetParent instanceof $))) {
// throw new TypeError('widgetParent() expects a string or a jQuery object parameter');
// }
// options.widgetParent = widgetParent;
// if (widget) {
// hide();
// show();
// }
// return picker;
// };
// picker.keepOpen = function (keepOpen) {
// if (arguments.length === 0) {
// return options.keepOpen;
// }
// if (typeof keepOpen !== 'boolean') {
// throw new TypeError('keepOpen() expects a boolean parameter');
// }
// options.keepOpen = keepOpen;
// return picker;
// };
// picker.focusOnShow = function (focusOnShow) {
// if (arguments.length === 0) {
// return options.focusOnShow;
// }
// if (typeof focusOnShow !== 'boolean') {
// throw new TypeError('focusOnShow() expects a boolean parameter');
// }
// options.focusOnShow = focusOnShow;
// return picker;
// };
// picker.inline = function (inline) {
// if (arguments.length === 0) {
// return options.inline;
// }
// if (typeof inline !== 'boolean') {
// throw new TypeError('inline() expects a boolean parameter');
// }
// options.inline = inline;
// return picker;
// };
// picker.clear = function () {
// clear();
// return picker;
// };
// picker.keyBinds = function (keyBinds) {
// options.keyBinds = keyBinds;
// return picker;
// };
// picker.getMoment = function (d) {
// return this.getMoment(d);
// };
// picker.debug = function (debug) {
// if (typeof debug !== 'boolean') {
// throw new TypeError('debug() expects a boolean parameter');
// }
// options.debug = debug;
// return picker;
// };
// picker.allowInputToggle = function (allowInputToggle) {
// if (arguments.length === 0) {
// return options.allowInputToggle;
// }
// if (typeof allowInputToggle !== 'boolean') {
// throw new TypeError('allowInputToggle() expects a boolean parameter');
// }
// options.allowInputToggle = allowInputToggle;
// return picker;
// };
// picker.showClose = function (showClose) {
// if (arguments.length === 0) {
// return options.showClose;
// }
// if (typeof showClose !== 'boolean') {
// throw new TypeError('showClose() expects a boolean parameter');
// }
// options.showClose = showClose;
// return picker;
// };
// picker.keepInvalid = function (keepInvalid) {
// if (arguments.length === 0) {
// return options.keepInvalid;
// }
// if (typeof keepInvalid !== 'boolean') {
// throw new TypeError('keepInvalid() expects a boolean parameter');
// }
// options.keepInvalid = keepInvalid;
// return picker;
// };
// picker.datepickerInput = function (datepickerInput) {
// if (arguments.length === 0) {
// return options.datepickerInput;
// }
// if (typeof datepickerInput !== 'string') {
// throw new TypeError('datepickerInput() expects a string parameter');
// }
// options.datepickerInput = datepickerInput;
// return picker;
// };
// picker.parseInputDate = function (parseInputDate) {
// if (arguments.length === 0) {
// return options.parseInputDate;
// }
// if (typeof parseInputDate !== 'function') {
// throw new TypeError('parseInputDate() sholud be as function');
// }
// options.parseInputDate = parseInputDate;
// return picker;
// };
// picker.disabledTimeIntervals = function (disabledTimeIntervals) {
// ///<signature helpKeyword="$.fn.datetimepicker.disabledTimeIntervals">
// ///<summary>Returns an array with the currently set disabled dates on the component.</summary>
// ///<returns type="array">options.disabledTimeIntervals</returns>
// ///</signature>
// ///<signature>
// ///<summary>Setting this takes precedence over options.minDate, options.maxDate configuration. Also calling this function removes the configuration of
// ///options.enabledDates if such exist.</summary>
// ///<param name="dates" locid="$.fn.datetimepicker.disabledTimeIntervals_p:dates">Takes an [ string or Date or moment ] of values and allows the user to select only from those days.</param>
// ///</signature>
// if (arguments.length === 0) {
// return (options.disabledTimeIntervals ? $.extend({}, options.disabledTimeIntervals) : options.disabledTimeIntervals);
// }
// if (!disabledTimeIntervals) {
// options.disabledTimeIntervals = false;
// update();
// return picker;
// }
// if (!(disabledTimeIntervals instanceof Array)) {
// throw new TypeError('disabledTimeIntervals() expects an array parameter');
// }
// options.disabledTimeIntervals = disabledTimeIntervals;
// update();
// return picker;
// };
// picker.disabledHours = function (hours) {
// ///<signature helpKeyword="$.fn.datetimepicker.disabledHours">
// ///<summary>Returns an array with the currently set disabled hours on the component.</summary>
// ///<returns type="array">options.disabledHours</returns>
// ///</signature>
// ///<signature>
// ///<summary>Setting this takes precedence over options.minDate, options.maxDate configuration. Also calling this function removes the configuration of
// ///options.enabledHours if such exist.</summary>
// ///<param name="hours" locid="$.fn.datetimepicker.disabledHours_p:hours">Takes an [ int ] of values and disallows the user to select only from those hours.</param>
// ///</signature>
// if (arguments.length === 0) {
// return (options.disabledHours ? $.extend({}, options.disabledHours) : options.disabledHours);
// }
// if (!hours) {
// options.disabledHours = false;
// update();
// return picker;
// }
// if (!(hours instanceof Array)) {
// throw new TypeError('disabledHours() expects an array parameter');
// }
// options.disabledHours = indexGivenHours(hours);
// options.enabledHours = false;
// if (options.useCurrent && !options.keepInvalid) {
// var tries = 0;
// while (!isValid(date, 'h')) {
// date.add(1, 'h');
// if (tries === 24) {
// throw 'Tried 24 times to find a valid date';
// }
// tries++;
// }
// setValue(date);
// }
// update();
// return picker;
// };
// picker.enabledHours = function (hours) {
// ///<signature helpKeyword="$.fn.datetimepicker.enabledHours">
// ///<summary>Returns an array with the currently set enabled hours on the component.</summary>
// ///<returns type="array">options.enabledHours</returns>
// ///</signature>
// ///<signature>
// ///<summary>Setting this takes precedence over options.minDate, options.maxDate configuration. Also calling this function removes the configuration of options.disabledHours if such exist.</summary>
// ///<param name="hours" locid="$.fn.datetimepicker.enabledHours_p:hours">Takes an [ int ] of values and allows the user to select only from those hours.</param>
// ///</signature>
// if (arguments.length === 0) {
// return (options.enabledHours ? $.extend({}, options.enabledHours) : options.enabledHours);
// }
// if (!hours) {
// options.enabledHours = false;
// update();
// return picker;
// }
// if (!(hours instanceof Array)) {
// throw new TypeError('enabledHours() expects an array parameter');
// }
// options.enabledHours = indexGivenHours(hours);
// options.disabledHours = false;
// if (options.useCurrent && !options.keepInvalid) {
// var tries = 0;
// while (!isValid(date, 'h')) {
// date.add(1, 'h');
// if (tries === 24) {
// throw 'Tried 24 times to find a valid date';
// }
// tries++;
// }
// setValue(date);
// }
// update();
// return picker;
// };
// picker.viewDate = function (newDate) {
// ///<signature helpKeyword="$.fn.datetimepicker.viewDate">
// ///<summary>Returns the component's model current viewDate, a moment object or null if not set.</summary>
// ///<returns type="Moment">viewDate.clone()</returns>
// ///</signature>
// ///<signature>
// ///<summary>Sets the components model current moment to it. Passing a null value unsets the components model current moment. Parsing of the newDate parameter is made using moment library with the options.format and options.useStrict components configuration.</summary>
// ///<param name="newDate" locid="$.fn.datetimepicker.date_p:newDate">Takes string, viewDate, moment, null parameter.</param>
// ///</signature>
// if (arguments.length === 0) {
// return viewDate.clone();
// }
// if (!newDate) {
// viewDate = date.clone();
// return picker;
// }
// if (typeof newDate !== 'string' && !moment.isMoment(newDate) && !(newDate instanceof Date)) {
// throw new TypeError('viewDate() parameter must be one of [string, moment or Date]');
// }
// viewDate = parseInputDate(newDate);
// viewUpdate();
// return picker;
// };
// };
// })(jQuery); |
const assert = require('assert');
const md5 = require('blueimp-md5');
const createApp = require('../../lib');
describe('tokenize service', () => {
it('tokenizes and stems', () => {
const app = createApp();
const text = `what's the weather in vancouver`;
const hash = md5(text);
return app.service('tokenize').create({ text }).then(data => {
assert.equal(data._id, hash, 'id is MD5 hash of the string');
assert.deepEqual(data, {
_id: '873dd3d48eed1d576a4d5b1dcacd2348',
text: 'what\'s the weather in vancouver',
tokens: [ 'what', 's', 'the', 'weather', 'in', 'vancouver' ],
stems: [ 'what', 's', 'the', 'weather', 'in', 'vancouv' ]
});
});
});
});
|
'use strict';
var getTemplatedStylesheet = require('./templatedStylesheet'),
path = require('path');
module.exports = getTemplatedStylesheet(path.join(__dirname, '/templates/stylus.tpl'));
|
import React from 'react'
import Icon from 'react-icon-base'
const MdTonality = props => (
<Icon viewBox="0 0 40 40" {...props}>
<g><path d="m32.9 23.4c0.1-0.6 0.2-1.2 0.3-1.8h-11.6v1.8h11.3z m-2.5 5c0.4-0.6 0.9-1.2 1.2-1.8h-10v1.8h8.8z m-8.8 4.8c1.8-0.2 3.4-0.8 4.9-1.6h-4.9v1.6z m0-16.6v1.8h11.6c-0.1-0.6-0.2-1.2-0.3-1.8h-11.3z m0-5v1.8h10c-0.4-0.6-0.8-1.2-1.2-1.8h-8.8z m0-4.8v1.6h4.9c-1.5-0.8-3.1-1.4-4.9-1.6z m-3.2 26.4v-26.4c-6.6 0.8-11.8 6.4-11.8 13.2s5.2 12.4 11.8 13.2z m1.6-29.8c9.2 0 16.6 7.4 16.6 16.6s-7.4 16.6-16.6 16.6-16.6-7.4-16.6-16.6 7.4-16.6 16.6-16.6z"/></g>
</Icon>
)
export default MdTonality
|
'use strict'
const dotenv = require('dotenv')
const ENV = process.env.NODE_ENV || 'development'
if (ENV === 'development') dotenv.load()
const config = {
ENV: process.env.NODE_ENV,
PORT: process.env.PORT,
PROXY_URI: process.env.PROXY_URI,
WEBHOOK_URL: process.env.WEBHOOK_URL,
BATTLESHIP_COMMAND_TOKEN: process.env.BATTLESHIP_COMMAND_TOKEN,
SLACK_TOKEN: process.env.SLACK_TOKEN,
ICON_EMOJI: ':passenger_ship:',
USERNAME: "Battleship"
}
module.exports = (key) => {
if (!key) return config
return config[key]
}
|
'use strict';var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") return Reflect.decorate(decorators, target, key, desc);
switch (arguments.length) {
case 2: return decorators.reduceRight(function(o, d) { return (d && d(o)) || o; }, target);
case 3: return decorators.reduceRight(function(o, d) { return (d && d(target, key)), void 0; }, void 0);
case 4: return decorators.reduceRight(function(o, d) { return (d && d(target, key, o)) || o; }, desc);
}
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var collection_1 = require('angular2/src/facade/collection');
var lang_1 = require('angular2/src/facade/lang');
var exceptions_1 = require('angular2/src/facade/exceptions');
var DefaultKeyValueDifferFactory = (function () {
function DefaultKeyValueDifferFactory() {
}
DefaultKeyValueDifferFactory.prototype.supports = function (obj) { return obj instanceof Map || lang_1.isJsObject(obj); };
DefaultKeyValueDifferFactory.prototype.create = function (cdRef) { return new DefaultKeyValueDiffer(); };
DefaultKeyValueDifferFactory = __decorate([
lang_1.CONST(),
__metadata('design:paramtypes', [])
], DefaultKeyValueDifferFactory);
return DefaultKeyValueDifferFactory;
})();
exports.DefaultKeyValueDifferFactory = DefaultKeyValueDifferFactory;
var DefaultKeyValueDiffer = (function () {
function DefaultKeyValueDiffer() {
this._records = new Map();
this._mapHead = null;
this._previousMapHead = null;
this._changesHead = null;
this._changesTail = null;
this._additionsHead = null;
this._additionsTail = null;
this._removalsHead = null;
this._removalsTail = null;
}
Object.defineProperty(DefaultKeyValueDiffer.prototype, "isDirty", {
get: function () {
return this._additionsHead !== null || this._changesHead !== null ||
this._removalsHead !== null;
},
enumerable: true,
configurable: true
});
DefaultKeyValueDiffer.prototype.forEachItem = function (fn) {
var record;
for (record = this._mapHead; record !== null; record = record._next) {
fn(record);
}
};
DefaultKeyValueDiffer.prototype.forEachPreviousItem = function (fn) {
var record;
for (record = this._previousMapHead; record !== null; record = record._nextPrevious) {
fn(record);
}
};
DefaultKeyValueDiffer.prototype.forEachChangedItem = function (fn) {
var record;
for (record = this._changesHead; record !== null; record = record._nextChanged) {
fn(record);
}
};
DefaultKeyValueDiffer.prototype.forEachAddedItem = function (fn) {
var record;
for (record = this._additionsHead; record !== null; record = record._nextAdded) {
fn(record);
}
};
DefaultKeyValueDiffer.prototype.forEachRemovedItem = function (fn) {
var record;
for (record = this._removalsHead; record !== null; record = record._nextRemoved) {
fn(record);
}
};
DefaultKeyValueDiffer.prototype.diff = function (map) {
if (lang_1.isBlank(map))
map = collection_1.MapWrapper.createFromPairs([]);
if (!(map instanceof Map || lang_1.isJsObject(map))) {
throw new exceptions_1.BaseException("Error trying to diff '" + map + "'");
}
if (this.check(map)) {
return this;
}
else {
return null;
}
};
DefaultKeyValueDiffer.prototype.onDestroy = function () { };
DefaultKeyValueDiffer.prototype.check = function (map) {
var _this = this;
this._reset();
var records = this._records;
var oldSeqRecord = this._mapHead;
var lastOldSeqRecord = null;
var lastNewSeqRecord = null;
var seqChanged = false;
this._forEach(map, function (value, key) {
var newSeqRecord;
if (oldSeqRecord !== null && key === oldSeqRecord.key) {
newSeqRecord = oldSeqRecord;
if (!lang_1.looseIdentical(value, oldSeqRecord.currentValue)) {
oldSeqRecord.previousValue = oldSeqRecord.currentValue;
oldSeqRecord.currentValue = value;
_this._addToChanges(oldSeqRecord);
}
}
else {
seqChanged = true;
if (oldSeqRecord !== null) {
oldSeqRecord._next = null;
_this._removeFromSeq(lastOldSeqRecord, oldSeqRecord);
_this._addToRemovals(oldSeqRecord);
}
if (records.has(key)) {
newSeqRecord = records.get(key);
}
else {
newSeqRecord = new KVChangeRecord(key);
records.set(key, newSeqRecord);
newSeqRecord.currentValue = value;
_this._addToAdditions(newSeqRecord);
}
}
if (seqChanged) {
if (_this._isInRemovals(newSeqRecord)) {
_this._removeFromRemovals(newSeqRecord);
}
if (lastNewSeqRecord == null) {
_this._mapHead = newSeqRecord;
}
else {
lastNewSeqRecord._next = newSeqRecord;
}
}
lastOldSeqRecord = oldSeqRecord;
lastNewSeqRecord = newSeqRecord;
oldSeqRecord = oldSeqRecord === null ? null : oldSeqRecord._next;
});
this._truncate(lastOldSeqRecord, oldSeqRecord);
return this.isDirty;
};
/** @internal */
DefaultKeyValueDiffer.prototype._reset = function () {
if (this.isDirty) {
var record;
// Record the state of the mapping
for (record = this._previousMapHead = this._mapHead; record !== null; record = record._next) {
record._nextPrevious = record._next;
}
for (record = this._changesHead; record !== null; record = record._nextChanged) {
record.previousValue = record.currentValue;
}
for (record = this._additionsHead; record != null; record = record._nextAdded) {
record.previousValue = record.currentValue;
}
// todo(vicb) once assert is supported
// assert(() {
// var r = _changesHead;
// while (r != null) {
// var nextRecord = r._nextChanged;
// r._nextChanged = null;
// r = nextRecord;
// }
//
// r = _additionsHead;
// while (r != null) {
// var nextRecord = r._nextAdded;
// r._nextAdded = null;
// r = nextRecord;
// }
//
// r = _removalsHead;
// while (r != null) {
// var nextRecord = r._nextRemoved;
// r._nextRemoved = null;
// r = nextRecord;
// }
//
// return true;
//});
this._changesHead = this._changesTail = null;
this._additionsHead = this._additionsTail = null;
this._removalsHead = this._removalsTail = null;
}
};
/** @internal */
DefaultKeyValueDiffer.prototype._truncate = function (lastRecord, record) {
while (record !== null) {
if (lastRecord === null) {
this._mapHead = null;
}
else {
lastRecord._next = null;
}
var nextRecord = record._next;
// todo(vicb) assert
// assert((() {
// record._next = null;
// return true;
//}));
this._addToRemovals(record);
lastRecord = record;
record = nextRecord;
}
for (var rec = this._removalsHead; rec !== null; rec = rec._nextRemoved) {
rec.previousValue = rec.currentValue;
rec.currentValue = null;
this._records.delete(rec.key);
}
};
/** @internal */
DefaultKeyValueDiffer.prototype._isInRemovals = function (record) {
return record === this._removalsHead || record._nextRemoved !== null ||
record._prevRemoved !== null;
};
/** @internal */
DefaultKeyValueDiffer.prototype._addToRemovals = function (record) {
// todo(vicb) assert
// assert(record._next == null);
// assert(record._nextAdded == null);
// assert(record._nextChanged == null);
// assert(record._nextRemoved == null);
// assert(record._prevRemoved == null);
if (this._removalsHead === null) {
this._removalsHead = this._removalsTail = record;
}
else {
this._removalsTail._nextRemoved = record;
record._prevRemoved = this._removalsTail;
this._removalsTail = record;
}
};
/** @internal */
DefaultKeyValueDiffer.prototype._removeFromSeq = function (prev, record) {
var next = record._next;
if (prev === null) {
this._mapHead = next;
}
else {
prev._next = next;
}
// todo(vicb) assert
// assert((() {
// record._next = null;
// return true;
//})());
};
/** @internal */
DefaultKeyValueDiffer.prototype._removeFromRemovals = function (record) {
// todo(vicb) assert
// assert(record._next == null);
// assert(record._nextAdded == null);
// assert(record._nextChanged == null);
var prev = record._prevRemoved;
var next = record._nextRemoved;
if (prev === null) {
this._removalsHead = next;
}
else {
prev._nextRemoved = next;
}
if (next === null) {
this._removalsTail = prev;
}
else {
next._prevRemoved = prev;
}
record._prevRemoved = record._nextRemoved = null;
};
/** @internal */
DefaultKeyValueDiffer.prototype._addToAdditions = function (record) {
// todo(vicb): assert
// assert(record._next == null);
// assert(record._nextAdded == null);
// assert(record._nextChanged == null);
// assert(record._nextRemoved == null);
// assert(record._prevRemoved == null);
if (this._additionsHead === null) {
this._additionsHead = this._additionsTail = record;
}
else {
this._additionsTail._nextAdded = record;
this._additionsTail = record;
}
};
/** @internal */
DefaultKeyValueDiffer.prototype._addToChanges = function (record) {
// todo(vicb) assert
// assert(record._nextAdded == null);
// assert(record._nextChanged == null);
// assert(record._nextRemoved == null);
// assert(record._prevRemoved == null);
if (this._changesHead === null) {
this._changesHead = this._changesTail = record;
}
else {
this._changesTail._nextChanged = record;
this._changesTail = record;
}
};
DefaultKeyValueDiffer.prototype.toString = function () {
var items = [];
var previous = [];
var changes = [];
var additions = [];
var removals = [];
var record;
for (record = this._mapHead; record !== null; record = record._next) {
items.push(lang_1.stringify(record));
}
for (record = this._previousMapHead; record !== null; record = record._nextPrevious) {
previous.push(lang_1.stringify(record));
}
for (record = this._changesHead; record !== null; record = record._nextChanged) {
changes.push(lang_1.stringify(record));
}
for (record = this._additionsHead; record !== null; record = record._nextAdded) {
additions.push(lang_1.stringify(record));
}
for (record = this._removalsHead; record !== null; record = record._nextRemoved) {
removals.push(lang_1.stringify(record));
}
return "map: " + items.join(', ') + "\n" + "previous: " + previous.join(', ') + "\n" +
"additions: " + additions.join(', ') + "\n" + "changes: " + changes.join(', ') + "\n" +
"removals: " + removals.join(', ') + "\n";
};
/** @internal */
DefaultKeyValueDiffer.prototype._forEach = function (obj, fn) {
if (obj instanceof Map) {
obj.forEach(fn);
}
else {
collection_1.StringMapWrapper.forEach(obj, fn);
}
};
return DefaultKeyValueDiffer;
})();
exports.DefaultKeyValueDiffer = DefaultKeyValueDiffer;
var KVChangeRecord = (function () {
function KVChangeRecord(key) {
this.key = key;
this.previousValue = null;
this.currentValue = null;
/** @internal */
this._nextPrevious = null;
/** @internal */
this._next = null;
/** @internal */
this._nextAdded = null;
/** @internal */
this._nextRemoved = null;
/** @internal */
this._prevRemoved = null;
/** @internal */
this._nextChanged = null;
}
KVChangeRecord.prototype.toString = function () {
return lang_1.looseIdentical(this.previousValue, this.currentValue) ?
lang_1.stringify(this.key) :
(lang_1.stringify(this.key) + '[' + lang_1.stringify(this.previousValue) + '->' +
lang_1.stringify(this.currentValue) + ']');
};
return KVChangeRecord;
})();
exports.KVChangeRecord = KVChangeRecord;
//# sourceMappingURL=default_keyvalue_differ.js.map |
window.hideAlert = function () {
$('#alertMessage').addClass("hidden");
$('#alertMessage').text("");
};
window.showAlert = function (msg) {
$('#alertMessage').text(msg);
$('#alertMessage').addClass("alert-danger");
$('#alertMessage').removeClass("hidden");
$('#alertMessage').fadeOut(100).fadeIn(100).fadeOut(100).fadeIn(100);
};
window.showInfo = function (msg) {
$('#alertMessage').text(msg);
$('#alertMessage').removeClass("alert-danger");
$('#alertMessage').removeClass("hidden");
$('#alertMessage').fadeOut(100).fadeIn(100).fadeOut(100).fadeIn(100);
};
window.dataErrorAlert = function (data) {
switch (data.idError) {
case "InvalidFile":
showAlert(Resources["InvalidFile"]);
break;
case "InvalidReg":
showAlert(Resources["WrongRegExpMessage"]);
break;
case "NotFound":
showAlert(Resources["NoSearchResultsMessage"]);
break;
case "InvalidPassword":
showAlert(Resources["UnlockInvalidPassword"]);
break;
default:
showAlert(data.idError);
break;
}
};
window.handleError = function (xhr, exception) {
hideLoader();
$('#workButton').removeClass("hidden");
var msg = '';
if (xhr.status === 0) {
msg = 'Not connect.\n Verify Network.';
} else if (xhr.status == 404) {
msg = 'Requested page not found. [404]';
} else if (xhr.status == 500) {
msg = 'Internal Server Error [500].';
} else if (exception === 'parsererror') {
msg = 'Requested JSON parse failed.';
} else if (exception === 'timeout') {
msg = 'Time out error.';
} else if (exception === 'abort') {
msg = 'Ajax request aborted.';
} else {
msg = 'Uncaught Error.\n' + xhr.responseText;
}
showAlert(msg);
};
|
define('controllers/panel',['require','jquery','backbone','utils/metrics','utils/browser','utils/video-player','utils/pubsub','controllers/panel-display'],function(require) {
var $ = require('jquery'),
Backbone = require('backbone'),
Metrics = require('utils/metrics'),
Browser = require('utils/browser'),
VideoPlayer = require('utils/video-player'),
PubSub = require('utils/pubsub'),
PanelDisplay = require('controllers/panel-display')
;
var PanelView = Backbone.View.extend({
events: {
},
panelOn: false,
minWidth: 320,
minHeight: 180,
leftLimit: 100,
topLimit: 100,
offset: 10,
border: 5,
initialize: function() {
Browser.checkMobileTabletDevice();
this.logger = new eventsCore.util.Logger('PanelView');
this.panel1 = new PanelDisplay({el: '#panel1'}).render();
this.panel2 = new PanelDisplay({el: '#panel2'}).render();
//this.logger.info('initialize - panel1:%o panel2:%o', this.panel1, this.panel2);
this.on('route:change', this.checkPage);
this.listenTo(PubSub, 'video:playPanel', this.onPlayPanel);
this.listenTo(PubSub, 'video:exitPanel', this.onExitPanel);
this.listenTo(PubSub, 'video:resetHero', this.onResetHero);
this.listenTo(PubSub, 'video:resetVod', this.onResetVod);
this.listenTo(VideoPlayer, 'player:play', this.onPlayEvent);
this.listenTo(VideoPlayer, 'player:panelOpen', this.onPanelOpenEvent);
this.listenTo(VideoPlayer, 'player:panelClosed', this.onPanelClosedEvent);
},
render: function() {
return this;
},
/**
* checks state/position of each panel and updates initial mute status
* executes on play and route change
*/
checkVolume: function() {
this.logger.info('checkVolume - panel1:%o panel2:%o', this.panel1.state(), this.panel2.state());
if (this.panel1.state() != '' && this.panel2.state() == '') {
this.panel1.mute(false);
this.panel2.mute(true);
}
else if (this.panel2.state() != '' && this.panel1.state() == '') {
this.panel2.mute(false);
this.panel1.mute(true);
}
else if (this.panel1.state() == 'floatVideo' && this.panel2.state() == 'heroVideo') {
this.panel2.mute(false);
this.panel1.mute(true);
}
else if (this.panel1.state() == 'heroVideo' && this.panel2.state() == 'floatVideo') {
this.panel1.mute(false);
this.panel2.mute(true);
}
},
/**
* close any open hero panel
* - used for mobile internal ref to a different watch live channel
*/
onResetHero: function() {
if(this.panel1.state() === 'heroVideo') {
this.panel1.onPanelExit();
} else if(this.panel2.state() === 'heroVideo') {
this.panel2.onPanelExit();
}
},
/**
* close any open vod floated panel
*/
onResetVod: function() {
if(this.panel1.state() === 'floatVideo') {
this.panel1.onPanelExit();
} else if(this.panel2.state() === 'floatVideo') {
this.panel2.onPanelExit();
}
},
/**
* play video in a panel, check for channel existing in panel first and use existing if playing
* @param data - panel video data
* @param channel - this live video data
* @param options - options to be passed to video player, consisting of:
* floated - optional boolean indicating if should start in float mode
* vod - indicates if playing a vod
*/
onPlayPanel: function(data, channel, options) {
options = _.extend({ floated: false, vod: false }, options);
this.logger.info('onPlayPanel - panel1:%o chan1:%o panel2:%o chan2:%o data:%o', this.panel1.state(), this.panel1.channelId(), this.panel2.state(), this.panel2.channelId(), data);
//if panel1 floating and opening the same channel, close to hero (to force back to hero when return to live channel page)
// do not close if float is true, call is trying to open same channel in already open float panel
if (this.panel1.channelId() == data[0].id) {
// if panel has no state, reset it to play channel
if(this.panel1.state() === '') {
this.panel1.playPanel(data, channel, options);
} else if (this.panel1.state() == 'floatVideo' && !options.floated)
this.panel1.panelClose(data, false);
else
this.logger.warn('onPlayPanel - ignoring call, attempted to open same channel already active');
}
//if panel2 floating and opening the same channel, close to hero (to force back to hero when return to live channel page)
// do not close if float is true, call i trying to open same channel in already open float panel
else if (this.panel2.channelId() == data[0].id){
// if panel has no state, reset it to play channel
if(this.panel2.state() === '') {
this.panel2.playPanel(data, channel, options);
} else if (this.panel2.state() == 'floatVideo' && !options.floated)
this.panel2.panelClose(data, false);
else
this.logger.warn('onPlayPanel - ignoring call, attempted to open same channel to floating panel');
}
//if panel1 in hero use it, (if not playing this channel)
else if ((this.panel1.state() == 'heroVideo' || this.panel1.state() == '') && this.panel1.channelId() != data[0].id) {
this.panel1.playPanel(data, channel, options);
}
//else use panel2 (if not playing this channel)
else if (this.panel2.channelId() != data[0].id){
this.panel2.playPanel(data, channel, options);
}
},
/**
* exit video playing in panel, whichever panel is open
*/
onExitPanel: function() {
this.logger.info('onExitPanel - panel1:%o chan1:%o panel2:%o chan2:%o', this.panel1.state(), this.panel1.channelId(), this.panel2.state(), this.panel2.channelId());
// close whichever one is floated
if(this.panel1.state() === 'floatVideo') {
this.panel1.onPanelExit();
} else if(this.panel2.state() === 'floatVideo') {
this.panel2.onPanelExit();
}
},
/**
* on play, initiates check for setting initial mute
* @param data - event data with panel id
*/
onPlayEvent: function(data) {
//this.logger.info('onPlayEvent - data:%o', data.id);
if (data.id == 'panel1' || data.id == 'panel2')
this.checkVolume();
},
/**
* handle panel open event from video player
* triggers panel to transition to float state
* @param data - event data with panel id
*/
onPanelOpenEvent: function(data) {
this.logger.info('onPanelOpenEvent - panel1:%o panel2:%o id:%o', this.panel1.state(), this.panel2.state(), data.id);
if(data.id == 'panel1') {
if (this.panel2.state() == 'floatVideo') {
this.panel2.panelClose(null, false);
}
this.panel1.panelOpen();
}
else if(data.id == 'panel2') {
if (this.panel1.state() == 'floatVideo') {
this.panel1.panelClose(null, false);
}
this.panel2.panelOpen();
}
},
/**
* handle panel close event from video player
* triggers panel to return to hero state
* @param data - event data with panel id
*/
onPanelClosedEvent: function(data) {
this.logger.info('onPanelClosedEvent - panel1:%o panel2:%o id:%o', this.panel1.state(), this.panel2.state(), data.id);
if(data.id == 'panel1') {
this.panel1.panelClose(data, true);
if (this.panel2.state() == 'heroVideo') {
this.panel2.panelClose(data, false);
this.checkVolume();
}
}
else if(data.id == 'panel2') {
this.panel2.panelClose(data, true);
if (this.panel1.state() == 'heroVideo') {
this.panel1.panelClose(data, false);
this.checkVolume();
}
}
},
/**
* initiate page check for closing hero on route change
* also check volume on route change
*/
checkPage: function(){
var route = Backbone.history.getFragment();
this.panel1.checkPage(route);
this.panel2.checkPage(route);
this.checkVolume();
}
});
return PanelView;
})
;
|
// Design Basic Game Solo Challenge
// This is a solo challenge
// Your mission description:To complete a line of the same figure, horizontal, diagonal or vertical
// Overall mission: To win all the time :)
// Goals: make a line of the same kind before computer does
// Characters:You and the computer
// Objects:tic tac toe
// Functions:clear_board, refresh_board, turn
// Pseudocode
// Make a Tictactoe class
// Initialize the instance
// Paint the board
// Take a turn UNTIL someones win
// Check if some one won
// Clear the board
//
//
//
//
// Initial Code
turns = 0
board_state = [[" "," "," "],
[" "," "," "],
[" "," "," "]];
var Tictactoe = {
take_turn : function(user){
mark = prompt("It is your turn, where do you want to mark?");
horizontal = mark[1];
vertical = mark[0].toUpperCase();
if (vertical == "A"){
vertical = 0
} else if (vertical == "B"){
vertical = 1
} else {
vertical = 2
}
board_state[horizontal-1][vertical] = user
console.log(board_state)
},
print_board : function(){
line = ""
console.log(" A B C")
for (i in board_state){
new_line = "\n ═══╬═══╬═══\n"
for (x in board_state[i]){
ln = parseInt(i);
if (x == 0){line = (ln+1)+" "}
if (x == 2) {
if (i == 2){new_line = "\n"}
line += " "+board_state[i][x]+new_line;
} else {
line += " "+board_state[i][x]+" ║"
}
}
console.log(line);
}
}
}
alert ("Welcome to @cyberpolin's Tic Tac Toe\n So it is the turn of User 1, please select where you want to mark...")
Tictactoe.print_board()
while (turns < 9){
if (turns%2 == 0){
Tictactoe.take_turn("o");
} else {
Tictactoe.take_turn("x");
}
Tictactoe.print_board();
turns++;
}
// RELECTION
// What was the most difficult part of this challenge?
// Order my toughts to make the code works as i wannted, also as javascript is not a language thinked for terminal it was difficult to figure out how it was going to work.
// What did you learn about creating objects and functions that interact with one another?
// Is like in ruby, i think of them as just methods
// Did you learn about any new built-in methods you could use in your refactored solution? If so, what were they and how do they work?
// The only one i used was toUpperCase, ad they are like Ruby methods even tough Javascript have a different syntax.
// How can you access and manipulate properties of objects?
// like in Ruby object[property] = new_value, or the JS way object.property = new_value
// TODO'S
// Check if a place is marked already
// Check if you have winned
// Make it playable with computer
// MAKE IT GRAPHICAL!!!! |
// GridFS
// Copyright(c) 2013 Siddharth Mahendraker <[email protected]>
// MIT Licensed
exports.GridFS = require('./lib/GridFS');
exports.GridStream = require('./lib/GridStream');
|
// @flow
class A {
x = [1, 2, 3];
y = 4;
foo() {
this.x = this.x.map(function (z) {
this.y; // error, function has wrong this
});
}
}
class B {
x = [1, 2, 3];
y = 4;
foo() {
this.x = this.x.map(function (z) {
this.y; // ok, function gets passed correct this
}, this);
}
}
class C {
x = [1, 2, 3];
y = 4;
foo() {
this.x = this.x.map(z => {
this.y; // ok, arrow binds surrounding context this
});
}
}
|
import collectionClass from "./collections.class";
import collectionColor from "./collections.color";
function collectionBackgroundStyles(contentItem) {
return `
.${collectionClass(contentItem)} {
background-color: #${collectionColor(contentItem)};
}
`;
}
export default collectionBackgroundStyles;
|
version https://git-lfs.github.com/spec/v1
oid sha256:71736be070607c3c30f4c139b063edf1b1ffa587cf725a0acc1e06c6d3af0e48
size 53235
|
'use strict';
/**
* Module dependencies.
*/
var mongoose = require('mongoose'),
CurrentModel = mongoose.model('Attendance'),
Schedule = mongoose.model('Schedule'),
Group = mongoose.model('Group'),
_ = require('lodash');
exports.attendance = function(req, res, next, id) {
CurrentModel.load(id, function(err, item) {
if (err) return next(err);
if (!item) return next(new Error('Failed to load item ' + id));
req.attendance = item;
next();
});
};
exports.schedule = function(req, res, next, id) {
Schedule.load(id, function(err, item) {
if (err) return next(err);
if (!item) return next(new Error('Failed to load item ' + id));
req.schedule = item;
next();
});
};
exports.group = function(req, res, next, id) {
Group.load(id, function(err, item) {
if (err) return next(err);
if (!item) return next(new Error('Failed to load item ' + id));
req.group = item;
next();
});
};
exports.create = function(req, res) {
var value = new CurrentModel(req.body);
value.group = req.group;
value.schedule = req.schedule;
value.save(function(err) {
if (err) {
return res.send('users/signup', {
errors: err.errors,
object: value
});
} else {
res.jsonp(value);
}
});
};
exports.update = function(req, res) {
var item = req.attendance;
item = _.extend(item, req.body);
item.save(function(err) {
if (err) {
return res.send('users/signup', {
errors: err.errors,
object: item
});
} else {
res.jsonp(item);
}
});
};
exports.destroy = function(req, res) {
var item = req.attendance;
item.remove(function(err) {
if (err) {
return res.send('users/signup', {
errors: err.errors,
object: item
});
} else {
res.jsonp(item);
}
});
};
exports.show = function(req, res) {
res.jsonp(req.attendance);
};
exports.all = function(req, res) {
CurrentModel.find({ group: req.group, schedule: req.schedule }).populate('participant', 'name email').exec(function(err, items) {
if (err) {
res.render('error', {
status: 500
});
} else {
res.jsonp(items);
}
});
};
|
Subsets and Splits