/******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId]) {
/******/ return installedModules[moduleId].exports;
/******/ }
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ i: moduleId,
/******/ l: false,
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ // Flag the module as loaded
/******/ module.l = true;
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/******/
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/
/******/ // define getter function for harmony exports
/******/ __webpack_require__.d = function(exports, name, getter) {
/******/ if(!__webpack_require__.o(exports, name)) {
/******/ Object.defineProperty(exports, name, { enumerable: true, get: getter });
/******/ }
/******/ };
/******/
/******/ // define __esModule on exports
/******/ __webpack_require__.r = function(exports) {
/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
/******/ }
/******/ Object.defineProperty(exports, '__esModule', { value: true });
/******/ };
/******/
/******/ // create a fake namespace object
/******/ // mode & 1: value is a module id, require it
/******/ // mode & 2: merge all properties of value into the ns
/******/ // mode & 4: return value when already ns object
/******/ // mode & 8|1: behave like require
/******/ __webpack_require__.t = function(value, mode) {
/******/ if(mode & 1) value = __webpack_require__(value);
/******/ if(mode & 8) return value;
/******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;
/******/ var ns = Object.create(null);
/******/ __webpack_require__.r(ns);
/******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value });
/******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));
/******/ return ns;
/******/ };
/******/
/******/ // getDefaultExport function for compatibility with non-harmony modules
/******/ __webpack_require__.n = function(module) {
/******/ var getter = module && module.__esModule ?
/******/ function getDefault() { return module['default']; } :
/******/ function getModuleExports() { return module; };
/******/ __webpack_require__.d(getter, 'a', getter);
/******/ return getter;
/******/ };
/******/
/******/ // Object.prototype.hasOwnProperty.call
/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/
/******/
/******/ // Load entry module and return exports
/******/ return __webpack_require__(__webpack_require__.s = "./app/assets/javascripts/index.js");
/******/ })
/************************************************************************/
/******/ ({
/***/ "../snjs/dist/snjs.js":
/*!****************************!*\
!*** ../snjs/dist/snjs.js ***!
\****************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
(function webpackUniversalModuleDefinition(root, factory) {
if (true) module.exports = factory();else {}
})(window, function () {
return (
/******/
function (modules) {
// webpackBootstrap
/******/
// The module cache
/******/
var installedModules = {};
/******/
/******/
// The require function
/******/
function __webpack_require__(moduleId) {
/******/
/******/
// Check if module is in cache
/******/
if (installedModules[moduleId]) {
/******/
return installedModules[moduleId].exports;
/******/
}
/******/
// Create a new module (and put it into the cache)
/******/
var module = installedModules[moduleId] = {
/******/
i: moduleId,
/******/
l: false,
/******/
exports: {}
/******/
};
/******/
/******/
// Execute the module function
/******/
modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/
// Flag the module as loaded
/******/
module.l = true;
/******/
/******/
// Return the exports of the module
/******/
return module.exports;
/******/
}
/******/
/******/
/******/
// expose the modules object (__webpack_modules__)
/******/
__webpack_require__.m = modules;
/******/
/******/
// expose the module cache
/******/
__webpack_require__.c = installedModules;
/******/
/******/
// define getter function for harmony exports
/******/
__webpack_require__.d = function (exports, name, getter) {
/******/
if (!__webpack_require__.o(exports, name)) {
/******/
Object.defineProperty(exports, name, {
enumerable: true,
get: getter
});
/******/
}
/******/
};
/******/
/******/
// define __esModule on exports
/******/
__webpack_require__.r = function (exports) {
/******/
if (typeof Symbol !== 'undefined' && Symbol.toStringTag) {
/******/
Object.defineProperty(exports, Symbol.toStringTag, {
value: 'Module'
});
/******/
}
/******/
Object.defineProperty(exports, '__esModule', {
value: true
});
/******/
};
/******/
/******/
// create a fake namespace object
/******/
// mode & 1: value is a module id, require it
/******/
// mode & 2: merge all properties of value into the ns
/******/
// mode & 4: return value when already ns object
/******/
// mode & 8|1: behave like require
/******/
__webpack_require__.t = function (value, mode) {
/******/
if (mode & 1) value = __webpack_require__(value);
/******/
if (mode & 8) return value;
/******/
if (mode & 4 && typeof value === 'object' && value && value.__esModule) return value;
/******/
var ns = Object.create(null);
/******/
__webpack_require__.r(ns);
/******/
Object.defineProperty(ns, 'default', {
enumerable: true,
value: value
});
/******/
if (mode & 2 && typeof value != 'string') for (var key in value) __webpack_require__.d(ns, key, function (key) {
return value[key];
}.bind(null, key));
/******/
return ns;
/******/
};
/******/
/******/
// getDefaultExport function for compatibility with non-harmony modules
/******/
__webpack_require__.n = function (module) {
/******/
var getter = module && module.__esModule ?
/******/
function getDefault() {
return module['default'];
} :
/******/
function getModuleExports() {
return module;
};
/******/
__webpack_require__.d(getter, 'a', getter);
/******/
return getter;
/******/
};
/******/
/******/
// Object.prototype.hasOwnProperty.call
/******/
__webpack_require__.o = function (object, property) {
return Object.prototype.hasOwnProperty.call(object, property);
};
/******/
/******/
// __webpack_public_path__
/******/
__webpack_require__.p = "";
/******/
/******/
/******/
// Load entry module and return exports
/******/
return __webpack_require__(__webpack_require__.s = "./lib/main.js");
/******/
}(
/************************************************************************/
/******/
{
/***/
"./lib/main.js":
/*!*********************!*\
!*** ./lib/main.js ***!
\*********************/
/*! exports provided: SNApplication, SNProtocolService, SNProtocolOperator001, SNProtocolOperator002, SNProtocolOperator003, SNProtocolOperator004, DeviceInterface, SFItem, SNItemsKey, SFPredicate, SNNote, SNTag, SNSmartTag, SNMfa, SNServerExtension, SNComponent, SNEditor, SNActionsExtension, Action, SNTheme, SNEncryptedStorage, SNComponentManager, HistorySession, ItemHistory, ItemHistoryEntry, SFPrivileges, SNWebCrypto, SNReactNativeCrypto, SNModelManager, SNHttpManager, DeviceAuthService, DeviceAuthResponse, SNStorageManager, STORAGE_PERSISTENCE_POLICY_DEFAULT, STORAGE_PERSISTENCE_POLICY_EPHEMERAL, STORAGE_ENCRYPTION_POLICY_DEFAULT, STORAGE_ENCRYPTION_POLICY_DISABLED, STORAGE_VALUE_MODE_DEFAULT, STORAGE_VALUE_MODE_NONWRAPPED, Challenges, SNSyncManager, TIMING_STRATEGY_RESOLVE_ON_NEXT, TIMING_STRATEGY_FORCE_SPAWN_NEW, SNSessionManager, SNMigrationService, SNAlertManager, SNHistoryManager, SNPrivilegesManager, SNSingletonManager, SNKeyManager, KEY_MODE_ROOT_KEY_NONE, KEY_MODE_ROOT_KEY_ONLY, KEY_MODE_ROOT_KEY_PLUS_WRAPPER, KEY_MODE_WRAPPER_ONLY, SNApiService, findInArray, isNullOrUndefined, deepMerge, extendArray, removeFromIndex, subtractFromArray, arrayByDifference, uniqCombineObjArrays, greaterOfTwoDates, ENCRYPTION_INTENT_LOCAL_STORAGE_DECRYPTED, ENCRYPTION_INTENT_LOCAL_STORAGE_ENCRYPTED, ENCRYPTION_INTENT_LOCAL_STORAGE_PREFER_ENCRYPTED, ENCRYPTION_INTENT_FILE_DECRYPTED, ENCRYPTION_INTENT_FILE_ENCRYPTED, ENCRYPTION_INTENT_SYNC, isLocalStorageIntent, isFileIntent, isDecryptedIntent, intentRequiresEncryption, CONTENT_TYPE_ROOT_KEY, CONTENT_TYPE_ITEMS_KEY, CONTENT_TYPE_ENCRYPTED_STORAGE, CONTENT_TYPE_NOTE, CONTENT_TYPE_TAG, CONTENT_TYPE_USER_PREFS, CONTENT_TYPE_COMPONENT, CONTENT_TYPE_PRIVILEGES, ApplicationEvents, Environments, Platforms, isEnvironmentWebOrDesktop, isEnvironmentMobile, SYNC_EVENT_FULL_SYNC_COMPLETED, SNPureItemPayload, SNStorageItemPayload, PayloadCollection, CreateMaxPayloadFromAnyObject, CreateSourcedPayloadFromObject, PAYLOAD_SOURCE_REMOTE_RETRIEVED, PAYLOAD_SOURCE_REMOTE_SAVED, PAYLOAD_SOURCE_LOCAL_SAVED, PAYLOAD_SOURCE_LOCAL_RETRIEVED, PAYLOAD_SOURCE_LOCAL_DIRTIED, PAYLOAD_SOURCE_COMPONENT_RETRIEVED, PAYLOAD_SOURCE_DESKTOP_INSTALLED, PAYLOAD_SOURCE_REMOTE_ACTION_RETRIEVED, PAYLOAD_SOURCE_FILE_IMPORT, isPayloadSourceRetrieved, PAYLOAD_CONTENT_FORMAT_ENCRYPTED_STRING, PAYLOAD_CONTENT_FORMAT_DECRYPTED_BARE_OBJECT, PAYLOAD_CONTENT_FORMAT_DECRYPTED_BASE_64_STRING, STORAGE_KEY_ROOT_KEY_PARAMS, STORAGE_KEY_MOBILE_PASSCODE_TIMING, BaseMigration, ProtectedActions, PRIVILEGE_CREDENTIAL_ACCOUNT_PASSWORD, PRIVILEGE_CREDENTIAL_LOCAL_PASSCODE, PRIVILEGE_SESSION_LENGTH_NONE, PRIVILEGE_SESSION_LENGTH_FIVE_MINUTES, PRIVILEGE_SESSION_LENGTH_ONE_HOUR, PRIVILEGE_SESSION_LENGTH_ONE_WEEK */
/***/
function (module, exports) {
throw new Error("Module build failed (from ./node_modules/babel-loader/lib/index.js):\nSyntaxError: /Users/mo/Desktop/sn/dev/snjs/lib/main.js: Unexpected token, expected \",\" (85:14)\n\n\u001b[0m \u001b[90m 83 | \u001b[39m\u001b[36mexport\u001b[39m {\u001b[0m\n\u001b[0m \u001b[90m 84 | \u001b[39m \u001b[33mCONTENT_TYPE_ROOT_KEY\u001b[39m\u001b[33m,\u001b[39m\u001b[0m\n\u001b[0m\u001b[31m\u001b[1m>\u001b[22m\u001b[39m\u001b[90m 85 | \u001b[39m \u001b[33mContentTypes\u001b[39m\u001b[33m.\u001b[39m\u001b[33mItemS_KEY\u001b[39m\u001b[33m,\u001b[39m\u001b[0m\n\u001b[0m \u001b[90m | \u001b[39m \u001b[31m\u001b[1m^\u001b[22m\u001b[39m\u001b[0m\n\u001b[0m \u001b[90m 86 | \u001b[39m \u001b[33mCONTENT_TYPE_ENCRYPTED_STORAGE\u001b[39m\u001b[33m,\u001b[39m\u001b[0m\n\u001b[0m \u001b[90m 87 | \u001b[39m \u001b[33mCONTENT_TYPE_NOTE\u001b[39m\u001b[33m,\u001b[39m\u001b[0m\n\u001b[0m \u001b[90m 88 | \u001b[39m \u001b[33mCONTENT_TYPE_TAG\u001b[39m\u001b[33m,\u001b[39m\u001b[0m\n at Object.raise (/Users/mo/Desktop/sn/dev/snjs/node_modules/@babel/parser/lib/index.js:6983:17)\n at Object.unexpected (/Users/mo/Desktop/sn/dev/snjs/node_modules/@babel/parser/lib/index.js:8376:16)\n at Object.expect (/Users/mo/Desktop/sn/dev/snjs/node_modules/@babel/parser/lib/index.js:8362:28)\n at Object.parseExportSpecifiers (/Users/mo/Desktop/sn/dev/snjs/node_modules/@babel/parser/lib/index.js:11983:14)\n at Object.maybeParseExportNamedSpecifiers (/Users/mo/Desktop/sn/dev/snjs/node_modules/@babel/parser/lib/index.js:11788:36)\n at Object.parseExport (/Users/mo/Desktop/sn/dev/snjs/node_modules/@babel/parser/lib/index.js:11727:32)\n at Object.parseStatementContent (/Users/mo/Desktop/sn/dev/snjs/node_modules/@babel/parser/lib/index.js:10770:27)\n at Object.parseStatement (/Users/mo/Desktop/sn/dev/snjs/node_modules/@babel/parser/lib/index.js:10666:17)\n at Object.parseBlockOrModuleBlockBody (/Users/mo/Desktop/sn/dev/snjs/node_modules/@babel/parser/lib/index.js:11242:25)\n at Object.parseBlockBody (/Users/mo/Desktop/sn/dev/snjs/node_modules/@babel/parser/lib/index.js:11229:10)\n at Object.parseTopLevel (/Users/mo/Desktop/sn/dev/snjs/node_modules/@babel/parser/lib/index.js:10597:10)\n at Object.parse (/Users/mo/Desktop/sn/dev/snjs/node_modules/@babel/parser/lib/index.js:12107:10)\n at parse (/Users/mo/Desktop/sn/dev/snjs/node_modules/@babel/parser/lib/index.js:12158:38)\n at parser (/Users/mo/Desktop/sn/dev/snjs/node_modules/@babel/core/lib/transformation/normalize-file.js:168:34)\n at normalizeFile (/Users/mo/Desktop/sn/dev/snjs/node_modules/@babel/core/lib/transformation/normalize-file.js:102:11)\n at runSync (/Users/mo/Desktop/sn/dev/snjs/node_modules/@babel/core/lib/transformation/index.js:44:43)\n at runAsync (/Users/mo/Desktop/sn/dev/snjs/node_modules/@babel/core/lib/transformation/index.js:35:14)\n at /Users/mo/Desktop/sn/dev/snjs/node_modules/@babel/core/lib/transform.js:34:34\n at processTicksAndRejections (internal/process/task_queues.js:79:11)");
/***/
}
/******/
})
);
});
/***/ }),
/***/ "./app/assets/javascripts/app.js":
/*!***************************************!*\
!*** ./app/assets/javascripts/app.js ***!
\***************************************/
/*! no exports provided */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var angular__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! angular */ "./node_modules/angular/index.js");
/* harmony import */ var angular__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(angular__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _routes__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./routes */ "./app/assets/javascripts/routes.js");
/* harmony import */ var _application__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./application */ "./app/assets/javascripts/application.js");
/* harmony import */ var _state__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./state */ "./app/assets/javascripts/state.js");
/* harmony import */ var _controllers__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./controllers */ "./app/assets/javascripts/controllers/index.js");
/* harmony import */ var _directives_functional__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./directives/functional */ "./app/assets/javascripts/directives/functional/index.js");
/* harmony import */ var _directives_views__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./directives/views */ "./app/assets/javascripts/directives/views/index.js");
/* harmony import */ var _filters__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./filters */ "./app/assets/javascripts/filters/index.js");
/* harmony import */ var _services__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./services */ "./app/assets/javascripts/services/index.js");
angular__WEBPACK_IMPORTED_MODULE_0___default.a.module('app', ['ngSanitize']); // Config
angular__WEBPACK_IMPORTED_MODULE_0___default.a.module('app').config(_routes__WEBPACK_IMPORTED_MODULE_1__["configRoutes"]).constant('appVersion', "3.3.0"); // Controllers
angular__WEBPACK_IMPORTED_MODULE_0___default.a.module('app').directive('root', function () {
return new _controllers__WEBPACK_IMPORTED_MODULE_4__["Root"]();
}).directive('tagsPanel', function () {
return new _controllers__WEBPACK_IMPORTED_MODULE_4__["TagsPanel"]();
}).directive('notesPanel', function () {
return new _controllers__WEBPACK_IMPORTED_MODULE_4__["NotesPanel"]();
}).directive('editorPanel', function () {
return new _controllers__WEBPACK_IMPORTED_MODULE_4__["EditorPanel"]();
}).directive('footer', function () {
return new _controllers__WEBPACK_IMPORTED_MODULE_4__["Footer"]();
}).directive('lockScreen', function () {
return new _controllers__WEBPACK_IMPORTED_MODULE_4__["LockScreen"]();
}); // Directives - Functional
angular__WEBPACK_IMPORTED_MODULE_0___default.a.module('app').directive('snAutofocus', ['$timeout', _directives_functional__WEBPACK_IMPORTED_MODULE_5__["autofocus"]]).directive('clickOutside', ['$document', _directives_functional__WEBPACK_IMPORTED_MODULE_5__["clickOutside"]]).directive('delayHide', _directives_functional__WEBPACK_IMPORTED_MODULE_5__["delayHide"]).directive('elemReady', _directives_functional__WEBPACK_IMPORTED_MODULE_5__["elemReady"]).directive('fileChange', _directives_functional__WEBPACK_IMPORTED_MODULE_5__["fileChange"]).directive('infiniteScroll', ['$rootScope', '$window', '$timeout', _directives_functional__WEBPACK_IMPORTED_MODULE_5__["infiniteScroll"]]).directive('lowercase', _directives_functional__WEBPACK_IMPORTED_MODULE_5__["lowercase"]).directive('selectOnClick', ['$window', _directives_functional__WEBPACK_IMPORTED_MODULE_5__["selectOnClick"]]).directive('snEnter', _directives_functional__WEBPACK_IMPORTED_MODULE_5__["snEnter"]); // Directives - Views
angular__WEBPACK_IMPORTED_MODULE_0___default.a.module('app').directive('accountMenu', function () {
return new _directives_views__WEBPACK_IMPORTED_MODULE_6__["AccountMenu"]();
}).directive('actionsMenu', function () {
return new _directives_views__WEBPACK_IMPORTED_MODULE_6__["ActionsMenu"]();
}).directive('componentModal', function () {
return new _directives_views__WEBPACK_IMPORTED_MODULE_6__["ComponentModal"]();
}).directive('componentView', ["$rootScope", "componentManager", "desktopManager", "$timeout", function ($rootScope, componentManager, desktopManager, $timeout) {
return new _directives_views__WEBPACK_IMPORTED_MODULE_6__["ComponentView"]($rootScope, componentManager, desktopManager, $timeout);
}]).directive('conflictResolutionModal', function () {
return new _directives_views__WEBPACK_IMPORTED_MODULE_6__["ConflictResolutionModal"]();
}).directive('editorMenu', function () {
return new _directives_views__WEBPACK_IMPORTED_MODULE_6__["EditorMenu"]();
}).directive('inputModal', function () {
return new _directives_views__WEBPACK_IMPORTED_MODULE_6__["InputModal"]();
}).directive('menuRow', function () {
return new _directives_views__WEBPACK_IMPORTED_MODULE_6__["MenuRow"]();
}).directive('panelResizer', function () {
return new _directives_views__WEBPACK_IMPORTED_MODULE_6__["PanelResizer"]();
}).directive('passwordWizard', function () {
return new _directives_views__WEBPACK_IMPORTED_MODULE_6__["PasswordWizard"]();
}).directive('permissionsModal', function () {
return new _directives_views__WEBPACK_IMPORTED_MODULE_6__["PermissionsModal"]();
}).directive('privilegesAuthModal', function () {
return new _directives_views__WEBPACK_IMPORTED_MODULE_6__["PrivilegesAuthModal"]();
}).directive('privilegesManagementModal', function () {
return new _directives_views__WEBPACK_IMPORTED_MODULE_6__["PrivilegesManagementModal"]();
}).directive('revisionPreviewModal', function () {
return new _directives_views__WEBPACK_IMPORTED_MODULE_6__["RevisionPreviewModal"]();
}).directive('sessionHistoryMenu', function () {
return new _directives_views__WEBPACK_IMPORTED_MODULE_6__["SessionHistoryMenu"]();
}).directive('syncResolutionMenu', function () {
return new _directives_views__WEBPACK_IMPORTED_MODULE_6__["SyncResolutionMenu"]();
}); // Filters
angular__WEBPACK_IMPORTED_MODULE_0___default.a.module('app').filter('trusted', ['$sce', _filters__WEBPACK_IMPORTED_MODULE_7__["trusted"]]); // Services
angular__WEBPACK_IMPORTED_MODULE_0___default.a.module('app').service('application', _application__WEBPACK_IMPORTED_MODULE_2__["Application"]).service('appState', _state__WEBPACK_IMPORTED_MODULE_3__["AppState"]).service('preferencesManager', _services__WEBPACK_IMPORTED_MODULE_8__["PreferencesManager"]).service('actionsManager', _services__WEBPACK_IMPORTED_MODULE_8__["ActionsManager"]).service('archiveManager', _services__WEBPACK_IMPORTED_MODULE_8__["ArchiveManager"]).service('authManager', _services__WEBPACK_IMPORTED_MODULE_8__["AuthManager"]).service('componentManager', _services__WEBPACK_IMPORTED_MODULE_8__["ComponentManager"]).service('databaseManager', _services__WEBPACK_IMPORTED_MODULE_8__["DatabaseManager"]).service('desktopManager', _services__WEBPACK_IMPORTED_MODULE_8__["DesktopManager"]).service('httpManager', _services__WEBPACK_IMPORTED_MODULE_8__["HttpManager"]).service('keyboardManager', _services__WEBPACK_IMPORTED_MODULE_8__["KeyboardManager"]).service('migrationManager', _services__WEBPACK_IMPORTED_MODULE_8__["MigrationManager"]).service('modelManager', _services__WEBPACK_IMPORTED_MODULE_8__["ModelManager"]).service('nativeExtManager', _services__WEBPACK_IMPORTED_MODULE_8__["NativeExtManager"]).service('lockManager', _services__WEBPACK_IMPORTED_MODULE_8__["LockManager"]).service('privilegesManager', _services__WEBPACK_IMPORTED_MODULE_8__["PrivilegesManager"]).service('sessionHistory', _services__WEBPACK_IMPORTED_MODULE_8__["SessionHistory"]).service('singletonManager', _services__WEBPACK_IMPORTED_MODULE_8__["SingletonManager"]).service('statusManager', _services__WEBPACK_IMPORTED_MODULE_8__["StatusManager"]).service('storageManager', _services__WEBPACK_IMPORTED_MODULE_8__["StorageManager"]).service('syncManager', _services__WEBPACK_IMPORTED_MODULE_8__["SyncManager"]).service('alertManager', _services__WEBPACK_IMPORTED_MODULE_8__["AlertManager"]).service('themeManager', _services__WEBPACK_IMPORTED_MODULE_8__["ThemeManager"]);
/***/ }),
/***/ "./app/assets/javascripts/application.js":
/*!***********************************************!*\
!*** ./app/assets/javascripts/application.js ***!
\***********************************************/
/*! exports provided: Application */
/***/ (function(module, exports) {
throw new Error("Module build failed (from ./node_modules/babel-loader/lib/index.js):\nSyntaxError: /Users/mo/Desktop/sn/dev/web/app/assets/javascripts/application.js: Unexpected token, expected \",\" (4:2)\n\n\u001b[0m \u001b[90m 2 | \u001b[39m \u001b[33mSNApplication\u001b[39m\u001b[33m,\u001b[39m\u001b[0m\n\u001b[0m \u001b[90m 3 | \u001b[39m \u001b[33mSNAlertManager\u001b[39m\u001b[0m\n\u001b[0m\u001b[31m\u001b[1m>\u001b[22m\u001b[39m\u001b[90m 4 | \u001b[39m \u001b[33mPlatforms\u001b[39m\u001b[33m,\u001b[39m\u001b[0m\n\u001b[0m \u001b[90m | \u001b[39m \u001b[31m\u001b[1m^\u001b[22m\u001b[39m\u001b[0m\n\u001b[0m \u001b[90m 5 | \u001b[39m \u001b[33mEnvironments\u001b[39m\u001b[0m\n\u001b[0m \u001b[90m 6 | \u001b[39m } from \u001b[32m'snjs'\u001b[39m\u001b[33m;\u001b[39m\u001b[0m\n\u001b[0m \u001b[90m 7 | \u001b[39m \u001b[36mimport\u001b[39m angular from \u001b[32m'angular'\u001b[39m\u001b[33m;\u001b[39m\u001b[0m\n at Parser.raise (/Users/mo/Desktop/sn/dev/web/node_modules/@babel/core/node_modules/@babel/parser/lib/index.js:7017:17)\n at Parser.unexpected (/Users/mo/Desktop/sn/dev/web/node_modules/@babel/core/node_modules/@babel/parser/lib/index.js:8395:16)\n at Parser.expect (/Users/mo/Desktop/sn/dev/web/node_modules/@babel/core/node_modules/@babel/parser/lib/index.js:8381:28)\n at Parser.parseNamedImportSpecifiers (/Users/mo/Desktop/sn/dev/web/node_modules/@babel/core/node_modules/@babel/parser/lib/index.js:12080:14)\n at Parser.parseImport (/Users/mo/Desktop/sn/dev/web/node_modules/@babel/core/node_modules/@babel/parser/lib/index.js:12023:39)\n at Parser.parseStatementContent (/Users/mo/Desktop/sn/dev/web/node_modules/@babel/core/node_modules/@babel/parser/lib/index.js:10788:27)\n at Parser.parseStatement (/Users/mo/Desktop/sn/dev/web/node_modules/@babel/core/node_modules/@babel/parser/lib/index.js:10690:17)\n at Parser.parseBlockOrModuleBlockBody (/Users/mo/Desktop/sn/dev/web/node_modules/@babel/core/node_modules/@babel/parser/lib/index.js:11264:25)\n at Parser.parseBlockBody (/Users/mo/Desktop/sn/dev/web/node_modules/@babel/core/node_modules/@babel/parser/lib/index.js:11251:10)\n at Parser.parseTopLevel (/Users/mo/Desktop/sn/dev/web/node_modules/@babel/core/node_modules/@babel/parser/lib/index.js:10621:10)\n at Parser.parse (/Users/mo/Desktop/sn/dev/web/node_modules/@babel/core/node_modules/@babel/parser/lib/index.js:12222:10)\n at parse (/Users/mo/Desktop/sn/dev/web/node_modules/@babel/core/node_modules/@babel/parser/lib/index.js:12273:38)\n at parser (/Users/mo/Desktop/sn/dev/web/node_modules/@babel/core/lib/parser/index.js:54:34)\n at parser.next ()\n at normalizeFile (/Users/mo/Desktop/sn/dev/web/node_modules/@babel/core/lib/transformation/normalize-file.js:93:38)\n at normalizeFile.next ()\n at run (/Users/mo/Desktop/sn/dev/web/node_modules/@babel/core/lib/transformation/index.js:31:50)\n at run.next ()\n at Function.transform (/Users/mo/Desktop/sn/dev/web/node_modules/@babel/core/lib/transform.js:27:41)\n at transform.next ()\n at step (/Users/mo/Desktop/sn/dev/web/node_modules/gensync/index.js:254:32)\n at /Users/mo/Desktop/sn/dev/web/node_modules/gensync/index.js:266:13\n at async.call.result.err.err (/Users/mo/Desktop/sn/dev/web/node_modules/gensync/index.js:216:11)\n at runMicrotasks ()\n at processTicksAndRejections (internal/process/task_queues.js:97:5)");
/***/ }),
/***/ "./app/assets/javascripts/controllers/abstract/pure_ctrl.js":
/*!******************************************************************!*\
!*** ./app/assets/javascripts/controllers/abstract/pure_ctrl.js ***!
\******************************************************************/
/*! exports provided: PureCtrl */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PureCtrl", function() { return PureCtrl; });
/* harmony import */ var _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/regenerator */ "./node_modules/@babel/runtime/regenerator/index.js");
/* harmony import */ var _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/helpers/asyncToGenerator */ "./node_modules/@babel/runtime/helpers/asyncToGenerator.js");
/* harmony import */ var _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "./node_modules/@babel/runtime/helpers/classCallCheck.js");
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @babel/runtime/helpers/createClass */ "./node_modules/@babel/runtime/helpers/createClass.js");
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3__);
var PureCtrl =
/*#__PURE__*/
function () {
function PureCtrl($timeout) {
_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2___default()(this, PureCtrl);
if (!$timeout) {
throw 'Invalid PureCtrl construction.';
}
this.$timeout = $timeout;
this.state = {};
this.props = {};
}
_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3___default()(PureCtrl, [{
key: "setState",
value: function () {
var _setState = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee(state) {
var _this = this;
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
return _context.abrupt("return", new Promise(function (resolve) {
_this.$timeout(function () {
_this.state = Object.freeze(Object.assign({}, _this.state, state));
resolve();
});
}));
case 1:
case "end":
return _context.stop();
}
}
}, _callee);
}));
function setState(_x) {
return _setState.apply(this, arguments);
}
return setState;
}()
}, {
key: "initProps",
value: function initProps(props) {
if (Object.keys(this.props).length > 0) {
throw 'Already init-ed props.';
}
this.props = Object.freeze(Object.assign({}, this.props, props));
}
}]);
return PureCtrl;
}();
/***/ }),
/***/ "./app/assets/javascripts/controllers/constants.js":
/*!*********************************************************!*\
!*** ./app/assets/javascripts/controllers/constants.js ***!
\*********************************************************/
/*! exports provided: PANEL_NAME_NOTES, PANEL_NAME_TAGS */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PANEL_NAME_NOTES", function() { return PANEL_NAME_NOTES; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PANEL_NAME_TAGS", function() { return PANEL_NAME_TAGS; });
var PANEL_NAME_NOTES = 'notes';
var PANEL_NAME_TAGS = 'tags';
/***/ }),
/***/ "./app/assets/javascripts/controllers/editor.js":
/*!******************************************************!*\
!*** ./app/assets/javascripts/controllers/editor.js ***!
\******************************************************/
/*! exports provided: EditorPanel */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "EditorPanel", function() { return EditorPanel; });
/* harmony import */ var _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/regenerator */ "./node_modules/@babel/runtime/regenerator/index.js");
/* harmony import */ var _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/helpers/asyncToGenerator */ "./node_modules/@babel/runtime/helpers/asyncToGenerator.js");
/* harmony import */ var _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "./node_modules/@babel/runtime/helpers/classCallCheck.js");
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @babel/runtime/helpers/createClass */ "./node_modules/@babel/runtime/helpers/createClass.js");
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var _babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "./node_modules/@babel/runtime/helpers/possibleConstructorReturn.js");
/* harmony import */ var _babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_4__);
/* harmony import */ var _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "./node_modules/@babel/runtime/helpers/getPrototypeOf.js");
/* harmony import */ var _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_5___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_5__);
/* harmony import */ var _babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! @babel/runtime/helpers/assertThisInitialized */ "./node_modules/@babel/runtime/helpers/assertThisInitialized.js");
/* harmony import */ var _babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_6___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_6__);
/* harmony import */ var _babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! @babel/runtime/helpers/inherits */ "./node_modules/@babel/runtime/helpers/inherits.js");
/* harmony import */ var _babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_7___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_7__);
/* harmony import */ var _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! @babel/runtime/helpers/defineProperty */ "./node_modules/@babel/runtime/helpers/defineProperty.js");
/* harmony import */ var _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_8___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_8__);
/* harmony import */ var angular__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! angular */ "./node_modules/angular/index.js");
/* harmony import */ var angular__WEBPACK_IMPORTED_MODULE_9___default = /*#__PURE__*/__webpack_require__.n(angular__WEBPACK_IMPORTED_MODULE_9__);
/* harmony import */ var snjs__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! snjs */ "../snjs/dist/snjs.js");
/* harmony import */ var snjs__WEBPACK_IMPORTED_MODULE_10___default = /*#__PURE__*/__webpack_require__.n(snjs__WEBPACK_IMPORTED_MODULE_10__);
/* harmony import */ var _utils__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! @/utils */ "./app/assets/javascripts/utils.js");
/* harmony import */ var _services_keyboardManager__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! @/services/keyboardManager */ "./app/assets/javascripts/services/keyboardManager.js");
/* harmony import */ var _editor_pug__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! %/editor.pug */ "./app/assets/templates/editor.pug");
/* harmony import */ var _editor_pug__WEBPACK_IMPORTED_MODULE_13___default = /*#__PURE__*/__webpack_require__.n(_editor_pug__WEBPACK_IMPORTED_MODULE_13__);
/* harmony import */ var _Controllers__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! @Controllers */ "./app/assets/javascripts/controllers/index.js");
/* harmony import */ var _state__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! @/state */ "./app/assets/javascripts/state.js");
/* harmony import */ var _strings__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! @/strings */ "./app/assets/javascripts/strings.js");
/* harmony import */ var _services_preferencesManager__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(/*! @/services/preferencesManager */ "./app/assets/javascripts/services/preferencesManager.js");
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_8___default()(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
var NOTE_PREVIEW_CHAR_LIMIT = 80;
var MINIMUM_STATUS_DURATION = 400;
var SAVE_TIMEOUT_DEBOUNCE = 350;
var SAVE_TIMEOUT_NO_DEBOUNCE = 100;
var EDITOR_DEBOUNCE = 200;
var APP_DATA_KEY_PINNED = 'pinned';
var APP_DATA_KEY_LOCKED = 'locked';
var APP_DATA_KEY_ARCHIVED = 'archived';
var APP_DATA_KEY_PREFERS_PLAIN_EDITOR = 'prefersPlainEditor';
var ELEMENT_ID_NOTE_TEXT_EDITOR = 'note-text-editor';
var ELEMENT_ID_NOTE_TITLE_EDITOR = 'note-title-editor';
var ELEMENT_ID_EDITOR_CONTENT = 'editor-content';
var ELEMENT_ID_NOTE_TAGS_COMPONENT_CONTAINER = 'note-tags-component-container';
var DESKTOP_MONOSPACE_FAMILY = "Menlo,Consolas,'DejaVu Sans Mono',monospace";
var WEB_MONOSPACE_FAMILY = "monospace";
var SANS_SERIF_FAMILY = "inherit";
var EditorCtrl =
/*#__PURE__*/
function (_PureCtrl) {
EditorCtrl.$inject = ["$timeout", "$rootScope", "appState", "application", "actionsManager", "desktopManager", "keyboardManager", "preferencesManager", "sessionHistory"];
_babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_7___default()(EditorCtrl, _PureCtrl);
/* @ngInject */
function EditorCtrl($timeout, $rootScope, appState, application, actionsManager, desktopManager, keyboardManager, preferencesManager, sessionHistory
/** Unused below, required to load globally */
) {
var _this;
_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2___default()(this, EditorCtrl);
_this = _babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_4___default()(this, _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_5___default()(EditorCtrl).call(this, $timeout));
_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_8___default()(_babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_6___default()(_this), "editorMenuOnSelect", function (component) {
if (!component || component.area === 'editor-editor') {
/** If plain editor or other editor */
_this.setMenuState('showEditorMenu', false);
var editor = component;
if (_this.state.selectedEditor && editor !== _this.state.selectedEditor) {
_this.disassociateComponentWithCurrentNote(_this.state.selectedEditor);
}
if (editor) {
var prefersPlain = _this.state.note.getAppDataItem(APP_DATA_KEY_PREFERS_PLAIN_EDITOR) === true;
if (prefersPlain) {
_this.state.note.setAppDataItem(APP_DATA_KEY_PREFERS_PLAIN_EDITOR, false);
_this.application.setItemNeedsSync({
item: _this.state.note
});
}
_this.associateComponentWithCurrentNote(editor);
} else {
/** Note prefers plain editor */
if (!_this.state.note.getAppDataItem(APP_DATA_KEY_PREFERS_PLAIN_EDITOR)) {
_this.state.note.setAppDataItem(APP_DATA_KEY_PREFERS_PLAIN_EDITOR, true);
_this.application.setItemNeedsSync({
item: _this.state.note
});
}
_this.reloadFont();
}
_this.setState({
selectedEditor: editor
});
} else if (component.area === 'editor-stack') {
_this.toggleStackComponentForCurrentItem(component);
}
/** Dirtying can happen above */
_this.application.sync();
});
_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_8___default()(_babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_6___default()(_this), "onPanelResizeFinish", function (width, left, isMaxWidth) {
if (isMaxWidth) {
_this.preferencesManager.setUserPrefValue(_services_preferencesManager__WEBPACK_IMPORTED_MODULE_17__["PREF_EDITOR_WIDTH"], null);
} else {
if (width !== undefined && width !== null) {
_this.preferencesManager.setUserPrefValue(_services_preferencesManager__WEBPACK_IMPORTED_MODULE_17__["PREF_EDITOR_WIDTH"], width);
_this.leftResizeControl.setWidth(width);
}
}
if (left !== undefined && left !== null) {
_this.preferencesManager.setUserPrefValue(_services_preferencesManager__WEBPACK_IMPORTED_MODULE_17__["PREF_EDITOR_LEFT"], left);
_this.rightResizeControl.setLeft(left);
}
_this.preferencesManager.syncUserPreferences();
});
_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_8___default()(_babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_6___default()(_this), "onEditorLoad", function (editor) {
_this.desktopManager.redoSearch();
});
_this.$rootScope = $rootScope;
_this.application = application;
_this.appState = appState;
_this.actionsManager = actionsManager;
_this.desktopManager = desktopManager;
_this.keyboardManager = keyboardManager;
_this.preferencesManager = preferencesManager;
_this.state = {
componentStack: [],
editorDebounce: EDITOR_DEBOUNCE,
isDesktop: Object(_utils__WEBPACK_IMPORTED_MODULE_11__["isDesktopApplication"])(),
spellcheck: true,
mutable: {
tagsString: ''
}
};
_this.leftResizeControl = {};
_this.rightResizeControl = {};
_this.addAppStateObserver();
_this.addAppEventObserver();
_this.addSyncStatusObserver();
_this.streamItems();
_this.registerComponentHandler();
_this.registerKeyboardShortcuts();
/** Used by .pug template */
_this.prefKeyMonospace = _services_preferencesManager__WEBPACK_IMPORTED_MODULE_17__["PREF_EDITOR_MONOSPACE_ENABLED"];
_this.prefKeySpellcheck = _services_preferencesManager__WEBPACK_IMPORTED_MODULE_17__["PREF_EDITOR_SPELLCHECK"];
_this.prefKeyMarginResizers = _services_preferencesManager__WEBPACK_IMPORTED_MODULE_17__["PREF_EDITOR_RESIZERS_ENABLED"];
return _this;
}
_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3___default()(EditorCtrl, [{
key: "addAppStateObserver",
value: function addAppStateObserver() {
var _this2 = this;
this.appState.addObserver(function (eventName, data) {
if (eventName === _state__WEBPACK_IMPORTED_MODULE_15__["APP_STATE_EVENT_NOTE_CHANGED"]) {
_this2.handleNoteSelectionChange(_this2.appState.getSelectedNote(), data.previousNote);
} else if (eventName === _state__WEBPACK_IMPORTED_MODULE_15__["APP_STATE_EVENT_PREFERENCES_CHANGED"]) {
_this2.loadPreferences();
}
});
}
}, {
key: "streamItems",
value: function streamItems() {
var _this3 = this;
this.application.streamItems({
contentType: snjs__WEBPACK_IMPORTED_MODULE_10__["CONTENT_TYPE_NOTE"],
stream: function () {
var _stream = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee(_ref) {
var items, source, matchingNote;
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
items = _ref.items, source = _ref.source;
if (_this3.state.note) {
_context.next = 3;
break;
}
return _context.abrupt("return");
case 3:
if (!(_this3.state.note.deleted || _this3.state.note.content.trashed)) {
_context.next = 5;
break;
}
return _context.abrupt("return");
case 5:
if (Object(snjs__WEBPACK_IMPORTED_MODULE_10__["isPayloadSourceRetrieved"])(source)) {
_context.next = 7;
break;
}
return _context.abrupt("return");
case 7:
matchingNote = items.find(function (item) {
return item.uuid === _this3.state.note.uuid;
});
if (matchingNote) {
_context.next = 10;
break;
}
return _context.abrupt("return");
case 10:
_this3.reloadTagsString();
case 11:
case "end":
return _context.stop();
}
}
}, _callee);
}));
function stream(_x) {
return _stream.apply(this, arguments);
}
return stream;
}()
});
this.application.streamItems({
contentType: snjs__WEBPACK_IMPORTED_MODULE_10__["CONTENT_TYPE_TAG"],
stream: function () {
var _stream2 = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee2(_ref2) {
var items, source, _iteratorNormalCompletion, _didIteratorError, _iteratorError, _iterator, _step, tag;
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee2$(_context2) {
while (1) {
switch (_context2.prev = _context2.next) {
case 0:
items = _ref2.items, source = _ref2.source;
if (_this3.state.note) {
_context2.next = 3;
break;
}
return _context2.abrupt("return");
case 3:
_iteratorNormalCompletion = true;
_didIteratorError = false;
_iteratorError = undefined;
_context2.prev = 6;
_iterator = items[Symbol.iterator]();
case 8:
if (_iteratorNormalCompletion = (_step = _iterator.next()).done) {
_context2.next = 16;
break;
}
tag = _step.value;
if (!(!_this3.state.note.savedTagsString || tag.deleted || tag.hasRelationshipWithItem(_this3.state.note))) {
_context2.next = 13;
break;
}
_this3.reloadTagsString();
return _context2.abrupt("break", 16);
case 13:
_iteratorNormalCompletion = true;
_context2.next = 8;
break;
case 16:
_context2.next = 22;
break;
case 18:
_context2.prev = 18;
_context2.t0 = _context2["catch"](6);
_didIteratorError = true;
_iteratorError = _context2.t0;
case 22:
_context2.prev = 22;
_context2.prev = 23;
if (!_iteratorNormalCompletion && _iterator.return != null) {
_iterator.return();
}
case 25:
_context2.prev = 25;
if (!_didIteratorError) {
_context2.next = 28;
break;
}
throw _iteratorError;
case 28:
return _context2.finish(25);
case 29:
return _context2.finish(22);
case 30:
case "end":
return _context2.stop();
}
}
}, _callee2, null, [[6, 18, 22, 30], [23,, 25, 29]]);
}));
function stream(_x2) {
return _stream2.apply(this, arguments);
}
return stream;
}()
});
this.application.streamItems({
contentType: snjs__WEBPACK_IMPORTED_MODULE_10__["CONTENT_TYPE_COMPONENT"],
stream: function () {
var _stream3 = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee3(_ref3) {
var items, source, editors, editor;
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee3$(_context3) {
while (1) {
switch (_context3.prev = _context3.next) {
case 0:
items = _ref3.items, source = _ref3.source;
if (_this3.state.note) {
_context3.next = 3;
break;
}
return _context3.abrupt("return");
case 3:
/** Reload componentStack in case new ones were added or removed */
_this3.reloadComponentStackArray();
/** Observe editor changes to see if the current note should update its editor */
editors = items.filter(function (item) {
return item.isEditor();
});
if (!(editors.length === 0)) {
_context3.next = 7;
break;
}
return _context3.abrupt("return");
case 7:
/** Find the most recent editor for note */
editor = _this3.editorForNote(_this3.state.note);
_this3.setState({
selectedEditor: editor
});
if (!editor) {
_this3.reloadFont();
}
case 10:
case "end":
return _context3.stop();
}
}
}, _callee3);
}));
function stream(_x3) {
return _stream3.apply(this, arguments);
}
return stream;
}()
});
}
}, {
key: "addAppEventObserver",
value: function addAppEventObserver() {
var _this4 = this;
this.application.addEventObserver(function (eventName) {
if (!_this4.state.note) {
return;
}
if (eventName === snjs__WEBPACK_IMPORTED_MODULE_10__["ApplicationEvents"].HighLatencySync) {
_this4.setState({
syncTakingTooLong: true
});
} else if (eventName === snjs__WEBPACK_IMPORTED_MODULE_10__["ApplicationEvents"].CompletedSync) {
_this4.setState({
syncTakingTooLong: false
});
if (_this4.state.note.dirty) {
/** if we're still dirty, don't change status, a sync is likely upcoming. */
} else {
var saved = _this4.state.note.updated_at > _this4.state.note.lastSyncBegan;
var isInErrorState = _this4.state.saveError;
if (isInErrorState || saved) {
_this4.showAllChangesSavedStatus();
}
}
} else if (eventName === snjs__WEBPACK_IMPORTED_MODULE_10__["ApplicationEvents"].FailedSync) {
/**
* Only show error status in editor if the note is dirty.
* Otherwise, it means the originating sync came from somewhere else
* and we don't want to display an error here.
*/
if (_this4.state.note.dirty) {
_this4.showErrorStatus();
}
}
});
}
}, {
key: "handleNoteSelectionChange",
value: function () {
var _handleNoteSelectionChange = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee4(note, previousNote) {
var associatedEditor;
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee4$(_context4) {
while (1) {
switch (_context4.prev = _context4.next) {
case 0:
this.setState({
note: this.appState.getSelectedNote(),
showExtensions: false,
showOptionsMenu: false,
altKeyDown: false,
noteStatus: null
});
if (note) {
_context4.next = 3;
break;
}
return _context4.abrupt("return");
case 3:
associatedEditor = this.editorForNote(note);
if (associatedEditor && associatedEditor !== this.state.selectedEditor) {
/**
* Setting note to not ready will remove the editor from view in a flash,
* so we only want to do this if switching between external editors
*/
this.setState({
noteReady: false,
selectedEditor: associatedEditor
});
} else if (!associatedEditor) {
/** No editor */
this.setState({
selectedEditor: null
});
}
_context4.next = 7;
return this.setState({
noteReady: true
});
case 7:
this.reloadTagsString();
this.loadPreferences();
if (note.dummy) {
this.focusEditor();
}
if (previousNote && previousNote !== note) {
if (previousNote.dummy) {
this.performNoteDeletion(previousNote);
}
}
this.reloadComponentContext();
case 12:
case "end":
return _context4.stop();
}
}
}, _callee4, this);
}));
function handleNoteSelectionChange(_x4, _x5) {
return _handleNoteSelectionChange.apply(this, arguments);
}
return handleNoteSelectionChange;
}()
}, {
key: "addSyncStatusObserver",
value: function addSyncStatusObserver() {
/** @todo */
// this.syncStatusObserver = this.syncManager.
// registerSyncStatusObserver((status) => {
// if (status.localError) {
// this.$timeout(() => {
// this.showErrorStatus({
// message: "Offline Saving Issue",
// desc: "Changes not saved"
// });
// }, 500);
// }
// });
}
}, {
key: "editorForNote",
value: function editorForNote(note) {
return this.componentManager.editorForNote(note);
}
}, {
key: "setMenuState",
value: function setMenuState(menu, state) {
this.setState(_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_8___default()({}, menu, state));
this.closeAllMenus({
exclude: menu
});
}
}, {
key: "toggleMenu",
value: function toggleMenu(menu) {
this.setMenuState(menu, !this.state[menu]);
}
}, {
key: "closeAllMenus",
value: function closeAllMenus() {
var _ref4 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
exclude = _ref4.exclude;
var allMenus = ['showOptionsMenu', 'showEditorMenu', 'showExtensions', 'showSessionHistory'];
var menuState = {};
for (var _i = 0, _allMenus = allMenus; _i < _allMenus.length; _i++) {
var candidate = _allMenus[_i];
if (candidate !== exclude) {
menuState[candidate] = false;
}
}
this.setState(menuState);
}
}, {
key: "hasAvailableExtensions",
value: function hasAvailableExtensions() {
return this.actionsManager.extensionsInContextOfItem(this.state.note).length > 0;
}
}, {
key: "performFirefoxPinnedTabFix",
value: function performFirefoxPinnedTabFix() {
/**
* For Firefox pinned tab issue:
* When a new browser session is started, and SN is in a pinned tab,
* SN is unusable until the tab is reloaded.
*/
if (document.hidden) {
window.location.reload();
}
}
}, {
key: "saveNote",
value: function saveNote(_ref5) {
var _this5 = this;
var bypassDebouncer = _ref5.bypassDebouncer,
updateClientModified = _ref5.updateClientModified,
dontUpdatePreviews = _ref5.dontUpdatePreviews;
this.performFirefoxPinnedTabFix();
var note = this.state.note;
note.dummy = false;
if (note.deleted) {
this.application.alertManager.alert({
text: _strings__WEBPACK_IMPORTED_MODULE_16__["STRING_DELETED_NOTE"]
});
return;
}
if (!this.application.findItem({
uuid: note.uuid
})) {
this.application.alertManager.alert({
text: _strings__WEBPACK_IMPORTED_MODULE_16__["STRING_INVALID_NOTE"]
});
return;
}
this.showSavingStatus();
if (!dontUpdatePreviews) {
var text = note.text || '';
var truncate = text.length > NOTE_PREVIEW_CHAR_LIMIT;
var substring = text.substring(0, NOTE_PREVIEW_CHAR_LIMIT);
var previewPlain = substring + (truncate ? _strings__WEBPACK_IMPORTED_MODULE_16__["STRING_ELLIPSES"] : '');
note.content.preview_plain = previewPlain;
note.content.preview_html = null;
}
this.application.setItemNeedsSync({
item: note,
updateUserModifiedDate: updateClientModified
});
if (this.saveTimeout) {
this.$timeout.cancel(this.saveTimeout);
}
var noDebounce = bypassDebouncer || this.application.noAccount();
var syncDebouceMs = noDebounce ? SAVE_TIMEOUT_NO_DEBOUNCE : SAVE_TIMEOUT_DEBOUNCE;
this.saveTimeout = this.$timeout(function () {
_this5.application.sync();
}, syncDebouceMs);
}
}, {
key: "showSavingStatus",
value: function showSavingStatus() {
this.setStatus({
message: "Saving..."
}, false);
}
}, {
key: "showAllChangesSavedStatus",
value: function showAllChangesSavedStatus() {
this.setState({
saveError: false,
syncTakingTooLong: false
});
var status = "All changes saved";
if (this.application.noAccount()) {
status += " (offline)";
}
this.setStatus({
message: status
});
}
}, {
key: "showErrorStatus",
value: function showErrorStatus(error) {
if (!error) {
error = {
message: "Sync Unreachable",
desc: "Changes saved offline"
};
}
this.setState({
saveError: true,
syncTakingTooLong: false
});
this.setStatus(error);
}
}, {
key: "setStatus",
value: function setStatus(status) {
var _this6 = this;
var wait = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
var waitForMs;
if (!this.state.noteStatus || !this.state.noteStatus.date) {
waitForMs = 0;
} else {
waitForMs = MINIMUM_STATUS_DURATION - (new Date() - this.state.noteStatus.date);
}
if (!wait || waitForMs < 0) {
waitForMs = 0;
}
if (this.statusTimeout) {
this.$timeout.cancel(this.statusTimeout);
}
this.statusTimeout = this.$timeout(function () {
status.date = new Date();
_this6.setState({
noteStatus: status
});
}, waitForMs);
}
}, {
key: "contentChanged",
value: function contentChanged() {
this.saveNote({
updateClientModified: true
});
}
}, {
key: "onTitleEnter",
value: function onTitleEnter($event) {
$event.target.blur();
this.onTitleChange();
this.focusEditor();
}
}, {
key: "onTitleChange",
value: function onTitleChange() {
this.saveNote({
dontUpdatePreviews: true,
updateClientModified: true
});
}
}, {
key: "focusEditor",
value: function focusEditor() {
var element = document.getElementById(ELEMENT_ID_NOTE_TEXT_EDITOR);
if (element) {
this.lastEditorFocusEventSource = _state__WEBPACK_IMPORTED_MODULE_15__["EVENT_SOURCE_SCRIPT"];
element.focus();
}
}
}, {
key: "focusTitle",
value: function focusTitle() {
document.getElementById(ELEMENT_ID_NOTE_TITLE_EDITOR).focus();
}
}, {
key: "clickedTextArea",
value: function clickedTextArea() {
this.setMenuState('showOptionsMenu', false);
}
}, {
key: "onNameFocus",
value: function onNameFocus() {
this.editingName = true;
}
}, {
key: "onContentFocus",
value: function onContentFocus() {
this.appState.editorDidFocus(this.lastEditorFocusEventSource);
this.lastEditorFocusEventSource = null;
}
}, {
key: "onNameBlur",
value: function onNameBlur() {
this.editingName = false;
}
}, {
key: "selectedMenuItem",
value: function selectedMenuItem(hide) {
if (hide) {
this.setMenuState('showOptionsMenu', false);
}
}
}, {
key: "deleteNote",
value: function () {
var _deleteNote = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee5(permanently) {
var _this7 = this;
var run, requiresPrivilege;
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee5$(_context5) {
while (1) {
switch (_context5.prev = _context5.next) {
case 0:
if (!this.state.note.dummy) {
_context5.next = 3;
break;
}
this.application.alertManager.alert({
text: _strings__WEBPACK_IMPORTED_MODULE_16__["STRING_DELETE_PLACEHOLDER_ATTEMPT"]
});
return _context5.abrupt("return");
case 3:
run = function run() {
if (_this7.state.note.locked) {
_this7.application.alertManager.alert({
text: _strings__WEBPACK_IMPORTED_MODULE_16__["STRING_DELETE_LOCKED_ATTEMPT"]
});
return;
}
var title = _this7.state.note.safeTitle().length ? "'".concat(_this7.state.note.title, "'") : "this note";
var text = Object(_strings__WEBPACK_IMPORTED_MODULE_16__["StringDeleteNote"])({
title: title,
permanently: permanently
});
_this7.application.alertManager.confirm({
text: text,
destructive: true,
onConfirm: function onConfirm() {
if (permanently) {
_this7.performNoteDeletion(_this7.state.note);
} else {
_this7.state.note.content.trashed = true;
_this7.saveNote({
bypassDebouncer: true,
dontUpdatePreviews: true
});
}
_this7.appState.setSelectedNote(null);
_this7.setMenuState('showOptionsMenu', false);
}
});
};
_context5.next = 6;
return this.application.privilegesManager.actionRequiresPrivilege(snjs__WEBPACK_IMPORTED_MODULE_10__["ProtectedActions"].DeleteNote);
case 6:
requiresPrivilege = _context5.sent;
if (requiresPrivilege) {
this.godService.presentPrivilegesModal(snjs__WEBPACK_IMPORTED_MODULE_10__["ProtectedActions"].DeleteNote, function () {
run();
});
} else {
run();
}
case 8:
case "end":
return _context5.stop();
}
}
}, _callee5, this);
}));
function deleteNote(_x6) {
return _deleteNote.apply(this, arguments);
}
return deleteNote;
}()
}, {
key: "performNoteDeletion",
value: function performNoteDeletion(note) {
this.application.deleteItem({
item: note
});
if (note === this.state.note) {
this.setState({
note: null
});
}
if (note.dummy) {
this.application.deleteItemLocally({
item: note
});
return;
}
this.application.sync();
}
}, {
key: "restoreTrashedNote",
value: function restoreTrashedNote() {
this.state.note.content.trashed = false;
this.saveNote({
bypassDebouncer: true,
dontUpdatePreviews: true
});
this.appState.setSelectedNote(null);
}
}, {
key: "deleteNotePermanantely",
value: function deleteNotePermanantely() {
this.deleteNote(true);
}
}, {
key: "getTrashCount",
value: function getTrashCount() {
return this.application.getTrashedItems().length;
}
}, {
key: "emptyTrash",
value: function emptyTrash() {
var _this8 = this;
var count = this.getTrashCount();
this.application.alertManager.confirm({
text: Object(_strings__WEBPACK_IMPORTED_MODULE_16__["StringEmptyTrash"])({
count: count
}),
destructive: true,
onConfirm: function onConfirm() {
_this8.application.emptyTrash();
_this8.application.sync();
}
});
}
}, {
key: "togglePin",
value: function togglePin() {
this.state.note.setAppDataItem(APP_DATA_KEY_PINNED, !this.state.note.pinned);
this.saveNote({
bypassDebouncer: true,
dontUpdatePreviews: true
});
}
}, {
key: "toggleLockNote",
value: function toggleLockNote() {
this.state.note.setAppDataItem(APP_DATA_KEY_LOCKED, !this.state.note.locked);
this.saveNote({
bypassDebouncer: true,
dontUpdatePreviews: true
});
}
}, {
key: "toggleProtectNote",
value: function toggleProtectNote() {
var _this9 = this;
this.state.note.content.protected = !this.state.note.content.protected;
this.saveNote({
bypassDebouncer: true,
dontUpdatePreviews: true
});
/** Show privileges manager if protection is not yet set up */
this.application.privilegesManager.actionHasPrivilegesConfigured(snjs__WEBPACK_IMPORTED_MODULE_10__["ProtectedActions"].ViewProtectedNotes).then(function (configured) {
if (!configured) {
_this9.godService.presentPrivilegesManagementModal();
}
});
}
}, {
key: "toggleNotePreview",
value: function toggleNotePreview() {
this.state.note.content.hidePreview = !this.state.note.content.hidePreview;
this.saveNote({
bypassDebouncer: true,
dontUpdatePreviews: true
});
}
}, {
key: "toggleArchiveNote",
value: function toggleArchiveNote() {
this.state.note.setAppDataItem(APP_DATA_KEY_ARCHIVED, !this.state.note.archived);
this.saveNote({
bypassDebouncer: true,
dontUpdatePreviews: true
});
}
}, {
key: "reloadTagsString",
value: function reloadTagsString() {
this.setState({
mutable: _objectSpread({}, this.state.mutable, {
tagsString: this.state.note.tagsString()
})
});
}
}, {
key: "addTag",
value: function addTag(tag) {
var strings = this.state.note.tags.map(function (currentTag) {
return currentTag.title;
});
strings.push(tag.title);
this.saveTags({
strings: strings
});
}
}, {
key: "removeTag",
value: function removeTag(tag) {
var strings = this.state.note.tags.map(function (currentTag) {
return currentTag.title;
}).filter(function (title) {
return title !== tag.title;
});
this.saveTags({
strings: strings
});
}
}, {
key: "saveTags",
value: function saveTags() {
var _ref6 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
strings = _ref6.strings;
if (!strings && this.state.mutable.tagsString === this.state.note.tagsString()) {
return;
}
if (!strings) {
strings = this.state.mutable.tagsString.split('#').filter(function (string) {
return string.length > 0;
}).map(function (string) {
return string.trim();
});
}
this.state.note.dummy = false;
var toRemove = [];
var _iteratorNormalCompletion2 = true;
var _didIteratorError2 = false;
var _iteratorError2 = undefined;
try {
for (var _iterator2 = this.state.note.tags[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
var tag = _step2.value;
if (strings.indexOf(tag.title) === -1) {
toRemove.push(tag);
}
}
} catch (err) {
_didIteratorError2 = true;
_iteratorError2 = err;
} finally {
try {
if (!_iteratorNormalCompletion2 && _iterator2.return != null) {
_iterator2.return();
}
} finally {
if (_didIteratorError2) {
throw _iteratorError2;
}
}
}
for (var _i2 = 0, _toRemove = toRemove; _i2 < _toRemove.length; _i2++) {
var tagToRemove = _toRemove[_i2];
tagToRemove.removeItemAsRelationship(this.state.note);
}
this.application.setItemsNeedsSync({
items: toRemove
});
var tags = [];
var _iteratorNormalCompletion3 = true;
var _didIteratorError3 = false;
var _iteratorError3 = undefined;
try {
for (var _iterator3 = strings[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) {
var tagString = _step3.value;
var existingRelationship = _.find(this.state.note.tags, {
title: tagString
});
if (!existingRelationship) {
tags.push(this.application.findOrCreateTag({
title: tagString
}));
}
}
} catch (err) {
_didIteratorError3 = true;
_iteratorError3 = err;
} finally {
try {
if (!_iteratorNormalCompletion3 && _iterator3.return != null) {
_iterator3.return();
}
} finally {
if (_didIteratorError3) {
throw _iteratorError3;
}
}
}
for (var _i3 = 0, _tags = tags; _i3 < _tags.length; _i3++) {
var _tag = _tags[_i3];
_tag.addItemAsRelationship(this.state.note);
}
this.application.saveItems({
items: tags
});
this.reloadTagsString();
}
}, {
key: "loadPreferences",
value: function loadPreferences() {
var monospaceEnabled = this.preferencesManager.getValue(_services_preferencesManager__WEBPACK_IMPORTED_MODULE_17__["PREF_EDITOR_MONOSPACE_ENABLED"], true);
var spellcheck = this.preferencesManager.getValue(_services_preferencesManager__WEBPACK_IMPORTED_MODULE_17__["PREF_EDITOR_SPELLCHECK"], true);
var marginResizersEnabled = this.preferencesManager.getValue(_services_preferencesManager__WEBPACK_IMPORTED_MODULE_17__["PREF_EDITOR_RESIZERS_ENABLED"], true);
this.setState({
monospaceEnabled: monospaceEnabled,
spellcheck: spellcheck,
marginResizersEnabled: marginResizersEnabled
});
if (!document.getElementById(ELEMENT_ID_EDITOR_CONTENT)) {
/** Elements have not yet loaded due to ng-if around wrapper */
return;
}
this.reloadFont();
if (this.state.marginResizersEnabled) {
var width = this.preferencesManager.getValue(_services_preferencesManager__WEBPACK_IMPORTED_MODULE_17__["PREF_EDITOR_WIDTH"], null);
if (width != null) {
this.leftResizeControl.setWidth(width);
this.rightResizeControl.setWidth(width);
}
var left = this.preferencesManager.getValue(_services_preferencesManager__WEBPACK_IMPORTED_MODULE_17__["PREF_EDITOR_LEFT"], null);
if (left != null) {
this.leftResizeControl.setLeft(left);
this.rightResizeControl.setLeft(left);
}
}
}
}, {
key: "reloadFont",
value: function reloadFont() {
var editor = document.getElementById(ELEMENT_ID_NOTE_TEXT_EDITOR);
if (!editor) {
return;
}
if (this.state.monospaceEnabled) {
if (this.state.isDesktop) {
editor.style.fontFamily = DESKTOP_MONOSPACE_FAMILY;
} else {
editor.style.fontFamily = WEB_MONOSPACE_FAMILY;
}
} else {
editor.style.fontFamily = SANS_SERIF_FAMILY;
}
}
}, {
key: "toggleKey",
value: function () {
var _toggleKey = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee6(key) {
var _this10 = this;
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee6$(_context6) {
while (1) {
switch (_context6.prev = _context6.next) {
case 0:
this[key] = !this[key];
this.preferencesManager.setUserPrefValue(key, this[key], true);
this.reloadFont();
if (!(key === _services_preferencesManager__WEBPACK_IMPORTED_MODULE_17__["PREF_EDITOR_SPELLCHECK"])) {
_context6.next = 10;
break;
}
_context6.next = 6;
return this.setState({
noteReady: false
});
case 6:
this.setState({
noteReady: true
});
this.reloadFont();
_context6.next = 11;
break;
case 10:
if (key === _services_preferencesManager__WEBPACK_IMPORTED_MODULE_17__["PREF_EDITOR_RESIZERS_ENABLED"] && this[key] === true) {
this.$timeout(function () {
_this10.leftResizeControl.flash();
_this10.rightResizeControl.flash();
});
}
case 11:
case "end":
return _context6.stop();
}
}
}, _callee6, this);
}));
function toggleKey(_x7) {
return _toggleKey.apply(this, arguments);
}
return toggleKey;
}()
/** @components */
}, {
key: "registerComponentHandler",
value: function registerComponentHandler() {
var _this11 = this;
this.componentManager.registerHandler({
identifier: 'editor',
areas: ['note-tags', 'editor-stack', 'editor-editor'],
activationHandler: function activationHandler(component) {
if (component.area === 'note-tags') {
_this11.setState({
tagsComponent: component.active ? component : null
});
} else if (component.area === 'editor-editor') {
if (component === _this11.state.selectedEditor && !component.active) {
_this11.setState({
selectedEditor: null
});
} else if (_this11.state.selectedEditor) {
if (_this11.state.selectedEditor.active && _this11.state.note) {
if (component.isExplicitlyEnabledForItem(_this11.state.note) && !_this11.state.selectedEditor.isExplicitlyEnabledForItem(_this11.state.note)) {
_this11.setState({
selectedEditor: component
});
}
}
} else if (_this11.state.note) {
var enableable = component.isExplicitlyEnabledForItem(_this11.state.note) || component.isDefaultEditor();
if (component.active && enableable) {
_this11.setState({
selectedEditor: component
});
} else {
/**
* Not a candidate, and no qualified editor.
* Disable the current editor.
*/
_this11.setState({
selectedEditor: null
});
}
}
} else if (component.area === 'editor-stack') {
_this11.reloadComponentContext();
}
},
contextRequestHandler: function contextRequestHandler(component) {
if (component === _this11.state.selectedEditor || component === _this11.state.tagsComponent || _this11.state.componentStack.includes(component)) {
return _this11.state.note;
}
},
focusHandler: function focusHandler(component, focused) {
if (component.isEditor() && focused) {
_this11.closeAllMenus();
}
},
actionHandler: function actionHandler(component, action, data) {
if (action === 'set-size') {
var setSize = function setSize(element, size) {
var widthString = typeof size.width === 'string' ? size.width : "".concat(data.width, "px");
var heightString = typeof size.height === 'string' ? size.height : "".concat(data.height, "px");
element.setAttribute('style', "width: ".concat(widthString, "; height: ").concat(heightString, ";"));
};
if (data.type === 'container') {
if (component.area === 'note-tags') {
var container = document.getElementById(ELEMENT_ID_NOTE_TAGS_COMPONENT_CONTAINER);
setSize(container, data);
}
}
} else if (action === 'associate-item') {
if (data.item.content_type === 'Tag') {
var tag = _this11.application.findItem({
uuid: data.item.uuid
});
_this11.addTag(tag);
}
} else if (action === 'deassociate-item') {
var _tag2 = _this11.application.findItem({
uuid: data.item.uuid
});
_this11.removeTag(_tag2);
} else if (action === 'save-items') {
var includesNote = data.items.map(function (item) {
return item.uuid;
}).includes(_this11.state.note.uuid);
if (includesNote) {
_this11.showSavingStatus();
}
}
}
});
}
}, {
key: "reloadComponentStackArray",
value: function reloadComponentStackArray() {
var components = this.componentManager.componentsForArea('editor-stack').sort(function (a, b) {
return a.name.toLowerCase() < b.name.toLowerCase() ? -1 : 1;
});
this.setState({
componentStack: components
});
}
}, {
key: "reloadComponentContext",
value: function reloadComponentContext() {
this.reloadComponentStackArray();
if (this.state.note) {
var _iteratorNormalCompletion4 = true;
var _didIteratorError4 = false;
var _iteratorError4 = undefined;
try {
for (var _iterator4 = this.state.componentStack[Symbol.iterator](), _step4; !(_iteratorNormalCompletion4 = (_step4 = _iterator4.next()).done); _iteratorNormalCompletion4 = true) {
var component = _step4.value;
if (component.active) {
this.componentManager.setComponentHidden(component, !component.isExplicitlyEnabledForItem(this.state.note));
}
}
} catch (err) {
_didIteratorError4 = true;
_iteratorError4 = err;
} finally {
try {
if (!_iteratorNormalCompletion4 && _iterator4.return != null) {
_iterator4.return();
}
} finally {
if (_didIteratorError4) {
throw _iteratorError4;
}
}
}
}
this.componentManager.contextItemDidChangeInArea('note-tags');
this.componentManager.contextItemDidChangeInArea('editor-stack');
this.componentManager.contextItemDidChangeInArea('editor-editor');
}
}, {
key: "toggleStackComponentForCurrentItem",
value: function toggleStackComponentForCurrentItem(component) {
if (component.hidden || !component.active) {
this.componentManager.setComponentHidden(component, false);
this.associateComponentWithCurrentNote(component);
if (!component.active) {
this.componentManager.activateComponent(component);
}
this.componentManager.contextItemDidChangeInArea('editor-stack');
} else {
this.componentManager.setComponentHidden(component, true);
this.disassociateComponentWithCurrentNote(component);
}
}
}, {
key: "disassociateComponentWithCurrentNote",
value: function disassociateComponentWithCurrentNote(component) {
var _this12 = this;
component.associatedItemIds = component.associatedItemIds.filter(function (id) {
return id !== _this12.state.note.uuid;
});
if (!component.disassociatedItemIds.includes(this.state.note.uuid)) {
component.disassociatedItemIds.push(this.state.note.uuid);
}
this.application.saveItem({
item: component
});
}
}, {
key: "associateComponentWithCurrentNote",
value: function associateComponentWithCurrentNote(component) {
var _this13 = this;
component.disassociatedItemIds = component.disassociatedItemIds.filter(function (id) {
return id !== _this13.state.note.uuid;
});
if (!component.associatedItemIds.includes(this.state.note.uuid)) {
component.associatedItemIds.push(this.state.note.uuid);
}
this.application.saveItem({
item: component
});
}
}, {
key: "registerKeyboardShortcuts",
value: function registerKeyboardShortcuts() {
var _this14 = this;
this.altKeyObserver = this.keyboardManager.addKeyObserver({
modifiers: [_services_keyboardManager__WEBPACK_IMPORTED_MODULE_12__["KeyboardManager"].KeyModifierAlt],
onKeyDown: function onKeyDown() {
_this14.setState({
altKeyDown: true
});
},
onKeyUp: function onKeyUp() {
_this14.setState({
altKeyDown: false
});
}
});
this.trashKeyObserver = this.keyboardManager.addKeyObserver({
key: _services_keyboardManager__WEBPACK_IMPORTED_MODULE_12__["KeyboardManager"].KeyBackspace,
notElementIds: [ELEMENT_ID_NOTE_TEXT_EDITOR, ELEMENT_ID_NOTE_TITLE_EDITOR],
modifiers: [_services_keyboardManager__WEBPACK_IMPORTED_MODULE_12__["KeyboardManager"].KeyModifierMeta],
onKeyDown: function onKeyDown() {
_this14.deleteNote();
}
});
this.deleteKeyObserver = this.keyboardManager.addKeyObserver({
key: _services_keyboardManager__WEBPACK_IMPORTED_MODULE_12__["KeyboardManager"].KeyBackspace,
modifiers: [_services_keyboardManager__WEBPACK_IMPORTED_MODULE_12__["KeyboardManager"].KeyModifierMeta, _services_keyboardManager__WEBPACK_IMPORTED_MODULE_12__["KeyboardManager"].KeyModifierShift, _services_keyboardManager__WEBPACK_IMPORTED_MODULE_12__["KeyboardManager"].KeyModifierAlt],
onKeyDown: function onKeyDown(event) {
event.preventDefault();
_this14.deleteNote(true);
}
});
}
}, {
key: "onSystemEditorLoad",
value: function onSystemEditorLoad() {
var _this15 = this;
if (this.loadedTabListener) {
return;
}
this.loadedTabListener = true;
/**
* Insert 4 spaces when a tab key is pressed,
* only used when inside of the text editor.
* If the shift key is pressed first, this event is
* not fired.
*/
var editor = document.getElementById(ELEMENT_ID_NOTE_TEXT_EDITOR);
this.tabObserver = this.keyboardManager.addKeyObserver({
element: editor,
key: _services_keyboardManager__WEBPACK_IMPORTED_MODULE_12__["KeyboardManager"].KeyTab,
onKeyDown: function onKeyDown(event) {
if (_this15.state.note.locked || event.shiftKey) {
return;
}
event.preventDefault();
/** Using document.execCommand gives us undo support */
var insertSuccessful = document.execCommand('insertText', false, '\t');
if (!insertSuccessful) {
/** document.execCommand works great on Chrome/Safari but not Firefox */
var start = editor.selectionStart;
var end = editor.selectionEnd;
var spaces = ' ';
/** Insert 4 spaces */
editor.value = editor.value.substring(0, start) + spaces + editor.value.substring(end);
/** Place cursor 4 spaces away from where the tab key was pressed */
editor.selectionStart = editor.selectionEnd = start + 4;
}
var note = _this15.state.note;
note.text = editor.value;
_this15.setState({
note: note
});
_this15.saveNote({
bypassDebouncer: true
});
}
});
/**
* Handles when the editor is destroyed,
* (and not when our controller is destroyed.)
*/
angular__WEBPACK_IMPORTED_MODULE_9___default.a.element(editor).on('$destroy', function () {
if (_this15.tabObserver) {
_this15.keyboardManager.removeKeyObserver(_this15.tabObserver);
_this15.loadedTabListener = false;
}
});
}
}]);
return EditorCtrl;
}(_Controllers__WEBPACK_IMPORTED_MODULE_14__["PureCtrl"]);
var EditorPanel = function EditorPanel() {
_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2___default()(this, EditorPanel);
this.restrict = 'E';
this.scope = {};
this.template = _editor_pug__WEBPACK_IMPORTED_MODULE_13___default.a;
this.replace = true;
this.controller = EditorCtrl;
this.controllerAs = 'self';
this.bindToController = true;
};
/***/ }),
/***/ "./app/assets/javascripts/controllers/footer.js":
/*!******************************************************!*\
!*** ./app/assets/javascripts/controllers/footer.js ***!
\******************************************************/
/*! exports provided: Footer */
/***/ (function(module, exports) {
throw new Error("Module build failed (from ./node_modules/babel-loader/lib/index.js):\nSyntaxError: /Users/mo/Desktop/sn/dev/web/app/assets/javascripts/controllers/footer.js: Unexpected token, expected \",\" (162:4)\n\n\u001b[0m \u001b[90m 160 | \u001b[39m }\u001b[0m\n\u001b[0m \u001b[90m 161 | \u001b[39m }\u001b[0m\n\u001b[0m\u001b[31m\u001b[1m>\u001b[22m\u001b[39m\u001b[90m 162 | \u001b[39m )\u001b[33m;\u001b[39m\u001b[0m\n\u001b[0m \u001b[90m | \u001b[39m \u001b[31m\u001b[1m^\u001b[22m\u001b[39m\u001b[0m\n\u001b[0m \u001b[90m 163 | \u001b[39m }\u001b[0m\n\u001b[0m \u001b[90m 164 | \u001b[39m\u001b[0m\n\u001b[0m \u001b[90m 165 | \u001b[39m registerComponentHandler() {\u001b[0m\n at Parser.raise (/Users/mo/Desktop/sn/dev/web/node_modules/@babel/core/node_modules/@babel/parser/lib/index.js:7017:17)\n at Parser.unexpected (/Users/mo/Desktop/sn/dev/web/node_modules/@babel/core/node_modules/@babel/parser/lib/index.js:8395:16)\n at Parser.expect (/Users/mo/Desktop/sn/dev/web/node_modules/@babel/core/node_modules/@babel/parser/lib/index.js:8381:28)\n at Parser.parseObj (/Users/mo/Desktop/sn/dev/web/node_modules/@babel/core/node_modules/@babel/parser/lib/index.js:9982:14)\n at Parser.parseExprAtom (/Users/mo/Desktop/sn/dev/web/node_modules/@babel/core/node_modules/@babel/parser/lib/index.js:9616:28)\n at Parser.parseExprSubscripts (/Users/mo/Desktop/sn/dev/web/node_modules/@babel/core/node_modules/@babel/parser/lib/index.js:9259:23)\n at Parser.parseMaybeUnary (/Users/mo/Desktop/sn/dev/web/node_modules/@babel/core/node_modules/@babel/parser/lib/index.js:9239:21)\n at Parser.parseExprOps (/Users/mo/Desktop/sn/dev/web/node_modules/@babel/core/node_modules/@babel/parser/lib/index.js:9109:23)\n at Parser.parseMaybeConditional (/Users/mo/Desktop/sn/dev/web/node_modules/@babel/core/node_modules/@babel/parser/lib/index.js:9082:23)\n at Parser.parseMaybeAssign (/Users/mo/Desktop/sn/dev/web/node_modules/@babel/core/node_modules/@babel/parser/lib/index.js:9037:21)\n at Parser.parseExprListItem (/Users/mo/Desktop/sn/dev/web/node_modules/@babel/core/node_modules/@babel/parser/lib/index.js:10327:18)\n at Parser.parseCallExpressionArguments (/Users/mo/Desktop/sn/dev/web/node_modules/@babel/core/node_modules/@babel/parser/lib/index.js:9440:22)\n at Parser.parseSubscript (/Users/mo/Desktop/sn/dev/web/node_modules/@babel/core/node_modules/@babel/parser/lib/index.js:9346:31)\n at Parser.parseSubscripts (/Users/mo/Desktop/sn/dev/web/node_modules/@babel/core/node_modules/@babel/parser/lib/index.js:9276:19)\n at Parser.parseExprSubscripts (/Users/mo/Desktop/sn/dev/web/node_modules/@babel/core/node_modules/@babel/parser/lib/index.js:9265:17)\n at Parser.parseMaybeUnary (/Users/mo/Desktop/sn/dev/web/node_modules/@babel/core/node_modules/@babel/parser/lib/index.js:9239:21)\n at Parser.parseExprOps (/Users/mo/Desktop/sn/dev/web/node_modules/@babel/core/node_modules/@babel/parser/lib/index.js:9109:23)\n at Parser.parseMaybeConditional (/Users/mo/Desktop/sn/dev/web/node_modules/@babel/core/node_modules/@babel/parser/lib/index.js:9082:23)\n at Parser.parseMaybeAssign (/Users/mo/Desktop/sn/dev/web/node_modules/@babel/core/node_modules/@babel/parser/lib/index.js:9037:21)\n at Parser.parseExpression (/Users/mo/Desktop/sn/dev/web/node_modules/@babel/core/node_modules/@babel/parser/lib/index.js:8989:23)\n at Parser.parseStatementContent (/Users/mo/Desktop/sn/dev/web/node_modules/@babel/core/node_modules/@babel/parser/lib/index.js:10819:23)\n at Parser.parseStatement (/Users/mo/Desktop/sn/dev/web/node_modules/@babel/core/node_modules/@babel/parser/lib/index.js:10690:17)\n at Parser.parseBlockOrModuleBlockBody (/Users/mo/Desktop/sn/dev/web/node_modules/@babel/core/node_modules/@babel/parser/lib/index.js:11264:25)\n at Parser.parseBlockBody (/Users/mo/Desktop/sn/dev/web/node_modules/@babel/core/node_modules/@babel/parser/lib/index.js:11251:10)\n at Parser.parseBlock (/Users/mo/Desktop/sn/dev/web/node_modules/@babel/core/node_modules/@babel/parser/lib/index.js:11235:10)\n at Parser.parseFunctionBody (/Users/mo/Desktop/sn/dev/web/node_modules/@babel/core/node_modules/@babel/parser/lib/index.js:10252:24)\n at Parser.parseFunctionBodyAndFinish (/Users/mo/Desktop/sn/dev/web/node_modules/@babel/core/node_modules/@babel/parser/lib/index.js:10222:10)\n at Parser.parseMethod (/Users/mo/Desktop/sn/dev/web/node_modules/@babel/core/node_modules/@babel/parser/lib/index.js:10187:10)\n at Parser.pushClassMethod (/Users/mo/Desktop/sn/dev/web/node_modules/@babel/core/node_modules/@babel/parser/lib/index.js:11668:30)\n at Parser.parseClassMemberWithIsStatic (/Users/mo/Desktop/sn/dev/web/node_modules/@babel/core/node_modules/@babel/parser/lib/index.js:11585:12)");
/***/ }),
/***/ "./app/assets/javascripts/controllers/index.js":
/*!*****************************************************!*\
!*** ./app/assets/javascripts/controllers/index.js ***!
\*****************************************************/
/*! exports provided: PureCtrl, EditorPanel, Footer, NotesPanel, TagsPanel, Root, LockScreen */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _abstract_pure_ctrl__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./abstract/pure_ctrl */ "./app/assets/javascripts/controllers/abstract/pure_ctrl.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PureCtrl", function() { return _abstract_pure_ctrl__WEBPACK_IMPORTED_MODULE_0__["PureCtrl"]; });
/* harmony import */ var _editor__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./editor */ "./app/assets/javascripts/controllers/editor.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "EditorPanel", function() { return _editor__WEBPACK_IMPORTED_MODULE_1__["EditorPanel"]; });
/* harmony import */ var _footer__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./footer */ "./app/assets/javascripts/controllers/footer.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Footer", function() { return _footer__WEBPACK_IMPORTED_MODULE_2__["Footer"]; });
/* harmony import */ var _notes_notes__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./notes/notes */ "./app/assets/javascripts/controllers/notes/notes.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "NotesPanel", function() { return _notes_notes__WEBPACK_IMPORTED_MODULE_3__["NotesPanel"]; });
/* harmony import */ var _tags__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./tags */ "./app/assets/javascripts/controllers/tags.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "TagsPanel", function() { return _tags__WEBPACK_IMPORTED_MODULE_4__["TagsPanel"]; });
/* harmony import */ var _root__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./root */ "./app/assets/javascripts/controllers/root.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Root", function() { return _root__WEBPACK_IMPORTED_MODULE_5__["Root"]; });
/* harmony import */ var _lockScreen__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./lockScreen */ "./app/assets/javascripts/controllers/lockScreen.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "LockScreen", function() { return _lockScreen__WEBPACK_IMPORTED_MODULE_6__["LockScreen"]; });
/***/ }),
/***/ "./app/assets/javascripts/controllers/lockScreen.js":
/*!**********************************************************!*\
!*** ./app/assets/javascripts/controllers/lockScreen.js ***!
\**********************************************************/
/*! exports provided: LockScreen */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "LockScreen", function() { return LockScreen; });
/* harmony import */ var _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/regenerator */ "./node_modules/@babel/runtime/regenerator/index.js");
/* harmony import */ var _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/helpers/asyncToGenerator */ "./node_modules/@babel/runtime/helpers/asyncToGenerator.js");
/* harmony import */ var _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "./node_modules/@babel/runtime/helpers/classCallCheck.js");
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @babel/runtime/helpers/createClass */ "./node_modules/@babel/runtime/helpers/createClass.js");
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var _lock_screen_pug__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! %/lock-screen.pug */ "./app/assets/templates/lock-screen.pug");
/* harmony import */ var _lock_screen_pug__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(_lock_screen_pug__WEBPACK_IMPORTED_MODULE_4__);
/* harmony import */ var _state__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! @/state */ "./app/assets/javascripts/state.js");
var ELEMENT_ID_PASSCODE_INPUT = 'passcode-input';
var LockScreenCtrl =
/*#__PURE__*/
function () {
LockScreenCtrl.$inject = ["$scope", "alertManager", "application", "appState"];
/* @ngInject */
function LockScreenCtrl($scope, alertManager, application, appState) {
_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2___default()(this, LockScreenCtrl);
this.$scope = $scope;
this.alertManager = alertManager;
this.application = application;
this.appState = appState;
this.formData = {};
this.addVisibilityObserver();
this.addDestroyHandler();
}
_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3___default()(LockScreenCtrl, [{
key: "addDestroyHandler",
value: function addDestroyHandler() {
var _this = this;
this.$scope.$on('$destroy', function () {
_this.unregisterObserver();
});
}
}, {
key: "addVisibilityObserver",
value: function addVisibilityObserver() {
var _this2 = this;
this.unregisterObserver = this.appState.addObserver(function (eventName, data) {
if (eventName === _state__WEBPACK_IMPORTED_MODULE_5__["APP_STATE_EVENT_WINDOW_DID_FOCUS"]) {
var input = _this2.passcodeInput;
if (input) {
input.focus();
}
}
});
}
}, {
key: "submitPasscodeForm",
value: function () {
var _submitPasscodeForm = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee($event) {
var _this3 = this;
var success;
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
if (!(!this.formData.passcode || this.formData.passcode.length === 0)) {
_context.next = 2;
break;
}
return _context.abrupt("return");
case 2:
this.passcodeInput.blur();
_context.next = 5;
return this.onValue()(this.formData.passcode);
case 5:
success = _context.sent;
if (!success) {
this.alertManager.alert({
text: "Invalid passcode. Please try again.",
onClose: function onClose() {
_this3.passcodeInput.focus();
}
});
}
case 7:
case "end":
return _context.stop();
}
}
}, _callee, this);
}));
function submitPasscodeForm(_x) {
return _submitPasscodeForm.apply(this, arguments);
}
return submitPasscodeForm;
}()
}, {
key: "forgotPasscode",
value: function forgotPasscode() {
this.formData.showRecovery = true;
}
}, {
key: "beginDeleteData",
value: function beginDeleteData() {
var _this4 = this;
this.alertManager.confirm({
text: "Are you sure you want to clear all local data?",
destructive: true,
onConfirm: function () {
var _onConfirm = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee2() {
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee2$(_context2) {
while (1) {
switch (_context2.prev = _context2.next) {
case 0:
_context2.next = 2;
return _this4.application.signOut();
case 2:
_context2.next = 4;
return _this4.application.restart();
case 4:
case "end":
return _context2.stop();
}
}
}, _callee2);
}));
function onConfirm() {
return _onConfirm.apply(this, arguments);
}
return onConfirm;
}()
});
}
}, {
key: "passcodeInput",
get: function get() {
return document.getElementById(ELEMENT_ID_PASSCODE_INPUT);
}
}]);
return LockScreenCtrl;
}();
var LockScreen = function LockScreen() {
_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2___default()(this, LockScreen);
this.restrict = 'E';
this.template = _lock_screen_pug__WEBPACK_IMPORTED_MODULE_4___default.a;
this.controller = LockScreenCtrl;
this.controllerAs = 'ctrl';
this.bindToController = true;
this.scope = {
onValue: '&'
};
};
/***/ }),
/***/ "./app/assets/javascripts/controllers/notes/note_utils.js":
/*!****************************************************************!*\
!*** ./app/assets/javascripts/controllers/notes/note_utils.js ***!
\****************************************************************/
/*! exports provided: SORT_KEY_CREATED_AT, SORT_KEY_UPDATED_AT, SORT_KEY_CLIENT_UPDATED_AT, SORT_KEY_TITLE, filterAndSortNotes, filterNotes, sortNotes */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SORT_KEY_CREATED_AT", function() { return SORT_KEY_CREATED_AT; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SORT_KEY_UPDATED_AT", function() { return SORT_KEY_UPDATED_AT; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SORT_KEY_CLIENT_UPDATED_AT", function() { return SORT_KEY_CLIENT_UPDATED_AT; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SORT_KEY_TITLE", function() { return SORT_KEY_TITLE; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "filterAndSortNotes", function() { return filterAndSortNotes; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "filterNotes", function() { return filterNotes; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "sortNotes", function() { return sortNotes; });
var SORT_KEY_CREATED_AT = 'created_at';
var SORT_KEY_UPDATED_AT = 'updated_at';
var SORT_KEY_CLIENT_UPDATED_AT = 'client_updated_at';
var SORT_KEY_TITLE = 'title';
function filterAndSortNotes(_ref) {
var notes = _ref.notes,
selectedTag = _ref.selectedTag,
showArchived = _ref.showArchived,
hidePinned = _ref.hidePinned,
filterText = _ref.filterText,
sortBy = _ref.sortBy,
reverse = _ref.reverse;
var filtered = filterNotes({
notes: notes,
selectedTag: selectedTag,
showArchived: showArchived,
hidePinned: hidePinned,
filterText: filterText
});
var sorted = sortNotes({
notes: filtered,
sortBy: sortBy,
reverse: reverse
});
return sorted;
}
function filterNotes(_ref2) {
var notes = _ref2.notes,
selectedTag = _ref2.selectedTag,
showArchived = _ref2.showArchived,
hidePinned = _ref2.hidePinned,
filterText = _ref2.filterText;
return notes.filter(function (note) {
var canShowArchived = showArchived;
var canShowPinned = !hidePinned;
var isTrash = selectedTag.content.isTrashTag;
if (!isTrash && note.content.trashed) {
return false;
}
var isSmartTag = selectedTag.isSmartTag();
if (isSmartTag) {
canShowArchived = canShowArchived || selectedTag.content.isArchiveTag || isTrash;
}
if (note.archived && !canShowArchived || note.pinned && !canShowPinned) {
return false;
}
return noteMatchesQuery({
note: note,
query: filterText
});
});
}
function noteMatchesQuery(_ref3) {
var note = _ref3.note,
query = _ref3.query;
if (query.length === 0) {
return true;
}
var title = note.safeTitle().toLowerCase();
var text = note.safeText().toLowerCase();
var lowercaseText = query.toLowerCase();
var quotedText = stringBetweenQuotes(lowercaseText);
if (quotedText) {
return title.includes(quotedText) || text.includes(quotedText);
}
if (stringIsUuid(lowercaseText)) {
return note.uuid === lowercaseText;
}
var words = lowercaseText.split(" ");
var matchesTitle = words.every(function (word) {
return title.indexOf(word) >= 0;
});
var matchesBody = words.every(function (word) {
return text.indexOf(word) >= 0;
});
return matchesTitle || matchesBody;
}
function stringBetweenQuotes(text) {
var matches = text.match(/"(.*?)"/);
return matches ? matches[1] : null;
}
function stringIsUuid(text) {
var matches = text.match(/\b[0-9a-f]{8}\b-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-\b[0-9a-f]{12}\b/);
return !!matches;
}
function sortNotes(_ref4) {
var _ref4$notes = _ref4.notes,
notes = _ref4$notes === void 0 ? [] : _ref4$notes,
sortBy = _ref4.sortBy,
reverse = _ref4.reverse;
var sortValueFn = function sortValueFn(a, b) {
var pinCheck = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
if (a.dummy) {
return -1;
}
if (b.dummy) {
return 1;
}
if (!pinCheck) {
if (a.pinned && b.pinned) {
return sortValueFn(a, b, true);
}
if (a.pinned) {
return -1;
}
if (b.pinned) {
return 1;
}
}
var aValue = a[sortBy] || '';
var bValue = b[sortBy] || '';
var vector = 1;
if (reverse) {
vector *= -1;
}
if (sortBy === SORT_KEY_TITLE) {
aValue = aValue.toLowerCase();
bValue = bValue.toLowerCase();
if (aValue.length === 0 && bValue.length === 0) {
return 0;
} else if (aValue.length === 0 && bValue.length !== 0) {
return 1 * vector;
} else if (aValue.length !== 0 && bValue.length === 0) {
return -1 * vector;
} else {
vector *= -1;
}
}
if (aValue > bValue) {
return -1 * vector;
} else if (aValue < bValue) {
return 1 * vector;
}
return 0;
};
var result = notes.sort(function (a, b) {
return sortValueFn(a, b);
});
return result;
}
/***/ }),
/***/ "./app/assets/javascripts/controllers/notes/notes.js":
/*!***********************************************************!*\
!*** ./app/assets/javascripts/controllers/notes/notes.js ***!
\***********************************************************/
/*! exports provided: NotesPanel */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "NotesPanel", function() { return NotesPanel; });
/* harmony import */ var _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/regenerator */ "./node_modules/@babel/runtime/regenerator/index.js");
/* harmony import */ var _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/helpers/asyncToGenerator */ "./node_modules/@babel/runtime/helpers/asyncToGenerator.js");
/* harmony import */ var _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "./node_modules/@babel/runtime/helpers/classCallCheck.js");
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @babel/runtime/helpers/createClass */ "./node_modules/@babel/runtime/helpers/createClass.js");
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var _babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "./node_modules/@babel/runtime/helpers/possibleConstructorReturn.js");
/* harmony import */ var _babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_4__);
/* harmony import */ var _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "./node_modules/@babel/runtime/helpers/getPrototypeOf.js");
/* harmony import */ var _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_5___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_5__);
/* harmony import */ var _babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! @babel/runtime/helpers/assertThisInitialized */ "./node_modules/@babel/runtime/helpers/assertThisInitialized.js");
/* harmony import */ var _babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_6___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_6__);
/* harmony import */ var _babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! @babel/runtime/helpers/inherits */ "./node_modules/@babel/runtime/helpers/inherits.js");
/* harmony import */ var _babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_7___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_7__);
/* harmony import */ var _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! @babel/runtime/helpers/defineProperty */ "./node_modules/@babel/runtime/helpers/defineProperty.js");
/* harmony import */ var _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_8___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_8__);
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! lodash */ "./node_modules/lodash/lodash.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_9___default = /*#__PURE__*/__webpack_require__.n(lodash__WEBPACK_IMPORTED_MODULE_9__);
/* harmony import */ var angular__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! angular */ "./node_modules/angular/index.js");
/* harmony import */ var angular__WEBPACK_IMPORTED_MODULE_10___default = /*#__PURE__*/__webpack_require__.n(angular__WEBPACK_IMPORTED_MODULE_10__);
/* harmony import */ var _notes_pug__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! %/notes.pug */ "./app/assets/templates/notes.pug");
/* harmony import */ var _notes_pug__WEBPACK_IMPORTED_MODULE_11___default = /*#__PURE__*/__webpack_require__.n(_notes_pug__WEBPACK_IMPORTED_MODULE_11__);
/* harmony import */ var snjs__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! snjs */ "../snjs/dist/snjs.js");
/* harmony import */ var snjs__WEBPACK_IMPORTED_MODULE_12___default = /*#__PURE__*/__webpack_require__.n(snjs__WEBPACK_IMPORTED_MODULE_12__);
/* harmony import */ var _services_keyboardManager__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! @/services/keyboardManager */ "./app/assets/javascripts/services/keyboardManager.js");
/* harmony import */ var _Controllers__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! @Controllers */ "./app/assets/javascripts/controllers/index.js");
/* harmony import */ var _state__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! @/state */ "./app/assets/javascripts/state.js");
/* harmony import */ var _services_preferencesManager__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! @/services/preferencesManager */ "./app/assets/javascripts/services/preferencesManager.js");
/* harmony import */ var _controllers_constants__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(/*! @/controllers/constants */ "./app/assets/javascripts/controllers/constants.js");
/* harmony import */ var _note_utils__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(/*! ./note_utils */ "./app/assets/javascripts/controllers/notes/note_utils.js");
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_8___default()(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
/**
* This is the height of a note cell with nothing but the title,
* which *is* a display option
*/
var MIN_NOTE_CELL_HEIGHT = 51.0;
var DEFAULT_LIST_NUM_NOTES = 20;
var ELEMENT_ID_SEARCH_BAR = 'search-bar';
var ELEMENT_ID_SCROLL_CONTAINER = 'notes-scrollable';
var NotesCtrl =
/*#__PURE__*/
function (_PureCtrl) {
NotesCtrl.$inject = ["$timeout", "$rootScope", "application", "appState", "desktopManager", "keyboardManager", "preferencesManager"];
_babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_7___default()(NotesCtrl, _PureCtrl);
/* @ngInject */
function NotesCtrl($timeout, $rootScope, application, appState, desktopManager, keyboardManager, preferencesManager) {
var _this;
_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2___default()(this, NotesCtrl);
_this = _babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_4___default()(this, _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_5___default()(NotesCtrl).call(this, $timeout));
_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_8___default()(_babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_6___default()(_this), "onPanelResize", function (newWidth, lastLeft, isAtMaxWidth, isCollapsed) {
_this.preferencesManager.setUserPrefValue(_services_preferencesManager__WEBPACK_IMPORTED_MODULE_16__["PREF_NOTES_PANEL_WIDTH"], newWidth);
_this.preferencesManager.syncUserPreferences();
_this.appState.panelDidResize({
name: _controllers_constants__WEBPACK_IMPORTED_MODULE_17__["PANEL_NAME_NOTES"],
collapsed: isCollapsed
});
});
_this.$rootScope = $rootScope;
_this.application = application;
_this.appState = appState;
_this.desktopManager = desktopManager;
_this.keyboardManager = keyboardManager;
_this.preferencesManager = preferencesManager;
_this.state = {
notes: [],
renderedNotes: [],
selectedNote: null,
tag: null,
sortBy: null,
showArchived: null,
hidePinned: null,
sortReverse: null,
panelTitle: null,
mutable: {
showMenu: false
},
noteFilter: {
text: ''
}
};
_this.panelController = {};
window.onresize = function (event) {
_this.resetPagination({
keepCurrentIfLarger: true
});
};
_this.addAppStateObserver();
_this.addAppEventObserver();
_this.streamNotesAndTags();
_this.reloadPreferences();
_this.resetPagination();
_this.registerKeyboardShortcuts();
angular__WEBPACK_IMPORTED_MODULE_10___default.a.element(document).ready(function () {
_this.reloadPreferences();
});
return _this;
}
_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3___default()(NotesCtrl, [{
key: "addAppStateObserver",
value: function addAppStateObserver() {
var _this2 = this;
this.appState.addObserver(function (eventName, data) {
if (eventName === _state__WEBPACK_IMPORTED_MODULE_15__["APP_STATE_EVENT_TAG_CHANGED"]) {
_this2.handleTagChange(_this2.appState.getSelectedTag(), data.previousTag);
} else if (eventName === _state__WEBPACK_IMPORTED_MODULE_15__["APP_STATE_EVENT_NOTE_CHANGED"]) {
_this2.handleNoteSelection(_this2.appState.getSelectedNote());
} else if (eventName === _state__WEBPACK_IMPORTED_MODULE_15__["APP_STATE_EVENT_PREFERENCES_CHANGED"]) {
_this2.reloadPreferences();
_this2.reloadNotes();
} else if (eventName === _state__WEBPACK_IMPORTED_MODULE_15__["APP_STATE_EVENT_EDITOR_FOCUSED"]) {
_this2.setShowMenuFalse();
}
});
}
}, {
key: "addAppEventObserver",
value: function addAppEventObserver() {
var _this3 = this;
this.application.addEventObserver(function (eventName) {
if (eventName === snjs__WEBPACK_IMPORTED_MODULE_12__["ApplicationEvents"].SignedIn) {
/** Delete dummy note if applicable */
if (_this3.state.selectedNote && _this3.state.selectedNote.dummy) {
_this3.application.removeItemLocally({
item: _this3.state.selectedNote
});
_this3.selectNote(null).then(function () {
_this3.reloadNotes();
});
/**
* We want to see if the user will download any items from the server.
* If the next sync completes and our notes are still 0,
* we need to create a dummy.
*/
_this3.createDummyOnSynCompletionIfNoNotes = true;
}
} else if (eventName === snjs__WEBPACK_IMPORTED_MODULE_12__["ApplicationEvents"].LoadedLocalData) {
if (_this3.state.notes.length === 0) {
_this3.createNewNote();
}
} else if (eventName === snjs__WEBPACK_IMPORTED_MODULE_12__["ApplicationEvents"].CompletedSync) {
if (_this3.createDummyOnSynCompletionIfNoNotes && _this3.state.notes.length === 0) {
_this3.createDummyOnSynCompletionIfNoNotes = false;
_this3.createNewNote();
}
}
});
}
}, {
key: "streamNotesAndTags",
value: function streamNotesAndTags() {
var _this4 = this;
this.application.streamItems({
contentType: [snjs__WEBPACK_IMPORTED_MODULE_12__["CONTENT_TYPE_NOTE"], snjs__WEBPACK_IMPORTED_MODULE_12__["CONTENT_TYPE_TAG"]],
stream: function () {
var _stream = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee(_ref) {
var items, selectedNote, discarded, notIncluded, notes, _iteratorNormalCompletion, _didIteratorError, _iteratorError, _iterator, _step, note;
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
items = _ref.items;
_context.next = 3;
return _this4.reloadNotes();
case 3:
selectedNote = _this4.state.selectedNote;
if (selectedNote) {
discarded = selectedNote.deleted || selectedNote.content.trashed;
notIncluded = !_this4.state.notes.includes(selectedNote);
if (notIncluded || discarded) {
_this4.selectNextOrCreateNew();
}
} else {
_this4.selectFirstNote();
}
/** Note has changed values, reset its flags */
notes = items.filter(function (item) {
return item.content_type === snjs__WEBPACK_IMPORTED_MODULE_12__["CONTENT_TYPE_NOTE"];
});
_iteratorNormalCompletion = true;
_didIteratorError = false;
_iteratorError = undefined;
_context.prev = 9;
for (_iterator = notes[Symbol.iterator](); !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
note = _step.value;
_this4.loadFlagsForNote(note);
note.cachedCreatedAtString = note.createdAtString();
note.cachedUpdatedAtString = note.updatedAtString();
}
_context.next = 17;
break;
case 13:
_context.prev = 13;
_context.t0 = _context["catch"](9);
_didIteratorError = true;
_iteratorError = _context.t0;
case 17:
_context.prev = 17;
_context.prev = 18;
if (!_iteratorNormalCompletion && _iterator.return != null) {
_iterator.return();
}
case 20:
_context.prev = 20;
if (!_didIteratorError) {
_context.next = 23;
break;
}
throw _iteratorError;
case 23:
return _context.finish(20);
case 24:
return _context.finish(17);
case 25:
case "end":
return _context.stop();
}
}
}, _callee, null, [[9, 13, 17, 25], [18,, 20, 24]]);
}));
function stream(_x) {
return _stream.apply(this, arguments);
}
return stream;
}()
});
}
}, {
key: "handleTagChange",
value: function () {
var _handleTagChange = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee2(tag, previousTag) {
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee2$(_context2) {
while (1) {
switch (_context2.prev = _context2.next) {
case 0:
if (!(this.state.selectedNote && this.state.selectedNote.dummy)) {
_context2.next = 5;
break;
}
this.application.removeItemLocally({
item: this.state.selectedNote
});
if (previousTag) {
lodash__WEBPACK_IMPORTED_MODULE_9___default.a.remove(previousTag.notes, this.state.selectedNote);
}
_context2.next = 5;
return this.selectNote(null);
case 5:
_context2.next = 7;
return this.setState({
tag: tag
});
case 7:
this.resetScrollPosition();
this.setShowMenuFalse();
this.setNoteFilterText('');
this.desktopManager.searchText();
this.resetPagination();
_context2.next = 14;
return this.reloadNotes();
case 14:
if (this.state.notes.length > 0) {
this.selectFirstNote();
} else if (this.application.isDatabaseLoaded()) {
if (!tag.isSmartTag() || tag.content.isAllTag) {
this.createNewNote();
} else if (this.state.selectedNote && !this.state.notes.includes(this.state.selectedNote)) {
this.selectNote(null);
}
}
case 15:
case "end":
return _context2.stop();
}
}
}, _callee2, this);
}));
function handleTagChange(_x2, _x3) {
return _handleTagChange.apply(this, arguments);
}
return handleTagChange;
}()
}, {
key: "resetScrollPosition",
value: function resetScrollPosition() {
var scrollable = document.getElementById(ELEMENT_ID_SCROLL_CONTAINER);
if (scrollable) {
scrollable.scrollTop = 0;
scrollable.scrollLeft = 0;
}
}
/**
* @template
* @internal
*/
}, {
key: "selectNote",
value: function () {
var _selectNote = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee3(note) {
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee3$(_context3) {
while (1) {
switch (_context3.prev = _context3.next) {
case 0:
this.appState.setSelectedNote(note);
case 1:
case "end":
return _context3.stop();
}
}
}, _callee3, this);
}));
function selectNote(_x4) {
return _selectNote.apply(this, arguments);
}
return selectNote;
}()
}, {
key: "removeNoteFromList",
value: function () {
var _removeNoteFromList = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee4(note) {
var notes;
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee4$(_context4) {
while (1) {
switch (_context4.prev = _context4.next) {
case 0:
notes = this.state.notes;
lodash__WEBPACK_IMPORTED_MODULE_9___default.a.pull(notes, note);
_context4.next = 4;
return this.setState({
notes: notes,
renderedNotes: notes.slice(0, this.notesToDisplay)
});
case 4:
case "end":
return _context4.stop();
}
}
}, _callee4, this);
}));
function removeNoteFromList(_x5) {
return _removeNoteFromList.apply(this, arguments);
}
return removeNoteFromList;
}()
}, {
key: "reloadNotes",
value: function () {
var _reloadNotes = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee5() {
var notes, _iteratorNormalCompletion2, _didIteratorError2, _iteratorError2, _iterator2, _step2, note;
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee5$(_context5) {
while (1) {
switch (_context5.prev = _context5.next) {
case 0:
if (this.state.tag) {
_context5.next = 2;
break;
}
return _context5.abrupt("return");
case 2:
notes = Object(_note_utils__WEBPACK_IMPORTED_MODULE_18__["filterAndSortNotes"])({
notes: this.state.tag.notes,
selectedTag: this.state.tag,
showArchived: this.state.showArchived,
hidePinned: this.state.hidePinned,
filterText: this.state.noteFilter.text,
sortBy: this.state.sortBy,
reverse: this.state.sortReverse
});
_iteratorNormalCompletion2 = true;
_didIteratorError2 = false;
_iteratorError2 = undefined;
_context5.prev = 6;
for (_iterator2 = notes[Symbol.iterator](); !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
note = _step2.value;
if (note.errorDecrypting) {
this.loadFlagsForNote(note);
}
note.shouldShowTags = this.shouldShowTagsForNote(note);
}
_context5.next = 14;
break;
case 10:
_context5.prev = 10;
_context5.t0 = _context5["catch"](6);
_didIteratorError2 = true;
_iteratorError2 = _context5.t0;
case 14:
_context5.prev = 14;
_context5.prev = 15;
if (!_iteratorNormalCompletion2 && _iterator2.return != null) {
_iterator2.return();
}
case 17:
_context5.prev = 17;
if (!_didIteratorError2) {
_context5.next = 20;
break;
}
throw _iteratorError2;
case 20:
return _context5.finish(17);
case 21:
return _context5.finish(14);
case 22:
_context5.next = 24;
return this.setState({
notes: notes,
renderedNotes: notes.slice(0, this.notesToDisplay)
});
case 24:
this.reloadPanelTitle();
case 25:
case "end":
return _context5.stop();
}
}
}, _callee5, this, [[6, 10, 14, 22], [15,, 17, 21]]);
}));
function reloadNotes() {
return _reloadNotes.apply(this, arguments);
}
return reloadNotes;
}()
}, {
key: "setShowMenuFalse",
value: function setShowMenuFalse() {
this.setState({
mutable: _objectSpread({}, this.state.mutable, {
showMenu: false
})
});
}
}, {
key: "handleNoteSelection",
value: function () {
var _handleNoteSelection = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee6(note) {
var previousNote;
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee6$(_context6) {
while (1) {
switch (_context6.prev = _context6.next) {
case 0:
if (!(this.state.selectedNote === note)) {
_context6.next = 2;
break;
}
return _context6.abrupt("return");
case 2:
previousNote = this.state.selectedNote;
if (previousNote && previousNote.dummy) {
this.application.removeItemLocally({
previousNote: previousNote
});
this.removeNoteFromList(previousNote);
}
_context6.next = 6;
return this.setState({
selectedNote: note
});
case 6:
if (note) {
_context6.next = 8;
break;
}
return _context6.abrupt("return");
case 8:
this.selectedIndex = Math.max(0, this.displayableNotes().indexOf(note));
if (note.content.conflict_of) {
note.content.conflict_of = null;
this.application.saveItem({
item: note
});
}
if (this.isFiltering()) {
this.desktopManager.searchText(this.state.noteFilter.text);
}
case 11:
case "end":
return _context6.stop();
}
}
}, _callee6, this);
}));
function handleNoteSelection(_x6) {
return _handleNoteSelection.apply(this, arguments);
}
return handleNoteSelection;
}()
}, {
key: "reloadPreferences",
value: function reloadPreferences() {
var viewOptions = {};
var prevSortValue = this.state.sortBy;
var sortBy = this.preferencesManager.getValue(_services_preferencesManager__WEBPACK_IMPORTED_MODULE_16__["PREF_SORT_NOTES_BY"], _note_utils__WEBPACK_IMPORTED_MODULE_18__["SORT_KEY_CREATED_AT"]);
if (sortBy === _note_utils__WEBPACK_IMPORTED_MODULE_18__["SORT_KEY_UPDATED_AT"]) {
/** Use client_updated_at instead */
sortBy = _note_utils__WEBPACK_IMPORTED_MODULE_18__["SORT_KEY_CLIENT_UPDATED_AT"];
}
viewOptions.sortBy = sortBy;
viewOptions.sortReverse = this.preferencesManager.getValue(_services_preferencesManager__WEBPACK_IMPORTED_MODULE_16__["PREF_SORT_NOTES_REVERSE"], false);
viewOptions.showArchived = this.preferencesManager.getValue(_services_preferencesManager__WEBPACK_IMPORTED_MODULE_16__["PREF_NOTES_SHOW_ARCHIVED"], false);
viewOptions.hidePinned = this.preferencesManager.getValue(_services_preferencesManager__WEBPACK_IMPORTED_MODULE_16__["PREF_NOTES_HIDE_PINNED"], false);
viewOptions.hideNotePreview = this.preferencesManager.getValue(_services_preferencesManager__WEBPACK_IMPORTED_MODULE_16__["PREF_NOTES_HIDE_NOTE_PREVIEW"], false);
viewOptions.hideDate = this.preferencesManager.getValue(_services_preferencesManager__WEBPACK_IMPORTED_MODULE_16__["PREF_NOTES_HIDE_DATE"], false);
viewOptions.hideTags = this.preferencesManager.getValue(_services_preferencesManager__WEBPACK_IMPORTED_MODULE_16__["PREF_NOTES_HIDE_TAGS"], false);
this.setState(_objectSpread({}, viewOptions));
if (prevSortValue && prevSortValue !== sortBy) {
this.selectFirstNote();
}
var width = this.preferencesManager.getValue(_services_preferencesManager__WEBPACK_IMPORTED_MODULE_16__["PREF_NOTES_PANEL_WIDTH"]);
if (width) {
this.panelController.setWidth(width);
if (this.panelController.isCollapsed()) {
this.appState.panelDidResize({
name: _controllers_constants__WEBPACK_IMPORTED_MODULE_17__["PANEL_NAME_NOTES"],
collapsed: this.panelController.isCollapsed()
});
}
}
}
}, {
key: "paginate",
value: function paginate() {
this.notesToDisplay += this.pageSize;
this.reloadNotes();
if (this.searchSubmitted) {
this.desktopManager.searchText(this.state.noteFilter.text);
}
}
}, {
key: "resetPagination",
value: function resetPagination() {
var _ref2 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
keepCurrentIfLarger = _ref2.keepCurrentIfLarger;
var clientHeight = document.documentElement.clientHeight;
this.pageSize = clientHeight / MIN_NOTE_CELL_HEIGHT;
if (this.pageSize === 0) {
this.pageSize = DEFAULT_LIST_NUM_NOTES;
}
if (keepCurrentIfLarger && this.notesToDisplay > this.pageSize) {
return;
}
this.notesToDisplay = this.pageSize;
}
}, {
key: "reloadPanelTitle",
value: function reloadPanelTitle() {
var title;
if (this.isFiltering()) {
var resultCount = this.state.notes.length;
title = "".concat(resultCount, " search results");
} else if (this.state.tag) {
title = "".concat(this.state.tag.title);
}
this.setState({
panelTitle: title
});
}
}, {
key: "optionsSubtitle",
value: function optionsSubtitle() {
var base = "";
if (this.state.sortBy === 'created_at') {
base += " Date Added";
} else if (this.state.sortBy === 'client_updated_at') {
base += " Date Modified";
} else if (this.state.sortBy === 'title') {
base += " Title";
}
if (this.state.showArchived) {
base += " | + Archived";
}
if (this.state.hidePinned) {
base += " | – Pinned";
}
if (this.state.sortReverse) {
base += " | Reversed";
}
return base;
}
}, {
key: "loadFlagsForNote",
value: function loadFlagsForNote(note) {
var flags = [];
if (note.pinned) {
flags.push({
text: "Pinned",
class: 'info'
});
}
if (note.archived) {
flags.push({
text: "Archived",
class: 'warning'
});
}
if (note.content.protected) {
flags.push({
text: "Protected",
class: 'success'
});
}
if (note.locked) {
flags.push({
text: "Locked",
class: 'neutral'
});
}
if (note.content.trashed) {
flags.push({
text: "Deleted",
class: 'danger'
});
}
if (note.content.conflict_of) {
flags.push({
text: "Conflicted Copy",
class: 'danger'
});
}
if (note.errorDecrypting) {
flags.push({
text: "Missing Keys",
class: 'danger'
});
}
if (note.deleted) {
flags.push({
text: "Deletion Pending Sync",
class: 'danger'
});
}
note.flags = flags;
return flags;
}
}, {
key: "displayableNotes",
value: function displayableNotes() {
return this.state.notes;
}
}, {
key: "getFirstNonProtectedNote",
value: function getFirstNonProtectedNote() {
var displayableNotes = this.displayableNotes();
var index = 0;
var note = displayableNotes[index];
while (note && note.content.protected) {
index++;
if (index >= displayableNotes.length) {
break;
}
note = displayableNotes[index];
}
return note;
}
}, {
key: "selectFirstNote",
value: function selectFirstNote() {
var note = this.getFirstNonProtectedNote();
if (note) {
this.selectNote(note);
}
}
}, {
key: "selectNextNote",
value: function selectNextNote() {
var displayableNotes = this.displayableNotes();
var currentIndex = displayableNotes.indexOf(this.state.selectedNote);
if (currentIndex + 1 < displayableNotes.length) {
this.selectNote(displayableNotes[currentIndex + 1]);
}
}
}, {
key: "selectNextOrCreateNew",
value: function selectNextOrCreateNew() {
var note = this.getFirstNonProtectedNote();
if (note) {
this.selectNote(note);
} else if (!this.state.tag || !this.state.tag.isSmartTag()) {
this.createNewNote();
} else {
this.selectNote(null);
}
}
}, {
key: "selectPreviousNote",
value: function selectPreviousNote() {
var displayableNotes = this.displayableNotes();
var currentIndex = displayableNotes.indexOf(this.state.selectedNote);
if (currentIndex - 1 >= 0) {
this.selectNote(displayableNotes[currentIndex - 1]);
return true;
} else {
return false;
}
}
}, {
key: "createNewNote",
value: function createNewNote() {
if (this.state.selectedNote && this.state.selectedNote.dummy) {
return;
}
var title = "Note" + (this.state.notes ? " " + (this.state.notes.length + 1) : "");
var newNote = this.application.createItem({
contentType: snjs__WEBPACK_IMPORTED_MODULE_12__["CONTENT_TYPE_NOTE"],
content: {
text: '',
title: title
}
});
newNote.client_updated_at = new Date();
newNote.dummy = true;
this.application.setItemNeedsSync({
item: newNote
});
var selectedTag = this.appState.getSelectedTag();
if (!selectedTag.isSmartTag()) {
selectedTag.addItemAsRelationship(newNote);
this.application.setItemNeedsSync({
item: selectedTag
});
}
this.selectNote(newNote);
}
}, {
key: "isFiltering",
value: function isFiltering() {
return this.state.noteFilter.text && this.state.noteFilter.text.length > 0;
}
}, {
key: "setNoteFilterText",
value: function () {
var _setNoteFilterText = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee7(text) {
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee7$(_context7) {
while (1) {
switch (_context7.prev = _context7.next) {
case 0:
_context7.next = 2;
return this.setState({
noteFilter: _objectSpread({}, this.state.noteFilter, {
text: text
})
});
case 2:
case "end":
return _context7.stop();
}
}
}, _callee7, this);
}));
function setNoteFilterText(_x7) {
return _setNoteFilterText.apply(this, arguments);
}
return setNoteFilterText;
}()
}, {
key: "clearFilterText",
value: function () {
var _clearFilterText = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee8() {
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee8$(_context8) {
while (1) {
switch (_context8.prev = _context8.next) {
case 0:
_context8.next = 2;
return this.setNoteFilterText('');
case 2:
this.onFilterEnter();
this.filterTextChanged();
this.resetPagination();
case 5:
case "end":
return _context8.stop();
}
}
}, _callee8, this);
}));
function clearFilterText() {
return _clearFilterText.apply(this, arguments);
}
return clearFilterText;
}()
}, {
key: "filterTextChanged",
value: function () {
var _filterTextChanged = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee9() {
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee9$(_context9) {
while (1) {
switch (_context9.prev = _context9.next) {
case 0:
if (this.searchSubmitted) {
this.searchSubmitted = false;
}
_context9.next = 3;
return this.reloadNotes();
case 3:
if (!this.state.notes.includes(this.state.selectedNote)) {
this.selectFirstNote();
}
case 4:
case "end":
return _context9.stop();
}
}
}, _callee9, this);
}));
function filterTextChanged() {
return _filterTextChanged.apply(this, arguments);
}
return filterTextChanged;
}()
}, {
key: "onFilterEnter",
value: function onFilterEnter() {
/**
* For Desktop, performing a search right away causes
* input to lose focus. We wait until user explicity hits
* enter before highlighting desktop search results.
*/
this.searchSubmitted = true;
this.desktopManager.searchText(this.state.noteFilter.text);
}
}, {
key: "selectedMenuItem",
value: function selectedMenuItem() {
this.setShowMenuFalse();
}
}, {
key: "togglePrefKey",
value: function togglePrefKey(key) {
this.preferencesManager.setUserPrefValue(key, !this.state[key]);
this.preferencesManager.syncUserPreferences();
}
}, {
key: "selectedSortByCreated",
value: function selectedSortByCreated() {
this.setSortBy(_note_utils__WEBPACK_IMPORTED_MODULE_18__["SORT_KEY_CREATED_AT"]);
}
}, {
key: "selectedSortByUpdated",
value: function selectedSortByUpdated() {
this.setSortBy(_note_utils__WEBPACK_IMPORTED_MODULE_18__["SORT_KEY_CLIENT_UPDATED_AT"]);
}
}, {
key: "selectedSortByTitle",
value: function selectedSortByTitle() {
this.setSortBy(_note_utils__WEBPACK_IMPORTED_MODULE_18__["SORT_KEY_TITLE"]);
}
}, {
key: "toggleReverseSort",
value: function toggleReverseSort() {
this.selectedMenuItem();
this.preferencesManager.setUserPrefValue(_services_preferencesManager__WEBPACK_IMPORTED_MODULE_16__["PREF_SORT_NOTES_REVERSE"], !this.state.sortReverse);
this.preferencesManager.syncUserPreferences();
}
}, {
key: "setSortBy",
value: function setSortBy(type) {
this.preferencesManager.setUserPrefValue(_services_preferencesManager__WEBPACK_IMPORTED_MODULE_16__["PREF_SORT_NOTES_BY"], type);
this.preferencesManager.syncUserPreferences();
}
}, {
key: "shouldShowTagsForNote",
value: function shouldShowTagsForNote(note) {
if (this.state.hideTags || note.content.protected) {
return false;
}
if (this.state.tag.content.isAllTag) {
return note.tags && note.tags.length > 0;
}
if (this.state.tag.isSmartTag()) {
return true;
}
/**
* Inside a tag, only show tags string if
* note contains tags other than this.state.tag
*/
return note.tags && note.tags.length > 1;
}
}, {
key: "getSearchBar",
value: function getSearchBar() {
return document.getElementById(ELEMENT_ID_SEARCH_BAR);
}
}, {
key: "registerKeyboardShortcuts",
value: function registerKeyboardShortcuts() {
var _this5 = this;
/**
* In the browser we're not allowed to override cmd/ctrl + n, so we have to
* use Control modifier as well. These rules don't apply to desktop, but
* probably better to be consistent.
*/
this.newNoteKeyObserver = this.keyboardManager.addKeyObserver({
key: 'n',
modifiers: [_services_keyboardManager__WEBPACK_IMPORTED_MODULE_13__["KeyboardManager"].KeyModifierMeta, _services_keyboardManager__WEBPACK_IMPORTED_MODULE_13__["KeyboardManager"].KeyModifierCtrl],
onKeyDown: function onKeyDown(event) {
event.preventDefault();
_this5.createNewNote();
}
});
this.nextNoteKeyObserver = this.keyboardManager.addKeyObserver({
key: _services_keyboardManager__WEBPACK_IMPORTED_MODULE_13__["KeyboardManager"].KeyDown,
elements: [document.body, this.getSearchBar()],
onKeyDown: function onKeyDown(event) {
var searchBar = _this5.getSearchBar();
if (searchBar === document.activeElement) {
searchBar.blur();
}
_this5.selectNextNote();
}
});
this.nextNoteKeyObserver = this.keyboardManager.addKeyObserver({
key: _services_keyboardManager__WEBPACK_IMPORTED_MODULE_13__["KeyboardManager"].KeyUp,
element: document.body,
onKeyDown: function onKeyDown(event) {
_this5.selectPreviousNote();
}
});
this.searchKeyObserver = this.keyboardManager.addKeyObserver({
key: "f",
modifiers: [_services_keyboardManager__WEBPACK_IMPORTED_MODULE_13__["KeyboardManager"].KeyModifierMeta, _services_keyboardManager__WEBPACK_IMPORTED_MODULE_13__["KeyboardManager"].KeyModifierShift],
onKeyDown: function onKeyDown(event) {
var searchBar = _this5.getSearchBar();
if (searchBar) {
searchBar.focus();
}
;
}
});
}
}]);
return NotesCtrl;
}(_Controllers__WEBPACK_IMPORTED_MODULE_14__["PureCtrl"]);
var NotesPanel = function NotesPanel() {
_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2___default()(this, NotesPanel);
this.scope = {};
this.template = _notes_pug__WEBPACK_IMPORTED_MODULE_11___default.a;
this.replace = true;
this.controller = NotesCtrl;
this.controllerAs = 'self';
this.bindToController = true;
};
/***/ }),
/***/ "./app/assets/javascripts/controllers/root.js":
/*!****************************************************!*\
!*** ./app/assets/javascripts/controllers/root.js ***!
\****************************************************/
/*! exports provided: Root */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Root", function() { return Root; });
/* harmony import */ var _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/regenerator */ "./node_modules/@babel/runtime/regenerator/index.js");
/* harmony import */ var _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/helpers/asyncToGenerator */ "./node_modules/@babel/runtime/helpers/asyncToGenerator.js");
/* harmony import */ var _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "./node_modules/@babel/runtime/helpers/classCallCheck.js");
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @babel/runtime/helpers/createClass */ "./node_modules/@babel/runtime/helpers/createClass.js");
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var _babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "./node_modules/@babel/runtime/helpers/possibleConstructorReturn.js");
/* harmony import */ var _babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_4__);
/* harmony import */ var _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "./node_modules/@babel/runtime/helpers/getPrototypeOf.js");
/* harmony import */ var _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_5___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_5__);
/* harmony import */ var _babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! @babel/runtime/helpers/inherits */ "./node_modules/@babel/runtime/helpers/inherits.js");
/* harmony import */ var _babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_6___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_6__);
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! lodash */ "./node_modules/lodash/lodash.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_7___default = /*#__PURE__*/__webpack_require__.n(lodash__WEBPACK_IMPORTED_MODULE_7__);
/* harmony import */ var snjs__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! snjs */ "../snjs/dist/snjs.js");
/* harmony import */ var snjs__WEBPACK_IMPORTED_MODULE_8___default = /*#__PURE__*/__webpack_require__.n(snjs__WEBPACK_IMPORTED_MODULE_8__);
/* harmony import */ var _utils__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! @/utils */ "./app/assets/javascripts/utils.js");
/* harmony import */ var _root_pug__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! %/root.pug */ "./app/assets/templates/root.pug");
/* harmony import */ var _root_pug__WEBPACK_IMPORTED_MODULE_10___default = /*#__PURE__*/__webpack_require__.n(_root_pug__WEBPACK_IMPORTED_MODULE_10__);
/* harmony import */ var _state__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! @/state */ "./app/assets/javascripts/state.js");
/* harmony import */ var _controllers_constants__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! @/controllers/constants */ "./app/assets/javascripts/controllers/constants.js");
/* harmony import */ var _strings__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! @/strings */ "./app/assets/javascripts/strings.js");
var RootCtrl =
/*#__PURE__*/
function (_PureCtrl) {
RootCtrl.$inject = ["$location", "$rootScope", "$timeout", "application", "appState", "databaseManager", "lockManager", "preferencesManager", "themeManager", "statusManager"];
_babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_6___default()(RootCtrl, _PureCtrl);
/* @ngInject */
function RootCtrl($location, $rootScope, $timeout, application, appState, databaseManager, lockManager, preferencesManager, themeManager
/** Unused below, required to load globally */
, statusManager) {
var _this;
_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2___default()(this, RootCtrl);
_this = _babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_4___default()(this, _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_5___default()(RootCtrl).call(this, $timeout));
_this.$location = $location;
_this.$rootScope = $rootScope;
_this.$timeout = $timeout;
_this.application = application;
_this.appState = appState;
_this.databaseManager = databaseManager;
_this.lockManager = lockManager;
_this.preferencesManager = preferencesManager;
_this.statusManager = statusManager;
_this.platformString = Object(_utils__WEBPACK_IMPORTED_MODULE_9__["getPlatformString"])();
_this.state = {
needsUnlock: false,
appClass: ''
};
_this.loadApplication();
_this.handleAutoSignInFromParams();
_this.addAppStateObserver();
_this.addDragDropHandlers();
return _this;
}
_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3___default()(RootCtrl, [{
key: "loadApplication",
value: function () {
var _loadApplication = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee2() {
var _this2 = this;
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee2$(_context2) {
while (1) {
switch (_context2.prev = _context2.next) {
case 0:
this.application.prepareForLaunch({
callbacks: {
authChallengeResponses: function () {
var _authChallengeResponses = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee(challenges) {
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
if (challenges.includes(snjs__WEBPACK_IMPORTED_MODULE_8__["Challenges"].LocalPasscode)) {
_this2.setState({
needsUnlock: true
});
}
case 1:
case "end":
return _context.stop();
}
}
}, _callee);
}));
function authChallengeResponses(_x) {
return _authChallengeResponses.apply(this, arguments);
}
return authChallengeResponses;
}()
}
});
_context2.next = 3;
return this.application.launch();
case 3:
this.setState({
needsUnlock: false
});
_context2.next = 6;
return this.openDatabase();
case 6:
this.preferencesManager.load();
this.addSyncStatusObserver();
this.addSyncEventHandler();
case 9:
case "end":
return _context2.stop();
}
}
}, _callee2, this);
}));
function loadApplication() {
return _loadApplication.apply(this, arguments);
}
return loadApplication;
}()
}, {
key: "onUpdateAvailable",
value: function onUpdateAvailable() {
this.$rootScope.$broadcast('new-update-available');
}
}, {
key: "addAppStateObserver",
value: function addAppStateObserver() {
var _this3 = this;
this.appState.addObserver(
/*#__PURE__*/
function () {
var _ref = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee3(eventName, data) {
var appClass;
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee3$(_context3) {
while (1) {
switch (_context3.prev = _context3.next) {
case 0:
if (!(eventName === _state__WEBPACK_IMPORTED_MODULE_11__["APP_STATE_EVENT_PANEL_RESIZED"])) {
_context3.next = 9;
break;
}
if (data.panel === _controllers_constants__WEBPACK_IMPORTED_MODULE_12__["PANEL_NAME_NOTES"]) {
_this3.notesCollapsed = data.collapsed;
}
if (data.panel === _controllers_constants__WEBPACK_IMPORTED_MODULE_12__["PANEL_NAME_TAGS"]) {
_this3.tagsCollapsed = data.collapsed;
}
appClass = "";
if (_this3.notesCollapsed) {
appClass += "collapsed-notes";
}
if (_this3.tagsCollapsed) {
appClass += " collapsed-tags";
}
_this3.setState({
appClass: appClass
});
_context3.next = 14;
break;
case 9:
if (!(eventName === _state__WEBPACK_IMPORTED_MODULE_11__["APP_STATE_EVENT_WINDOW_DID_FOCUS"])) {
_context3.next = 14;
break;
}
_context3.next = 12;
return _this3.application.isPasscodeLocked();
case 12:
if (_context3.sent) {
_context3.next = 14;
break;
}
_this3.application.sync();
case 14:
case "end":
return _context3.stop();
}
}
}, _callee3);
}));
return function (_x2, _x3) {
return _ref.apply(this, arguments);
};
}());
}
}, {
key: "openDatabase",
value: function () {
var _openDatabase = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee4() {
var _this4 = this;
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee4$(_context4) {
while (1) {
switch (_context4.prev = _context4.next) {
case 0:
this.databaseManager.setLocked(false);
this.databaseManager.openDatabase({
onUpgradeNeeded: function onUpgradeNeeded() {
/**
* New database/database wiped, delete syncToken so that items
* can be refetched entirely from server
*/
_this4.application.syncManager.clearSyncPositionTokens();
_this4.application.sync();
}
});
case 2:
case "end":
return _context4.stop();
}
}
}, _callee4, this);
}));
function openDatabase() {
return _openDatabase.apply(this, arguments);
}
return openDatabase;
}() // addSyncStatusObserver() {
// this.syncStatusObserver = this.syncManager.registerSyncStatusObserver((status) => {
// if (status.retrievedCount > 20) {
// const text = `Downloading ${status.retrievedCount} items. Keep app open.`;
// this.syncStatus = this.statusManager.replaceStatusWithString(
// this.syncStatus,
// text
// );
// this.showingDownloadStatus = true;
// } else if (this.showingDownloadStatus) {
// this.showingDownloadStatus = false;
// const text = "Download Complete.";
// this.syncStatus = this.statusManager.replaceStatusWithString(
// this.syncStatus,
// text
// );
// setTimeout(() => {
// this.syncStatus = this.statusManager.removeStatus(this.syncStatus);
// }, 2000);
// } else if (status.total > 20) {
// this.uploadSyncStatus = this.statusManager.replaceStatusWithString(
// this.uploadSyncStatus,
// `Syncing ${status.current}/${status.total} items...`
// );
// } else if (this.uploadSyncStatus) {
// this.uploadSyncStatus = this.statusManager.removeStatus(
// this.uploadSyncStatus
// );
// }
// });
// }
// addSyncEventHandler() {
// let lastShownDate;
// this.syncManager.addEventHandler((syncEvent, data) => {
// this.$rootScope.$broadcast(
// syncEvent,
// data || {}
// );
// if (syncEvent === 'sync-session-invalid') {
// /** Don't show repeatedly; at most 30 seconds in between */
// const SHOW_INTERVAL = 30;
// const lastShownSeconds = (new Date() - lastShownDate) / 1000;
// if (!lastShownDate || lastShownSeconds > SHOW_INTERVAL) {
// lastShownDate = new Date();
// setTimeout(() => {
// this.alertManager.alert({
// text: STRING_SESSION_EXPIRED
// });
// }, 500);
// }
// } else if (syncEvent === 'sync-exception') {
// this.alertManager.alert({
// text: StringSyncException(data)
// });
// }
// });
// }
// loadLocalData() {
// const encryptionEnabled = this.application.getUser || this.application.hasPasscode();
// this.syncStatus = this.statusManager.addStatusFromString(
// encryptionEnabled ? "Decrypting items..." : "Loading items..."
// );
// const incrementalCallback = (current, total) => {
// const notesString = `${current}/${total} items...`;
// const status = encryptionEnabled
// ? `Decrypting ${notesString}`
// : `Loading ${notesString}`;
// this.syncStatus = this.statusManager.replaceStatusWithString(
// this.syncStatus,
// status
// );
// };
// this.syncManager.loadLocalItems({ incrementalCallback }).then(() => {
// this.$timeout(() => {
// this.$rootScope.$broadcast("initial-data-loaded");
// this.syncStatus = this.statusManager.replaceStatusWithString(
// this.syncStatus,
// "Syncing..."
// );
// this.syncManager.sync({
// checkIntegrity: true
// }).then(() => {
// this.syncStatus = this.statusManager.removeStatus(this.syncStatus);
// });
// });
// });
// }
}, {
key: "addDragDropHandlers",
value: function addDragDropHandlers() {
var _this5 = this;
/**
* Disable dragging and dropping of files (but allow text) into main SN interface.
* both 'dragover' and 'drop' are required to prevent dropping of files.
* This will not prevent extensions from receiving drop events.
*/
window.addEventListener('dragover', function (event) {
if (event.dataTransfer.files.length > 0) {
event.preventDefault();
}
}, false);
window.addEventListener('drop', function (event) {
if (event.dataTransfer.files.length > 0) {
event.preventDefault();
_this5.application.alertManager.alert({
text: _strings__WEBPACK_IMPORTED_MODULE_13__["STRING_DEFAULT_FILE_ERROR"]
});
}
}, false);
}
}, {
key: "handleAutoSignInFromParams",
value: function handleAutoSignInFromParams() {
var _this6 = this;
var urlParam = function urlParam(key) {
return _this6.$location.search()[key];
};
var autoSignInFromParams =
/*#__PURE__*/
function () {
var _ref2 = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee5() {
var server, email, pw;
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee5$(_context5) {
while (1) {
switch (_context5.prev = _context5.next) {
case 0:
server = urlParam('server');
email = urlParam('email');
pw = urlParam('pw');
if (_this6.application.getUser()) {
_context5.next = 21;
break;
}
_context5.next = 6;
return _this6.application.getHost();
case 6:
_context5.t1 = _context5.sent;
_context5.t2 = server;
_context5.t0 = _context5.t1 === _context5.t2;
if (!_context5.t0) {
_context5.next = 11;
break;
}
_context5.t0 = _this6.application.getUser().email === email;
case 11:
if (!_context5.t0) {
_context5.next = 15;
break;
}
return _context5.abrupt("return");
case 15:
_context5.next = 17;
return _this6.application.signOut();
case 17:
_context5.next = 19;
return _this6.application.restart();
case 19:
_context5.next = 24;
break;
case 21:
_context5.next = 23;
return _this6.application.setHost(server);
case 23:
_this6.application.signIn({
email: email,
password: pw
});
case 24:
case "end":
return _context5.stop();
}
}
}, _callee5);
}));
return function autoSignInFromParams() {
return _ref2.apply(this, arguments);
};
}();
if (urlParam('server')) {
autoSignInFromParams();
}
}
}]);
return RootCtrl;
}(PureCtrl);
var Root = function Root() {
_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2___default()(this, Root);
this.template = _root_pug__WEBPACK_IMPORTED_MODULE_10___default.a;
this.controller = RootCtrl;
this.replace = true;
this.controllerAs = 'self';
this.bindToController = true;
};
/***/ }),
/***/ "./app/assets/javascripts/controllers/tags.js":
/*!****************************************************!*\
!*** ./app/assets/javascripts/controllers/tags.js ***!
\****************************************************/
/*! exports provided: TagsPanel */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TagsPanel", function() { return TagsPanel; });
/* harmony import */ var _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/regenerator */ "./node_modules/@babel/runtime/regenerator/index.js");
/* harmony import */ var _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/helpers/asyncToGenerator */ "./node_modules/@babel/runtime/helpers/asyncToGenerator.js");
/* harmony import */ var _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "./node_modules/@babel/runtime/helpers/classCallCheck.js");
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @babel/runtime/helpers/createClass */ "./node_modules/@babel/runtime/helpers/createClass.js");
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var _babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "./node_modules/@babel/runtime/helpers/possibleConstructorReturn.js");
/* harmony import */ var _babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_4__);
/* harmony import */ var _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "./node_modules/@babel/runtime/helpers/getPrototypeOf.js");
/* harmony import */ var _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_5___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_5__);
/* harmony import */ var _babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! @babel/runtime/helpers/assertThisInitialized */ "./node_modules/@babel/runtime/helpers/assertThisInitialized.js");
/* harmony import */ var _babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_6___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_6__);
/* harmony import */ var _babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! @babel/runtime/helpers/inherits */ "./node_modules/@babel/runtime/helpers/inherits.js");
/* harmony import */ var _babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_7___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_7__);
/* harmony import */ var _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! @babel/runtime/helpers/defineProperty */ "./node_modules/@babel/runtime/helpers/defineProperty.js");
/* harmony import */ var _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_8___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_8__);
/* harmony import */ var snjs__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! snjs */ "../snjs/dist/snjs.js");
/* harmony import */ var snjs__WEBPACK_IMPORTED_MODULE_9___default = /*#__PURE__*/__webpack_require__.n(snjs__WEBPACK_IMPORTED_MODULE_9__);
/* harmony import */ var _tags_pug__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! %/tags.pug */ "./app/assets/templates/tags.pug");
/* harmony import */ var _tags_pug__WEBPACK_IMPORTED_MODULE_10___default = /*#__PURE__*/__webpack_require__.n(_tags_pug__WEBPACK_IMPORTED_MODULE_10__);
/* harmony import */ var _state__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! @/state */ "./app/assets/javascripts/state.js");
/* harmony import */ var _controllers_constants__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! @/controllers/constants */ "./app/assets/javascripts/controllers/constants.js");
/* harmony import */ var _services_preferencesManager__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! @/services/preferencesManager */ "./app/assets/javascripts/services/preferencesManager.js");
/* harmony import */ var _strings__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! @/strings */ "./app/assets/javascripts/strings.js");
/* harmony import */ var _Controllers__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! @Controllers */ "./app/assets/javascripts/controllers/index.js");
var TagsPanelCtrl =
/*#__PURE__*/
function (_PureCtrl) {
TagsPanelCtrl.$inject = ["$rootScope", "$timeout", "application", "appState", "preferencesManager"];
_babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_7___default()(TagsPanelCtrl, _PureCtrl);
/* @ngInject */
function TagsPanelCtrl($rootScope, $timeout, application, appState, preferencesManager) {
var _this;
_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2___default()(this, TagsPanelCtrl);
_this = _babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_4___default()(this, _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_5___default()(TagsPanelCtrl).call(this, $timeout));
_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_8___default()(_babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_6___default()(_this), "onPanelResize", function (newWidth, lastLeft, isAtMaxWidth, isCollapsed) {
_this.preferencesManager.setUserPrefValue(_services_preferencesManager__WEBPACK_IMPORTED_MODULE_13__["PREF_TAGS_PANEL_WIDTH"], newWidth, true);
_this.appState.panelDidResize({
name: _controllers_constants__WEBPACK_IMPORTED_MODULE_12__["PANEL_NAME_TAGS"],
collapsed: isCollapsed
});
});
_this.$rootScope = $rootScope;
_this.application = application;
_this.appState = appState;
_this.preferencesManager = preferencesManager;
_this.panelController = {};
_this.beginStreamingItems();
_this.addAppStateObserver();
_this.loadPreferences();
_this.registerComponentHandler();
_this.state = {
smartTags: _this.application.getSmartTags(),
noteCounts: {}
};
return _this;
}
_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3___default()(TagsPanelCtrl, [{
key: "$onInit",
value: function $onInit() {
this.selectTag(this.state.smartTags[0]);
}
}, {
key: "beginStreamingItems",
value: function beginStreamingItems() {
var _this2 = this;
this.application.streamItems({
contentType: snjs__WEBPACK_IMPORTED_MODULE_9__["CONTENT_TYPE_TAG"],
stream: function () {
var _stream = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee(_ref) {
var items, selectedTag;
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
items = _ref.items;
_context.next = 3;
return _this2.setState({
tags: _this2.application.getItems({
contentType: snjs__WEBPACK_IMPORTED_MODULE_9__["CONTENT_TYPE_TAG"]
}),
smartTags: _this2.application.getItems({
contentType: snjs__WEBPACK_IMPORTED_MODULE_9__["CONTENT_TYPE_SMART_TAG"]
})
});
case 3:
_this2.reloadNoteCounts();
if (_this2.state.selectedTag) {
/** If the selected tag has been deleted, revert to All view. */
selectedTag = items.find(function (tag) {
return tag.uuid === _this2.state.selectedTag.uuid;
});
if (selectedTag && selectedTag.deleted) {
_this2.selectTag(_this2.state.smartTags[0]);
}
}
case 5:
case "end":
return _context.stop();
}
}
}, _callee);
}));
function stream(_x) {
return _stream.apply(this, arguments);
}
return stream;
}()
});
}
}, {
key: "addAppStateObserver",
value: function addAppStateObserver() {
var _this3 = this;
this.appState.addObserver(function (eventName, data) {
if (eventName === _state__WEBPACK_IMPORTED_MODULE_11__["APP_STATE_EVENT_PREFERENCES_CHANGED"]) {
_this3.loadPreferences();
} else if (eventName === _state__WEBPACK_IMPORTED_MODULE_11__["APP_STATE_EVENT_TAG_CHANGED"]) {
_this3.setState({
selectedTag: _this3.appState.getSelectedTag()
});
}
});
}
}, {
key: "reloadNoteCounts",
value: function reloadNoteCounts() {
var allTags = [];
if (this.state.tags) {
allTags = allTags.concat(this.state.tags);
}
if (this.state.smartTags) {
allTags = allTags.concat(this.state.smartTags);
}
var noteCounts = {};
var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = undefined;
try {
for (var _iterator = allTags[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
var tag = _step.value;
var validNotes = snjs__WEBPACK_IMPORTED_MODULE_9__["SNNote"].filterDummyNotes(tag.notes).filter(function (note) {
return !note.archived && !note.content.trashed;
});
noteCounts[tag.uuid] = validNotes.length;
}
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
} finally {
try {
if (!_iteratorNormalCompletion && _iterator.return != null) {
_iterator.return();
}
} finally {
if (_didIteratorError) {
throw _iteratorError;
}
}
}
this.setState({
noteCounts: noteCounts
});
}
}, {
key: "loadPreferences",
value: function loadPreferences() {
var width = this.preferencesManager.getValue(_services_preferencesManager__WEBPACK_IMPORTED_MODULE_13__["PREF_TAGS_PANEL_WIDTH"]);
if (width) {
this.panelController.setWidth(width);
if (this.panelController.isCollapsed()) {
this.appState.panelDidResize({
name: _controllers_constants__WEBPACK_IMPORTED_MODULE_12__["PANEL_NAME_TAGS"],
collapsed: this.panelController.isCollapsed()
});
}
}
}
}, {
key: "registerComponentHandler",
value: function registerComponentHandler() {
var _this4 = this;
this.application.componentManager.registerHandler({
identifier: 'tags',
areas: ['tags-list'],
activationHandler: function activationHandler(component) {
_this4.component = component;
},
contextRequestHandler: function contextRequestHandler(component) {
return null;
},
actionHandler: function actionHandler(component, action, data) {
if (action === 'select-item') {
if (data.item.content_type === 'Tag') {
var tag = _this4.application.findItem({
uuid: data.item.uuid
});
if (tag) {
_this4.selectTag(tag);
}
} else if (data.item.content_type === 'SN|SmartTag') {
var smartTag = new snjs__WEBPACK_IMPORTED_MODULE_9__["SNSmartTag"](data.item);
_this4.selectTag(smartTag);
}
} else if (action === 'clear-selection') {
_this4.selectTag(_this4.state.smartTags[0]);
}
}
});
}
}, {
key: "selectTag",
value: function () {
var _selectTag = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee2(tag) {
var _this5 = this;
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee2$(_context2) {
while (1) {
switch (_context2.prev = _context2.next) {
case 0:
if (tag.isSmartTag()) {
Object.defineProperty(tag, 'notes', {
get: function get() {
return _this5.application.getNotesMatchingSmartTag({
smartTag: tag
});
}
});
}
if (tag.content.conflict_of) {
tag.content.conflict_of = null;
this.application.saveItem({
item: tag
});
}
this.appState.setSelectedTag(tag);
case 3:
case "end":
return _context2.stop();
}
}
}, _callee2, this);
}));
function selectTag(_x2) {
return _selectTag.apply(this, arguments);
}
return selectTag;
}()
}, {
key: "clickedAddNewTag",
value: function clickedAddNewTag() {
if (this.state.editingTag) {
return;
}
var newTag = this.application.createItem({
contentType: snjs__WEBPACK_IMPORTED_MODULE_9__["CONTENT_TYPE_TAG"]
});
this.setState({
previousTag: this.state.selectedTag,
selectedTag: newTag,
editingTag: newTag,
newTag: newTag
});
/** @todo Should not be accessing internal function */
/** Rely on local state instead of adding to global state */
this.application.modelManager.insertItems({
items: [newTag]
});
}
}, {
key: "tagTitleDidChange",
value: function tagTitleDidChange(tag) {
this.setState({
editingTag: tag
});
}
}, {
key: "saveTag",
value: function () {
var _saveTag = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee3($event, tag) {
var matchingTag, alreadyExists;
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee3$(_context3) {
while (1) {
switch (_context3.prev = _context3.next) {
case 0:
$event.target.blur();
_context3.next = 3;
return this.setState({
editingTag: null
});
case 3:
if (!(!tag.title || tag.title.length === 0)) {
_context3.next = 7;
break;
}
if (this.state.editingTag) {
tag.title = this.editingOriginalName;
this.editingOriginalName = null;
} else if (this.state.newTag) {
/** @todo Should not be accessing internal function */
/** Rely on local state instead of adding to global state */
this.application.modelManager.removeItemLocally(tag);
this.setState({
selectedTag: this.state.previousTag
});
}
this.setState({
newTag: null
});
return _context3.abrupt("return");
case 7:
this.editingOriginalName = null;
matchingTag = this.application.findTag({
title: tag.title
});
alreadyExists = matchingTag && matchingTag !== tag;
if (!(this.state.newTag === tag && alreadyExists)) {
_context3.next = 15;
break;
}
this.application.alertManager.alert({
text: "A tag with this name already exists."
});
/** @todo Should not be accessing internal function */
/** Rely on local state instead of adding to global state */
this.application.modelManager.removeItemLocally(tag);
this.setState({
newTag: null
});
return _context3.abrupt("return");
case 15:
this.application.saveItem({
item: tag
});
this.selectTag(tag);
this.setState({
newTag: null
});
case 18:
case "end":
return _context3.stop();
}
}
}, _callee3, this);
}));
function saveTag(_x3, _x4) {
return _saveTag.apply(this, arguments);
}
return saveTag;
}()
}, {
key: "selectedRenameTag",
value: function () {
var _selectedRenameTag = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee4($event, tag) {
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee4$(_context4) {
while (1) {
switch (_context4.prev = _context4.next) {
case 0:
this.editingOriginalName = tag.title;
_context4.next = 3;
return this.setState({
editingTag: tag
});
case 3:
document.getElementById('tag-' + tag.uuid).focus();
case 4:
case "end":
return _context4.stop();
}
}
}, _callee4, this);
}));
function selectedRenameTag(_x5, _x6) {
return _selectedRenameTag.apply(this, arguments);
}
return selectedRenameTag;
}()
}, {
key: "selectedDeleteTag",
value: function selectedDeleteTag(tag) {
this.removeTag(tag);
this.selectTag(this.state.smartTags[0]);
}
}, {
key: "removeTag",
value: function removeTag(tag) {
var _this6 = this;
this.application.alertManager.confirm({
text: _strings__WEBPACK_IMPORTED_MODULE_14__["STRING_DELETE_TAG"],
destructive: true,
onConfirm: function onConfirm() {
_this6.application.deleteItem({
item: tag
});
}
});
}
}]);
return TagsPanelCtrl;
}(_Controllers__WEBPACK_IMPORTED_MODULE_15__["PureCtrl"]);
var TagsPanel = function TagsPanel() {
_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2___default()(this, TagsPanel);
this.restrict = 'E';
this.scope = {};
this.template = _tags_pug__WEBPACK_IMPORTED_MODULE_10___default.a;
this.replace = true;
this.controller = TagsPanelCtrl;
this.controllerAs = 'self';
this.bindToController = true;
};
/***/ }),
/***/ "./app/assets/javascripts/directives/functional/autofocus.js":
/*!*******************************************************************!*\
!*** ./app/assets/javascripts/directives/functional/autofocus.js ***!
\*******************************************************************/
/*! exports provided: autofocus */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "autofocus", function() { return autofocus; });
autofocus.$inject = ["$timeout"];
/* @ngInject */
function autofocus($timeout) {
return {
restrict: 'A',
scope: {
shouldFocus: '='
},
link: function link($scope, $element) {
$timeout(function () {
if ($scope.shouldFocus) {
$element[0].focus();
}
});
}
};
}
/***/ }),
/***/ "./app/assets/javascripts/directives/functional/click-outside.js":
/*!***********************************************************************!*\
!*** ./app/assets/javascripts/directives/functional/click-outside.js ***!
\***********************************************************************/
/*! exports provided: clickOutside */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "clickOutside", function() { return clickOutside; });
clickOutside.$inject = ["$document"];
/* @ngInject */
function clickOutside($document) {
return {
restrict: 'A',
replace: false,
link: function link($scope, $element, attrs) {
var didApplyClickOutside = false;
$element.bind('click', function (e) {
didApplyClickOutside = false;
if (attrs.isOpen) {
e.stopPropagation();
}
});
$document.bind('click', function () {
// Ignore click if on SKAlert
if (event.target.closest(".sk-modal")) {
return;
}
if (!didApplyClickOutside) {
$scope.$apply(attrs.clickOutside);
didApplyClickOutside = true;
}
});
}
};
}
/***/ }),
/***/ "./app/assets/javascripts/directives/functional/delay-hide.js":
/*!********************************************************************!*\
!*** ./app/assets/javascripts/directives/functional/delay-hide.js ***!
\********************************************************************/
/*! exports provided: delayHide */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "delayHide", function() { return delayHide; });
/* harmony import */ var angular__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! angular */ "./node_modules/angular/index.js");
/* harmony import */ var angular__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(angular__WEBPACK_IMPORTED_MODULE_0__);
delayHide.$inject = ["$timeout"];
/* @ngInject */
function delayHide($timeout) {
return {
restrict: 'A',
scope: {
show: '=',
delay: '@'
},
link: function link(scope, elem, attrs) {
showElement(false); // This is where all the magic happens!
// Whenever the scope variable updates we simply
// show if it evaluates to 'true' and hide if 'false'
scope.$watch('show', function (newVal) {
newVal ? showSpinner() : hideSpinner();
});
function showSpinner() {
if (scope.hidePromise) {
$timeout.cancel(scope.hidePromise);
scope.hidePromise = null;
}
showElement(true);
}
function hideSpinner() {
scope.hidePromise = $timeout(showElement.bind(this, false), getDelay());
}
function showElement(show) {
show ? elem.css({
display: ''
}) : elem.css({
display: 'none'
});
}
function getDelay() {
var delay = parseInt(scope.delay);
return angular__WEBPACK_IMPORTED_MODULE_0___default.a.isNumber(delay) ? delay : 200;
}
}
};
}
/***/ }),
/***/ "./app/assets/javascripts/directives/functional/elemReady.js":
/*!*******************************************************************!*\
!*** ./app/assets/javascripts/directives/functional/elemReady.js ***!
\*******************************************************************/
/*! exports provided: elemReady */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "elemReady", function() { return elemReady; });
elemReady.$inject = ["$parse"];
/* @ngInject */
function elemReady($parse) {
return {
restrict: 'A',
link: function link($scope, elem, attrs) {
elem.ready(function () {
$scope.$apply(function () {
var func = $parse(attrs.elemReady);
func($scope);
});
});
}
};
}
/***/ }),
/***/ "./app/assets/javascripts/directives/functional/file-change.js":
/*!*********************************************************************!*\
!*** ./app/assets/javascripts/directives/functional/file-change.js ***!
\*********************************************************************/
/*! exports provided: fileChange */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "fileChange", function() { return fileChange; });
/* @ngInject */
function fileChange() {
return {
restrict: 'A',
scope: {
handler: '&'
},
link: function link(scope, element) {
element.on('change', function (event) {
scope.$apply(function () {
scope.handler({
files: event.target.files
});
});
});
}
};
}
/***/ }),
/***/ "./app/assets/javascripts/directives/functional/index.js":
/*!***************************************************************!*\
!*** ./app/assets/javascripts/directives/functional/index.js ***!
\***************************************************************/
/*! exports provided: autofocus, clickOutside, delayHide, elemReady, fileChange, infiniteScroll, lowercase, selectOnClick, snEnter */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _autofocus__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./autofocus */ "./app/assets/javascripts/directives/functional/autofocus.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "autofocus", function() { return _autofocus__WEBPACK_IMPORTED_MODULE_0__["autofocus"]; });
/* harmony import */ var _click_outside__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./click-outside */ "./app/assets/javascripts/directives/functional/click-outside.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "clickOutside", function() { return _click_outside__WEBPACK_IMPORTED_MODULE_1__["clickOutside"]; });
/* harmony import */ var _delay_hide__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./delay-hide */ "./app/assets/javascripts/directives/functional/delay-hide.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "delayHide", function() { return _delay_hide__WEBPACK_IMPORTED_MODULE_2__["delayHide"]; });
/* harmony import */ var _elemReady__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./elemReady */ "./app/assets/javascripts/directives/functional/elemReady.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "elemReady", function() { return _elemReady__WEBPACK_IMPORTED_MODULE_3__["elemReady"]; });
/* harmony import */ var _file_change__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./file-change */ "./app/assets/javascripts/directives/functional/file-change.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "fileChange", function() { return _file_change__WEBPACK_IMPORTED_MODULE_4__["fileChange"]; });
/* harmony import */ var _infiniteScroll__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./infiniteScroll */ "./app/assets/javascripts/directives/functional/infiniteScroll.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "infiniteScroll", function() { return _infiniteScroll__WEBPACK_IMPORTED_MODULE_5__["infiniteScroll"]; });
/* harmony import */ var _lowercase__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./lowercase */ "./app/assets/javascripts/directives/functional/lowercase.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "lowercase", function() { return _lowercase__WEBPACK_IMPORTED_MODULE_6__["lowercase"]; });
/* harmony import */ var _selectOnClick__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./selectOnClick */ "./app/assets/javascripts/directives/functional/selectOnClick.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "selectOnClick", function() { return _selectOnClick__WEBPACK_IMPORTED_MODULE_7__["selectOnClick"]; });
/* harmony import */ var _snEnter__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./snEnter */ "./app/assets/javascripts/directives/functional/snEnter.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "snEnter", function() { return _snEnter__WEBPACK_IMPORTED_MODULE_8__["snEnter"]; });
/***/ }),
/***/ "./app/assets/javascripts/directives/functional/infiniteScroll.js":
/*!************************************************************************!*\
!*** ./app/assets/javascripts/directives/functional/infiniteScroll.js ***!
\************************************************************************/
/*! exports provided: infiniteScroll */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "infiniteScroll", function() { return infiniteScroll; });
infiniteScroll.$inject = ["$rootScope", "$window", "$timeout"];
/* @ngInject */
function infiniteScroll($rootScope, $window, $timeout) {
return {
link: function link(scope, elem, attrs) {
var offset = parseInt(attrs.threshold) || 0;
var e = elem[0];
elem.on('scroll', function () {
if (scope.$eval(attrs.canLoad) && e.scrollTop + e.offsetHeight >= e.scrollHeight - offset) {
scope.$apply(attrs.infiniteScroll);
}
});
}
};
}
/***/ }),
/***/ "./app/assets/javascripts/directives/functional/lowercase.js":
/*!*******************************************************************!*\
!*** ./app/assets/javascripts/directives/functional/lowercase.js ***!
\*******************************************************************/
/*! exports provided: lowercase */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "lowercase", function() { return lowercase; });
/* @ngInject */
function lowercase() {
return {
require: 'ngModel',
link: function link(scope, element, attrs, modelCtrl) {
var lowercase = function lowercase(inputValue) {
if (inputValue === undefined) inputValue = '';
var lowercased = inputValue.toLowerCase();
if (lowercased !== inputValue) {
modelCtrl.$setViewValue(lowercased);
modelCtrl.$render();
}
return lowercased;
};
modelCtrl.$parsers.push(lowercase);
lowercase(scope[attrs.ngModel]);
}
};
}
/***/ }),
/***/ "./app/assets/javascripts/directives/functional/selectOnClick.js":
/*!***********************************************************************!*\
!*** ./app/assets/javascripts/directives/functional/selectOnClick.js ***!
\***********************************************************************/
/*! exports provided: selectOnClick */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "selectOnClick", function() { return selectOnClick; });
selectOnClick.$inject = ["$window"];
/* @ngInject */
function selectOnClick($window) {
return {
restrict: 'A',
link: function link(scope, element, attrs) {
element.on('focus', function () {
if (!$window.getSelection().toString()) {
/** Required for mobile Safari */
this.setSelectionRange(0, this.value.length);
}
});
}
};
}
/***/ }),
/***/ "./app/assets/javascripts/directives/functional/snEnter.js":
/*!*****************************************************************!*\
!*** ./app/assets/javascripts/directives/functional/snEnter.js ***!
\*****************************************************************/
/*! exports provided: snEnter */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "snEnter", function() { return snEnter; });
/* @ngInject */
function snEnter() {
return function (scope, element, attrs) {
element.bind('keydown keypress', function (event) {
if (event.which === 13) {
scope.$apply(function () {
scope.$eval(attrs.snEnter, {
event: event
});
});
event.preventDefault();
}
});
};
}
/***/ }),
/***/ "./app/assets/javascripts/directives/views/accountMenu.js":
/*!****************************************************************!*\
!*** ./app/assets/javascripts/directives/views/accountMenu.js ***!
\****************************************************************/
/*! exports provided: AccountMenu */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AccountMenu", function() { return AccountMenu; });
/* harmony import */ var _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/regenerator */ "./node_modules/@babel/runtime/regenerator/index.js");
/* harmony import */ var _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/helpers/defineProperty */ "./node_modules/@babel/runtime/helpers/defineProperty.js");
/* harmony import */ var _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @babel/runtime/helpers/asyncToGenerator */ "./node_modules/@babel/runtime/helpers/asyncToGenerator.js");
/* harmony import */ var _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "./node_modules/@babel/runtime/helpers/classCallCheck.js");
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @babel/runtime/helpers/createClass */ "./node_modules/@babel/runtime/helpers/createClass.js");
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_4__);
/* harmony import */ var _babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "./node_modules/@babel/runtime/helpers/possibleConstructorReturn.js");
/* harmony import */ var _babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_5___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_5__);
/* harmony import */ var _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "./node_modules/@babel/runtime/helpers/getPrototypeOf.js");
/* harmony import */ var _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_6___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_6__);
/* harmony import */ var _babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! @babel/runtime/helpers/inherits */ "./node_modules/@babel/runtime/helpers/inherits.js");
/* harmony import */ var _babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_7___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_7__);
/* harmony import */ var _utils__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! @/utils */ "./app/assets/javascripts/utils.js");
/* harmony import */ var _directives_account_menu_pug__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! %/directives/account-menu.pug */ "./app/assets/templates/directives/account-menu.pug");
/* harmony import */ var _directives_account_menu_pug__WEBPACK_IMPORTED_MODULE_9___default = /*#__PURE__*/__webpack_require__.n(_directives_account_menu_pug__WEBPACK_IMPORTED_MODULE_9__);
/* harmony import */ var snjs__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! snjs */ "../snjs/dist/snjs.js");
/* harmony import */ var snjs__WEBPACK_IMPORTED_MODULE_10___default = /*#__PURE__*/__webpack_require__.n(snjs__WEBPACK_IMPORTED_MODULE_10__);
/* harmony import */ var _Controllers__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! @Controllers */ "./app/assets/javascripts/controllers/index.js");
/* harmony import */ var _strings__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! @/strings */ "./app/assets/javascripts/strings.js");
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_1___default()(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
var ELEMENT_ID_IMPORT_PASSWORD_INPUT = 'import-password-request';
var ELEMENT_NAME_AUTH_EMAIL = 'email';
var ELEMENT_NAME_AUTH_PASSWORD = 'password';
var ELEMENT_NAME_AUTH_PASSWORD_CONF = 'password_conf';
var AccountMenuCtrl =
/*#__PURE__*/
function (_PureCtrl) {
AccountMenuCtrl.$inject = ["$scope", "$rootScope", "$timeout", "archiveManager", "appVersion", "godService", "lockManager", "application"];
_babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_7___default()(AccountMenuCtrl, _PureCtrl);
/* @ngInject */
function AccountMenuCtrl($scope, $rootScope, $timeout, archiveManager, appVersion, godService, lockManager, application) {
var _this;
_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_3___default()(this, AccountMenuCtrl);
_this = _babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_5___default()(this, _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_6___default()(AccountMenuCtrl).call(this, $timeout));
_this.$scope = $scope;
_this.$rootScope = $rootScope;
_this.$timeout = $timeout;
_this.archiveManager = archiveManager;
_this.godService = godService;
_this.lockManager = lockManager;
_this.application = application;
_this.state = {
appVersion: 'v' + (window.electronAppVersion || appVersion),
user: _this.application.getUser(),
canAddPasscode: !_this.application.isEphemeralSession(),
passcodeAutoLockOptions: _this.lockManager.getAutoLockIntervalOptions(),
formData: {
mergeLocal: true,
ephemeral: false
},
mutable: {}
};
_this.syncStatus = _this.application.getSyncStatus();
_this.loadHost();
_this.checkForSecurityUpdate();
_this.reloadAutoLockInterval();
_this.loadBackupsAvailability();
return _this;
}
_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_4___default()(AccountMenuCtrl, [{
key: "$onInit",
value: function $onInit() {
this.initProps({
closeFunction: this.closeFunction
});
}
}, {
key: "close",
value: function close() {
var _this2 = this;
this.$timeout(function () {
_this2.props.closeFunction()();
});
}
}, {
key: "loadHost",
value: function () {
var _loadHost = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_2___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee() {
var host;
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
_context.next = 2;
return this.application.getHost();
case 2:
host = _context.sent;
this.setState({
server: host,
formData: _objectSpread({}, this.state.formData, {
url: host
})
});
case 4:
case "end":
return _context.stop();
}
}
}, _callee, this);
}));
function loadHost() {
return _loadHost.apply(this, arguments);
}
return loadHost;
}()
}, {
key: "checkForSecurityUpdate",
value: function () {
var _checkForSecurityUpdate = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_2___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee2() {
var available;
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee2$(_context2) {
while (1) {
switch (_context2.prev = _context2.next) {
case 0:
_context2.next = 2;
return this.godService.checkForSecurityUpdate();
case 2:
available = _context2.sent;
this.setState({
securityUpdateAvailable: available
});
case 4:
case "end":
return _context2.stop();
}
}
}, _callee2, this);
}));
function checkForSecurityUpdate() {
return _checkForSecurityUpdate.apply(this, arguments);
}
return checkForSecurityUpdate;
}()
}, {
key: "loadBackupsAvailability",
value: function () {
var _loadBackupsAvailability = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_2___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee3() {
var hasUser, hasPasscode, encryptedAvailable, encryptionStatusString;
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee3$(_context3) {
while (1) {
switch (_context3.prev = _context3.next) {
case 0:
encryptionStatusString = function _ref() {
if (hasUser) {
return _strings__WEBPACK_IMPORTED_MODULE_12__["STRING_E2E_ENABLED"];
} else if (hasPasscode) {
return _strings__WEBPACK_IMPORTED_MODULE_12__["STRING_LOCAL_ENC_ENABLED"];
} else {
return _strings__WEBPACK_IMPORTED_MODULE_12__["STRING_ENC_NOT_ENABLED"];
}
};
_context3.t0 = _utils__WEBPACK_IMPORTED_MODULE_8__["isNullOrUndefined"];
_context3.next = 4;
return this.application.getUser();
case 4:
_context3.t1 = _context3.sent;
hasUser = !(0, _context3.t0)(_context3.t1);
_context3.next = 8;
return this.application.hasPasscode();
case 8:
hasPasscode = _context3.sent;
encryptedAvailable = hasUser || hasPasscode;
this.setState({
encryptionStatusString: encryptionStatusString(),
encryptionEnabled: encryptedAvailable,
mutable: _objectSpread({}, this.state.mutable, {
backupEncrypted: encryptedAvailable
})
});
case 11:
case "end":
return _context3.stop();
}
}
}, _callee3, this);
}));
function loadBackupsAvailability() {
return _loadBackupsAvailability.apply(this, arguments);
}
return loadBackupsAvailability;
}()
}, {
key: "submitMfaForm",
value: function submitMfaForm() {
this.login();
}
}, {
key: "blurAuthFields",
value: function blurAuthFields() {
var names = [ELEMENT_NAME_AUTH_EMAIL, ELEMENT_NAME_AUTH_PASSWORD, ELEMENT_NAME_AUTH_PASSWORD_CONF];
for (var _i = 0, _names = names; _i < _names.length; _i++) {
var name = _names[_i];
var element = document.getElementsByName(name)[0];
if (element) {
element.blur();
}
}
}
}, {
key: "submitAuthForm",
value: function submitAuthForm() {
if (!this.state.formData.email || !this.state.formData.user_password) {
return;
}
this.blurAuthFields();
if (this.state.formData.showLogin) {
this.login();
} else {
this.register();
}
}
}, {
key: "setFormDataState",
value: function () {
var _setFormDataState = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_2___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee4(formData) {
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee4$(_context4) {
while (1) {
switch (_context4.prev = _context4.next) {
case 0:
return _context4.abrupt("return", this.setState({
formData: _objectSpread({}, this.state.formData, {}, formData)
}));
case 1:
case "end":
return _context4.stop();
}
}
}, _callee4, this);
}));
function setFormDataState(_x) {
return _setFormDataState.apply(this, arguments);
}
return setFormDataState;
}()
}, {
key: "login",
value: function () {
var _login = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_2___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee5() {
var response, hasError, error;
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee5$(_context5) {
while (1) {
switch (_context5.prev = _context5.next) {
case 0:
_context5.next = 2;
return this.setFormDataState({
status: _strings__WEBPACK_IMPORTED_MODULE_12__["STRING_GENERATING_LOGIN_KEYS"],
authenticating: true
});
case 2:
_context5.next = 4;
return this.application.signIn({
email: this.state.formData.email,
password: this.state.formData.user_password,
strict: this.state.formData.strictSignin,
ephemeral: this.state.formData.ephemeral,
mfaKeyPath: this.state.formData.mfa.payload.mfa_key,
mfaCode: this.state.formData.userMfaCode,
mergeLocal: this.state.formData.mergeLocal
});
case 4:
response = _context5.sent;
hasError = !response || response.error;
if (hasError) {
_context5.next = 10;
break;
}
_context5.next = 9;
return this.onAuthSuccess();
case 9:
return _context5.abrupt("return");
case 10:
_context5.next = 12;
return this.setFormDataState({
status: null
});
case 12:
error = response ? response.error : {
message: "An unknown error occured."
};
if (!(error.tag === 'mfa-required' || error.tag === 'mfa-invalid')) {
_context5.next = 18;
break;
}
_context5.next = 16;
return this.setFormDataState({
showLogin: false,
mfa: error
});
case 16:
_context5.next = 21;
break;
case 18:
_context5.next = 20;
return this.setFormDataState({
showLogin: true,
mfa: null
});
case 20:
if (error.message) {
this.application.alertManager.alert({
text: error.message
});
}
case 21:
_context5.next = 23;
return this.setFormDataState({
authenticating: false
});
case 23:
case "end":
return _context5.stop();
}
}
}, _callee5, this);
}));
function login() {
return _login.apply(this, arguments);
}
return login;
}()
}, {
key: "register",
value: function () {
var _register = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_2___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee6() {
var confirmation, response, error;
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee6$(_context6) {
while (1) {
switch (_context6.prev = _context6.next) {
case 0:
confirmation = this.state.formData.password_conf;
if (!(confirmation !== this.state.formData.user_password)) {
_context6.next = 4;
break;
}
this.application.alertManager.alert({
text: _strings__WEBPACK_IMPORTED_MODULE_12__["STRING_NON_MATCHING_PASSWORDS"]
});
return _context6.abrupt("return");
case 4:
_context6.next = 6;
return this.setFormDataState({
confirmPassword: false,
status: _strings__WEBPACK_IMPORTED_MODULE_12__["STRING_GENERATING_REGISTER_KEYS"],
authenticating: true
});
case 6:
_context6.next = 8;
return this.application.register({
email: this.state.formData.email,
password: this.state.formData.user_password,
ephemeral: this.state.formData.ephemeral,
mergeLocal: this.state.formData.mergeLocal
});
case 8:
response = _context6.sent;
if (!(!response || response.error)) {
_context6.next = 18;
break;
}
_context6.next = 12;
return this.setFormDataState({
status: null
});
case 12:
error = response ? response.error : {
message: "An unknown error occured."
};
_context6.next = 15;
return this.setFormDataState({
authenticating: false
});
case 15:
this.application.alertManager.alert({
text: error.message
});
_context6.next = 21;
break;
case 18:
_context6.next = 20;
return this.onAuthSuccess();
case 20:
this.application.sync();
case 21:
case "end":
return _context6.stop();
}
}
}, _callee6, this);
}));
function register() {
return _register.apply(this, arguments);
}
return register;
}()
}, {
key: "mergeLocalChanged",
value: function mergeLocalChanged() {
var _this3 = this;
if (!this.state.formData.mergeLocal) {
this.application.alertManager.confirm({
text: _strings__WEBPACK_IMPORTED_MODULE_12__["STRING_ACCOUNT_MENU_UNCHECK_MERGE"],
destructive: true,
onCancel: function onCancel() {
_this3.setFormDataState({
mergeLocal: true
});
}
});
}
}
}, {
key: "onAuthSuccess",
value: function () {
var _onAuthSuccess = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_2___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee7() {
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee7$(_context7) {
while (1) {
switch (_context7.prev = _context7.next) {
case 0:
if (!this.state.formData.mergeLocal) {
_context7.next = 4;
break;
}
this.$rootScope.$broadcast('major-data-change');
_context7.next = 4;
return this.rewriteDatabase({
alternateUuids: true
});
case 4:
_context7.next = 6;
return this.setFormDataState({
authenticating: false
});
case 6:
this.close();
case 7:
case "end":
return _context7.stop();
}
}
}, _callee7, this);
}));
function onAuthSuccess() {
return _onAuthSuccess.apply(this, arguments);
}
return onAuthSuccess;
}()
}, {
key: "openPasswordWizard",
value: function openPasswordWizard(type) {
this.close();
this.godService.presentPasswordWizard(type);
}
}, {
key: "openPrivilegesModal",
value: function () {
var _openPrivilegesModal = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_2___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee8() {
var _this4 = this;
var run, needsPrivilege;
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee8$(_context8) {
while (1) {
switch (_context8.prev = _context8.next) {
case 0:
this.close();
run = function run() {
_this4.godService.presentPrivilegesManagementModal();
};
_context8.next = 4;
return this.application.privilegesManager.actionRequiresPrivilege(snjs__WEBPACK_IMPORTED_MODULE_10__["ProtectedActions"].ManagePrivileges);
case 4:
needsPrivilege = _context8.sent;
if (needsPrivilege) {
this.godService.presentPrivilegesModal(snjs__WEBPACK_IMPORTED_MODULE_10__["ProtectedActions"].ManagePrivileges, function () {
run();
});
} else {
run();
}
case 6:
case "end":
return _context8.stop();
}
}
}, _callee8, this);
}));
function openPrivilegesModal() {
return _openPrivilegesModal.apply(this, arguments);
}
return openPrivilegesModal;
}()
/**
* Allows IndexedDB unencrypted logs to be deleted
* `clearAllPayloads` will remove data from backing store,
* but not from working memory See:
* https://github.com/standardnotes/desktop/issues/131
*/
}, {
key: "rewriteDatabase",
value: function () {
var _rewriteDatabase = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_2___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee9() {
var _ref2,
alternateUuids,
_args9 = arguments;
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee9$(_context9) {
while (1) {
switch (_context9.prev = _context9.next) {
case 0:
_ref2 = _args9.length > 0 && _args9[0] !== undefined ? _args9[0] : {}, alternateUuids = _ref2.alternateUuids;
_context9.next = 3;
return this.application.destroyDatabase();
case 3:
_context9.next = 5;
return this.application.markAllItemsAsNeedingSync({
alternateUuids: alternateUuids
});
case 5:
case "end":
return _context9.stop();
}
}
}, _callee9, this);
}));
function rewriteDatabase() {
return _rewriteDatabase.apply(this, arguments);
}
return rewriteDatabase;
}()
}, {
key: "destroyLocalData",
value: function destroyLocalData() {
var _this5 = this;
this.application.alertManager.confirm({
text: _strings__WEBPACK_IMPORTED_MODULE_12__["STRING_SIGN_OUT_CONFIRMATION"],
destructive: true,
onConfirm: function () {
var _onConfirm = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_2___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee10() {
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee10$(_context10) {
while (1) {
switch (_context10.prev = _context10.next) {
case 0:
_context10.next = 2;
return _this5.application.signOut();
case 2:
window.location.reload();
case 3:
case "end":
return _context10.stop();
}
}
}, _callee10);
}));
function onConfirm() {
return _onConfirm.apply(this, arguments);
}
return onConfirm;
}()
});
}
}, {
key: "submitImportPassword",
value: function () {
var _submitImportPassword = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_2___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee11() {
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee11$(_context11) {
while (1) {
switch (_context11.prev = _context11.next) {
case 0:
_context11.next = 2;
return this.performImport(this.state.importData.data, this.state.importData.password);
case 2:
case "end":
return _context11.stop();
}
}
}, _callee11, this);
}));
function submitImportPassword() {
return _submitImportPassword.apply(this, arguments);
}
return submitImportPassword;
}()
}, {
key: "readFile",
value: function () {
var _readFile = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_2___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee12(file) {
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee12$(_context12) {
while (1) {
switch (_context12.prev = _context12.next) {
case 0:
return _context12.abrupt("return", new Promise(function (resolve, reject) {
var reader = new FileReader();
reader.onload = function (e) {
try {
var data = JSON.parse(e.target.result);
resolve(data);
} catch (e) {
this.application.alertManager.alert({
text: _strings__WEBPACK_IMPORTED_MODULE_12__["STRING_INVALID_IMPORT_FILE"]
});
}
};
reader.readAsText(file);
}));
case 1:
case "end":
return _context12.stop();
}
}
}, _callee12);
}));
function readFile(_x2) {
return _readFile.apply(this, arguments);
}
return readFile;
}()
/**
* @template
*/
}, {
key: "importFileSelected",
value: function () {
var _importFileSelected = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_2___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee14(files) {
var _this6 = this;
var run, needsPrivilege;
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee14$(_context14) {
while (1) {
switch (_context14.prev = _context14.next) {
case 0:
run =
/*#__PURE__*/
function () {
var _ref3 = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_2___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee13() {
var file, data, element;
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee13$(_context13) {
while (1) {
switch (_context13.prev = _context13.next) {
case 0:
file = files[0];
_context13.next = 3;
return _this6.readFile(file);
case 3:
data = _context13.sent;
if (data) {
_context13.next = 6;
break;
}
return _context13.abrupt("return");
case 6:
if (!data.auth_params) {
_context13.next = 13;
break;
}
_context13.next = 9;
return _this6.setState({
importData: _objectSpread({}, _this6.state.importData, {
requestPassword: true,
data: data
})
});
case 9:
element = document.getElementById(ELEMENT_ID_IMPORT_PASSWORD_INPUT);
if (element) {
element.scrollIntoView(false);
}
_context13.next = 15;
break;
case 13:
_context13.next = 15;
return _this6.performImport(data, null);
case 15:
case "end":
return _context13.stop();
}
}
}, _callee13);
}));
return function run() {
return _ref3.apply(this, arguments);
};
}();
_context14.next = 3;
return this.application.privilegesManager.actionRequiresPrivilege(snjs__WEBPACK_IMPORTED_MODULE_10__["ProtectedActions"].ManageBackups);
case 3:
needsPrivilege = _context14.sent;
if (needsPrivilege) {
this.godService.presentPrivilegesModal(snjs__WEBPACK_IMPORTED_MODULE_10__["ProtectedActions"].ManageBackups, run);
} else {
run();
}
case 5:
case "end":
return _context14.stop();
}
}
}, _callee14, this);
}));
function importFileSelected(_x3) {
return _importFileSelected.apply(this, arguments);
}
return importFileSelected;
}()
}, {
key: "performImport",
value: function () {
var _performImport = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_2___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee15(data, password) {
var errorCount, message;
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee15$(_context15) {
while (1) {
switch (_context15.prev = _context15.next) {
case 0:
_context15.next = 2;
return this.setState({
importData: _objectSpread({}, this.state.importData, {
loading: true
})
});
case 2:
_context15.next = 4;
return this.importJSONData(data, password);
case 4:
errorCount = _context15.sent;
this.setState({
importData: null
});
if (errorCount > 0) {
message = Object(_strings__WEBPACK_IMPORTED_MODULE_12__["StringImportError"])({
errorCount: errorCount
});
this.application.alertManager.alert({
text: message
});
} else {
this.application.alertManager.alert({
text: _strings__WEBPACK_IMPORTED_MODULE_12__["STRING_IMPORT_SUCCESS"]
});
}
case 7:
case "end":
return _context15.stop();
}
}
}, _callee15, this);
}));
function performImport(_x4, _x5) {
return _performImport.apply(this, arguments);
}
return performImport;
}()
}, {
key: "importJSONData",
value: function () {
var _importJSONData = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_2___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee16(data, password) {
var _ref4, affectedItems, errorCount, _iteratorNormalCompletion, _didIteratorError, _iteratorError, _iterator, _step, item;
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee16$(_context16) {
while (1) {
switch (_context16.prev = _context16.next) {
case 0:
_context16.next = 2;
return this.application.importData({
data: data.items,
password: password
});
case 2:
_ref4 = _context16.sent;
affectedItems = _ref4.affectedItems;
errorCount = _ref4.errorCount;
_iteratorNormalCompletion = true;
_didIteratorError = false;
_iteratorError = undefined;
_context16.prev = 8;
for (_iterator = affectedItems[Symbol.iterator](); !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
item = _step.value;
/**
* Don't want to activate any components during import process in
* case of exceptions breaking up the import proccess
*/
if (item.content_type === 'SN|Component') {
item.active = false;
}
}
_context16.next = 16;
break;
case 12:
_context16.prev = 12;
_context16.t0 = _context16["catch"](8);
_didIteratorError = true;
_iteratorError = _context16.t0;
case 16:
_context16.prev = 16;
_context16.prev = 17;
if (!_iteratorNormalCompletion && _iterator.return != null) {
_iterator.return();
}
case 19:
_context16.prev = 19;
if (!_didIteratorError) {
_context16.next = 22;
break;
}
throw _iteratorError;
case 22:
return _context16.finish(19);
case 23:
return _context16.finish(16);
case 24:
return _context16.abrupt("return", errorCount);
case 25:
case "end":
return _context16.stop();
}
}
}, _callee16, this, [[8, 12, 16, 24], [17,, 19, 23]]);
}));
function importJSONData(_x6, _x7) {
return _importJSONData.apply(this, arguments);
}
return importJSONData;
}()
}, {
key: "downloadDataArchive",
value: function () {
var _downloadDataArchive = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_2___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee17() {
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee17$(_context17) {
while (1) {
switch (_context17.prev = _context17.next) {
case 0:
this.archiveManager.downloadBackup(this.state.mutable.backupEncrypted);
case 1:
case "end":
return _context17.stop();
}
}
}, _callee17, this);
}));
function downloadDataArchive() {
return _downloadDataArchive.apply(this, arguments);
}
return downloadDataArchive;
}()
}, {
key: "notesAndTagsCount",
value: function notesAndTagsCount() {
return this.application.getItems({
contentType: ['Note', 'Tag']
}).length;
}
}, {
key: "encryptionStatusForNotes",
value: function encryptionStatusForNotes() {
var length = this.notesAndTagsCount();
return length + "/" + length + " notes and tags encrypted";
}
}, {
key: "reloadAutoLockInterval",
value: function () {
var _reloadAutoLockInterval = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_2___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee18() {
var interval;
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee18$(_context18) {
while (1) {
switch (_context18.prev = _context18.next) {
case 0:
_context18.next = 2;
return this.lockManager.getAutoLockInterval();
case 2:
interval = _context18.sent;
this.setState({
selectedAutoLockInterval: interval
});
case 4:
case "end":
return _context18.stop();
}
}
}, _callee18, this);
}));
function reloadAutoLockInterval() {
return _reloadAutoLockInterval.apply(this, arguments);
}
return reloadAutoLockInterval;
}()
}, {
key: "selectAutoLockInterval",
value: function () {
var _selectAutoLockInterval = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_2___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee20(interval) {
var _this7 = this;
var run, needsPrivilege;
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee20$(_context20) {
while (1) {
switch (_context20.prev = _context20.next) {
case 0:
run =
/*#__PURE__*/
function () {
var _ref5 = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_2___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee19() {
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee19$(_context19) {
while (1) {
switch (_context19.prev = _context19.next) {
case 0:
_context19.next = 2;
return _this7.lockManager.setAutoLockInterval(interval);
case 2:
_this7.reloadAutoLockInterval();
case 3:
case "end":
return _context19.stop();
}
}
}, _callee19);
}));
return function run() {
return _ref5.apply(this, arguments);
};
}();
_context20.next = 3;
return this.application.privilegesManager.actionRequiresPrivilege(snjs__WEBPACK_IMPORTED_MODULE_10__["ProtectedActions"].ManagePasscode);
case 3:
needsPrivilege = _context20.sent;
if (needsPrivilege) {
this.godService.presentPrivilegesModal(snjs__WEBPACK_IMPORTED_MODULE_10__["ProtectedActions"].ManagePasscode, function () {
run();
});
} else {
run();
}
case 5:
case "end":
return _context20.stop();
}
}
}, _callee20, this);
}));
function selectAutoLockInterval(_x8) {
return _selectAutoLockInterval.apply(this, arguments);
}
return selectAutoLockInterval;
}()
}, {
key: "hasPasscode",
value: function hasPasscode() {
return this.application.hasPasscode();
}
}, {
key: "addPasscodeClicked",
value: function addPasscodeClicked() {
this.setFormDataState({
showPasscodeForm: true
});
}
}, {
key: "submitPasscodeForm",
value: function submitPasscodeForm() {
var _this8 = this;
var passcode = this.state.formData.passcode;
if (passcode !== this.state.formData.confirmPasscode) {
this.application.alertManager.alert({
text: _strings__WEBPACK_IMPORTED_MODULE_12__["STRING_NON_MATCHING_PASSCODES"]
});
return;
}
var func = this.state.formData.changingPasscode ? this.application.changePasscode.bind(this.application) : this.application.setPasscode.bind(this.application);
func(passcode,
/*#__PURE__*/
_babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_2___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee21() {
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee21$(_context21) {
while (1) {
switch (_context21.prev = _context21.next) {
case 0:
_context21.next = 2;
return _this8.setFormDataState({
passcode: null,
confirmPasscode: null,
showPasscodeForm: false
});
case 2:
_context21.t0 = _utils__WEBPACK_IMPORTED_MODULE_8__["isNullOrUndefined"];
_context21.next = 5;
return _this8.application.getUser();
case 5:
_context21.t1 = _context21.sent;
if (!(0, _context21.t0)(_context21.t1)) {
_context21.next = 9;
break;
}
_this8.$rootScope.$broadcast('major-data-change');
_this8.rewriteDatabase();
case 9:
case "end":
return _context21.stop();
}
}
}, _callee21);
})));
}
}, {
key: "changePasscodePressed",
value: function () {
var _changePasscodePressed = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_2___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee22() {
var _this9 = this;
var run, needsPrivilege;
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee22$(_context22) {
while (1) {
switch (_context22.prev = _context22.next) {
case 0:
run = function run() {
_this9.state.formData.changingPasscode = true;
_this9.addPasscodeClicked();
};
_context22.next = 3;
return this.application.privilegesManager.actionRequiresPrivilege(snjs__WEBPACK_IMPORTED_MODULE_10__["ProtectedActions"].ManagePasscode);
case 3:
needsPrivilege = _context22.sent;
if (needsPrivilege) {
this.godService.presentPrivilegesModal(snjs__WEBPACK_IMPORTED_MODULE_10__["ProtectedActions"].ManagePasscode, run);
} else {
run();
}
case 5:
case "end":
return _context22.stop();
}
}
}, _callee22, this);
}));
function changePasscodePressed() {
return _changePasscodePressed.apply(this, arguments);
}
return changePasscodePressed;
}()
}, {
key: "removePasscodePressed",
value: function () {
var _removePasscodePressed = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_2___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee24() {
var _this10 = this;
var run;
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee24$(_context24) {
while (1) {
switch (_context24.prev = _context24.next) {
case 0:
run =
/*#__PURE__*/
function () {
var _ref7 = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_2___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee23() {
var signedIn, message;
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee23$(_context23) {
while (1) {
switch (_context23.prev = _context23.next) {
case 0:
_context23.t0 = _utils__WEBPACK_IMPORTED_MODULE_8__["isNullOrUndefined"];
_context23.next = 3;
return _this10.application.getUser();
case 3:
_context23.t1 = _context23.sent;
signedIn = !(0, _context23.t0)(_context23.t1);
message = _strings__WEBPACK_IMPORTED_MODULE_12__["STRING_REMOVE_PASSCODE_CONFIRMATION"];
if (!signedIn) {
message += _strings__WEBPACK_IMPORTED_MODULE_12__["STRING_REMOVE_PASSCODE_OFFLINE_ADDENDUM"];
}
_this10.application.alertManager.confirm({
text: message,
destructive: true,
onConfirm: function onConfirm() {
_this10.application.removePasscode();
}
});
case 8:
case "end":
return _context23.stop();
}
}
}, _callee23);
}));
return function run() {
return _ref7.apply(this, arguments);
};
}();
this.godService.presentPrivilegesModal(snjs__WEBPACK_IMPORTED_MODULE_10__["ProtectedActions"].ManagePasscode, run);
case 2:
case "end":
return _context24.stop();
}
}
}, _callee24, this);
}));
function removePasscodePressed() {
return _removePasscodePressed.apply(this, arguments);
}
return removePasscodePressed;
}()
}, {
key: "isDesktopApplication",
value: function isDesktopApplication() {
return Object(_utils__WEBPACK_IMPORTED_MODULE_8__["isDesktopApplication"])();
}
}]);
return AccountMenuCtrl;
}(_Controllers__WEBPACK_IMPORTED_MODULE_11__["PureCtrl"]);
var AccountMenu = function AccountMenu() {
_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_3___default()(this, AccountMenu);
this.restrict = 'E';
this.template = _directives_account_menu_pug__WEBPACK_IMPORTED_MODULE_9___default.a;
this.controller = AccountMenuCtrl;
this.controllerAs = 'self';
this.bindToController = true;
this.scope = {
closeFunction: '&'
};
};
/***/ }),
/***/ "./app/assets/javascripts/directives/views/actionsMenu.js":
/*!****************************************************************!*\
!*** ./app/assets/javascripts/directives/views/actionsMenu.js ***!
\****************************************************************/
/*! exports provided: ActionsMenu */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ActionsMenu", function() { return ActionsMenu; });
/* harmony import */ var _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/regenerator */ "./node_modules/@babel/runtime/regenerator/index.js");
/* harmony import */ var _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/helpers/asyncToGenerator */ "./node_modules/@babel/runtime/helpers/asyncToGenerator.js");
/* harmony import */ var _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "./node_modules/@babel/runtime/helpers/classCallCheck.js");
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @babel/runtime/helpers/createClass */ "./node_modules/@babel/runtime/helpers/createClass.js");
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var _babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "./node_modules/@babel/runtime/helpers/possibleConstructorReturn.js");
/* harmony import */ var _babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_4__);
/* harmony import */ var _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "./node_modules/@babel/runtime/helpers/getPrototypeOf.js");
/* harmony import */ var _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_5___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_5__);
/* harmony import */ var _babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! @babel/runtime/helpers/inherits */ "./node_modules/@babel/runtime/helpers/inherits.js");
/* harmony import */ var _babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_6___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_6__);
/* harmony import */ var _directives_actions_menu_pug__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! %/directives/actions-menu.pug */ "./app/assets/templates/directives/actions-menu.pug");
/* harmony import */ var _directives_actions_menu_pug__WEBPACK_IMPORTED_MODULE_7___default = /*#__PURE__*/__webpack_require__.n(_directives_actions_menu_pug__WEBPACK_IMPORTED_MODULE_7__);
/* harmony import */ var _Controllers__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! @Controllers */ "./app/assets/javascripts/controllers/index.js");
var ActionsMenuCtrl =
/*#__PURE__*/
function (_PureCtrl) {
ActionsMenuCtrl.$inject = ["$scope", "$timeout", "actionsManager", "godService"];
_babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_6___default()(ActionsMenuCtrl, _PureCtrl);
/* @ngInject */
function ActionsMenuCtrl($scope, $timeout, actionsManager, godService) {
var _this;
_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2___default()(this, ActionsMenuCtrl);
_this = _babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_4___default()(this, _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_5___default()(ActionsMenuCtrl).call(this, $timeout));
_this.$timeout = $timeout;
_this.actionsManager = actionsManager;
_this.godService = godService;
return _this;
}
_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3___default()(ActionsMenuCtrl, [{
key: "$onInit",
value: function $onInit() {
this.initProps({
item: this.item
});
this.loadExtensions();
}
}, {
key: "loadExtensions",
value: function () {
var _loadExtensions = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee() {
var extensions, _iteratorNormalCompletion, _didIteratorError, _iteratorError, _iterator, _step, extension;
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
extensions = this.actionsManager.extensions.sort(function (a, b) {
return a.name.toLowerCase() < b.name.toLowerCase() ? -1 : 1;
});
_iteratorNormalCompletion = true;
_didIteratorError = false;
_iteratorError = undefined;
_context.prev = 4;
_iterator = extensions[Symbol.iterator]();
case 6:
if (_iteratorNormalCompletion = (_step = _iterator.next()).done) {
_context.next = 15;
break;
}
extension = _step.value;
extension.loading = true;
_context.next = 11;
return this.actionsManager.loadExtensionInContextOfItem(extension, this.props.item);
case 11:
extension.loading = false;
case 12:
_iteratorNormalCompletion = true;
_context.next = 6;
break;
case 15:
_context.next = 21;
break;
case 17:
_context.prev = 17;
_context.t0 = _context["catch"](4);
_didIteratorError = true;
_iteratorError = _context.t0;
case 21:
_context.prev = 21;
_context.prev = 22;
if (!_iteratorNormalCompletion && _iterator.return != null) {
_iterator.return();
}
case 24:
_context.prev = 24;
if (!_didIteratorError) {
_context.next = 27;
break;
}
throw _iteratorError;
case 27:
return _context.finish(24);
case 28:
return _context.finish(21);
case 29:
this.setState({
extensions: extensions
});
case 30:
case "end":
return _context.stop();
}
}
}, _callee, this, [[4, 17, 21, 29], [22,, 24, 28]]);
}));
function loadExtensions() {
return _loadExtensions.apply(this, arguments);
}
return loadExtensions;
}()
}, {
key: "executeAction",
value: function () {
var _executeAction = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee2(action, extension) {
var result;
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee2$(_context2) {
while (1) {
switch (_context2.prev = _context2.next) {
case 0:
if (!(action.verb === 'nested')) {
_context2.next = 3;
break;
}
if (!action.subrows) {
action.subrows = this.subRowsForAction(action, extension);
} else {
action.subrows = null;
}
return _context2.abrupt("return");
case 3:
action.running = true;
_context2.next = 6;
return this.actionsManager.executeAction(action, extension, this.props.item);
case 6:
result = _context2.sent;
if (!action.error) {
_context2.next = 9;
break;
}
return _context2.abrupt("return");
case 9:
action.running = false;
this.handleActionResult(action, result);
_context2.next = 13;
return this.actionsManager.loadExtensionInContextOfItem(extension, this.props.item);
case 13:
this.setState({
extensions: this.state.extensions
});
case 14:
case "end":
return _context2.stop();
}
}
}, _callee2, this);
}));
function executeAction(_x, _x2) {
return _executeAction.apply(this, arguments);
}
return executeAction;
}()
}, {
key: "handleActionResult",
value: function handleActionResult(action, result) {
switch (action.verb) {
case 'render':
{
var item = result.item;
this.godService.presentRevisionPreviewModal(item.uuid, item.content);
}
}
}
}, {
key: "subRowsForAction",
value: function subRowsForAction(parentAction, extension) {
var _this2 = this;
if (!parentAction.subactions) {
return null;
}
return parentAction.subactions.map(function (subaction) {
return {
onClick: function onClick() {
_this2.executeAction(subaction, extension, parentAction);
},
label: subaction.label,
subtitle: subaction.desc,
spinnerClass: subaction.running ? 'info' : null
};
});
}
}]);
return ActionsMenuCtrl;
}(_Controllers__WEBPACK_IMPORTED_MODULE_8__["PureCtrl"]);
var ActionsMenu = function ActionsMenu() {
_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2___default()(this, ActionsMenu);
this.restrict = 'E';
this.template = _directives_actions_menu_pug__WEBPACK_IMPORTED_MODULE_7___default.a;
this.replace = true;
this.controller = ActionsMenuCtrl;
this.controllerAs = 'self';
this.bindToController = true;
this.scope = {
item: '='
};
};
/***/ }),
/***/ "./app/assets/javascripts/directives/views/componentModal.js":
/*!*******************************************************************!*\
!*** ./app/assets/javascripts/directives/views/componentModal.js ***!
\*******************************************************************/
/*! exports provided: ComponentModalCtrl, ComponentModal */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ComponentModalCtrl", function() { return ComponentModalCtrl; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ComponentModal", function() { return ComponentModal; });
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "./node_modules/@babel/runtime/helpers/classCallCheck.js");
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/helpers/createClass */ "./node_modules/@babel/runtime/helpers/createClass.js");
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _directives_component_modal_pug__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! %/directives/component-modal.pug */ "./app/assets/templates/directives/component-modal.pug");
/* harmony import */ var _directives_component_modal_pug__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_directives_component_modal_pug__WEBPACK_IMPORTED_MODULE_2__);
var ComponentModalCtrl =
/*#__PURE__*/
function () {
ComponentModalCtrl.$inject = ["$scope", "$element"];
/* @ngInject */
function ComponentModalCtrl($scope, $element) {
_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0___default()(this, ComponentModalCtrl);
this.$element = $element;
this.$scope = $scope;
}
_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1___default()(ComponentModalCtrl, [{
key: "dismiss",
value: function dismiss(callback) {
this.$element.remove();
this.$scope.$destroy();
if (this.onDismiss && this.onDismiss()) {
this.onDismiss()(this.component);
}
callback && callback();
}
}]);
return ComponentModalCtrl;
}();
var ComponentModal = function ComponentModal() {
_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0___default()(this, ComponentModal);
this.restrict = 'E';
this.template = _directives_component_modal_pug__WEBPACK_IMPORTED_MODULE_2___default.a;
this.controller = ComponentModalCtrl;
this.controllerAs = 'ctrl';
this.bindToController = true;
this.scope = {
show: '=',
component: '=',
callback: '=',
onDismiss: '&'
};
};
/***/ }),
/***/ "./app/assets/javascripts/directives/views/componentView.js":
/*!******************************************************************!*\
!*** ./app/assets/javascripts/directives/views/componentView.js ***!
\******************************************************************/
/*! exports provided: ComponentView */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ComponentView", function() { return ComponentView; });
/* harmony import */ var _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/regenerator */ "./node_modules/@babel/runtime/regenerator/index.js");
/* harmony import */ var _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/helpers/asyncToGenerator */ "./node_modules/@babel/runtime/helpers/asyncToGenerator.js");
/* harmony import */ var _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "./node_modules/@babel/runtime/helpers/classCallCheck.js");
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @babel/runtime/helpers/createClass */ "./node_modules/@babel/runtime/helpers/createClass.js");
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var _directives_component_view_pug__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! %/directives/component-view.pug */ "./app/assets/templates/directives/component-view.pug");
/* harmony import */ var _directives_component_view_pug__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(_directives_component_view_pug__WEBPACK_IMPORTED_MODULE_4__);
/* harmony import */ var _utils__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../../utils */ "./app/assets/javascripts/utils.js");
/**
* The maximum amount of time we'll wait for a component
* to load before displaying error
*/
var MAX_LOAD_THRESHOLD = 4000;
var VISIBILITY_CHANGE_LISTENER_KEY = 'visibilitychange';
var ComponentViewCtrl =
/*#__PURE__*/
function () {
ComponentViewCtrl.$inject = ["$scope", "$rootScope", "$timeout", "application", "desktopManager", "themeManager"];
/* @ngInject */
function ComponentViewCtrl($scope, $rootScope, $timeout, application, desktopManager, themeManager) {
var _this = this;
_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2___default()(this, ComponentViewCtrl);
this.$rootScope = $rootScope;
this.$timeout = $timeout;
this.application = application;
this.themeManager = themeManager;
this.desktopManager = desktopManager;
this.componentValid = true;
$scope.$watch('ctrl.component', function (component, prevComponent) {
_this.componentValueDidSet(component, prevComponent);
});
$scope.$on('ext-reload-complete', function () {
_this.reloadStatus(false);
});
$scope.$on('$destroy', function () {
_this.destroy();
});
}
_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3___default()(ComponentViewCtrl, [{
key: "$onInit",
value: function $onInit() {
this.registerComponentHandlers();
this.registerPackageUpdateObserver();
}
}, {
key: "registerPackageUpdateObserver",
value: function registerPackageUpdateObserver() {
var _this2 = this;
this.updateObserver = this.desktopManager.registerUpdateObserver(function (component) {
if (component === _this2.component && component.active) {
_this2.reloadComponent();
}
});
}
}, {
key: "registerComponentHandlers",
value: function registerComponentHandlers() {
var _this3 = this;
this.themeHandlerIdentifier = 'component-view-' + Math.random();
this.application.componentManager.registerHandler({
identifier: this.themeHandlerIdentifier,
areas: ['themes'],
activationHandler: function activationHandler(component) {
_this3.reloadThemeStatus();
}
});
this.identifier = 'component-view-' + Math.random();
this.application.componentManager.registerHandler({
identifier: this.identifier,
areas: [this.component.area],
activationHandler: function activationHandler(component) {
if (component !== _this3.component) {
return;
}
_this3.$timeout(function () {
_this3.handleActivation();
});
},
actionHandler: function actionHandler(component, action, data) {
if (action === 'set-size') {
_this3.application.componentManager.handleSetSizeEvent(component, data);
}
}
});
}
}, {
key: "onVisibilityChange",
value: function onVisibilityChange() {
if (document.visibilityState === 'hidden') {
return;
}
if (this.issueLoading) {
this.reloadComponent();
}
}
}, {
key: "reloadComponent",
value: function () {
var _reloadComponent = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee() {
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
this.componentValid = false;
_context.next = 3;
return this.application.componentManager.reloadComponent(this.component);
case 3:
this.reloadStatus();
case 4:
case "end":
return _context.stop();
}
}
}, _callee, this);
}));
function reloadComponent() {
return _reloadComponent.apply(this, arguments);
}
return reloadComponent;
}()
}, {
key: "reloadStatus",
value: function reloadStatus() {
var _this4 = this;
var doManualReload = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true;
this.reloading = true;
var component = this.component;
var previouslyValid = this.componentValid;
var offlineRestricted = component.offlineOnly && !Object(_utils__WEBPACK_IMPORTED_MODULE_5__["isDesktopApplication"])();
var hasUrlError = function () {
if (Object(_utils__WEBPACK_IMPORTED_MODULE_5__["isDesktopApplication"])()) {
return !component.local_url && !component.hasValidHostedUrl();
} else {
return !component.hasValidHostedUrl();
}
}();
this.expired = component.valid_until && component.valid_until <= new Date();
if (!component.lockReadonly) {
component.readonly = this.expired;
}
this.componentValid = !offlineRestricted && !hasUrlError;
if (!this.componentValid) {
this.loading = false;
}
if (offlineRestricted) {
this.error = 'offline-restricted';
} else if (hasUrlError) {
this.error = 'url-missing';
} else {
this.error = null;
}
if (this.componentValid !== previouslyValid) {
if (this.componentValid) {
this.application.componentManager.reloadComponent(component, true);
}
}
if (this.expired && doManualReload) {
this.$rootScope.$broadcast('reload-ext-dat');
}
this.reloadThemeStatus();
this.$timeout(function () {
_this4.reloading = false;
}, 500);
}
}, {
key: "handleActivation",
value: function handleActivation() {
var _this5 = this;
if (!this.component.active) {
return;
}
var iframe = this.application.componentManager.iframeForComponent(this.component);
if (!iframe) {
return;
}
this.loading = true;
if (this.loadTimeout) {
this.$timeout.cancel(this.loadTimeout);
}
this.loadTimeout = this.$timeout(function () {
_this5.handleIframeLoadTimeout();
}, MAX_LOAD_THRESHOLD);
iframe.onload = function (event) {
_this5.handleIframeLoad(iframe);
};
}
}, {
key: "handleIframeLoadTimeout",
value: function () {
var _handleIframeLoadTimeout = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee2() {
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee2$(_context2) {
while (1) {
switch (_context2.prev = _context2.next) {
case 0:
if (this.loading) {
this.loading = false;
this.issueLoading = true;
if (!this.didAttemptReload) {
this.didAttemptReload = true;
this.reloadComponent();
} else {
document.addEventListener(VISIBILITY_CHANGE_LISTENER_KEY, this.onVisibilityChange.bind(this));
}
}
case 1:
case "end":
return _context2.stop();
}
}
}, _callee2, this);
}));
function handleIframeLoadTimeout() {
return _handleIframeLoadTimeout.apply(this, arguments);
}
return handleIframeLoadTimeout;
}()
}, {
key: "handleIframeLoad",
value: function () {
var _handleIframeLoad = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee3(iframe) {
var _this6 = this;
var desktopError, avoidFlickerTimeout;
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee3$(_context3) {
while (1) {
switch (_context3.prev = _context3.next) {
case 0:
desktopError = false;
if (Object(_utils__WEBPACK_IMPORTED_MODULE_5__["isDesktopApplication"])()) {
try {
/** Accessing iframe.contentWindow.origin only allowed in desktop app. */
if (!iframe.contentWindow.origin || iframe.contentWindow.origin === 'null') {
desktopError = true;
}
} catch (e) {}
}
this.$timeout.cancel(this.loadTimeout);
_context3.next = 5;
return this.application.componentManager.registerComponentWindow(this.component, iframe.contentWindow);
case 5:
avoidFlickerTimeout = 7;
this.$timeout(function () {
_this6.loading = false;
_this6.issueLoading = !!desktopError;
_this6.onLoad && _this6.onLoad(_this6.component);
}, avoidFlickerTimeout);
case 7:
case "end":
return _context3.stop();
}
}
}, _callee3, this);
}));
function handleIframeLoad(_x) {
return _handleIframeLoad.apply(this, arguments);
}
return handleIframeLoad;
}()
}, {
key: "componentValueDidSet",
value: function componentValueDidSet(component, prevComponent) {
var dontSync = true;
if (prevComponent && component !== prevComponent) {
this.application.componentManager.deactivateComponent(prevComponent, dontSync);
}
if (component) {
this.application.componentManager.activateComponent(component, dontSync);
this.reloadStatus();
}
}
}, {
key: "reloadThemeStatus",
value: function reloadThemeStatus() {
if (this.component.acceptsThemes()) {
return;
}
if (this.themeManager.hasActiveTheme()) {
if (!this.dismissedNoThemesMessage) {
this.showNoThemesMessage = true;
}
} else {
this.showNoThemesMessage = false;
}
}
}, {
key: "dismissNoThemesMessage",
value: function dismissNoThemesMessage() {
this.showNoThemesMessage = false;
this.dismissedNoThemesMessage = true;
}
}, {
key: "disableActiveTheme",
value: function disableActiveTheme() {
this.themeManager.deactivateAllThemes();
this.dismissNoThemesMessage();
}
}, {
key: "getUrl",
value: function getUrl() {
var url = this.application.componentManager.urlForComponent(this.component);
this.component.runningLocally = url === this.component.local_url;
return url;
}
}, {
key: "destroy",
value: function destroy() {
this.application.componentManager.deregisterHandler(this.themeHandlerIdentifier);
this.application.componentManager.deregisterHandler(this.identifier);
if (this.component && !this.manualDealloc) {
var dontSync = true;
this.application.componentManager.deactivateComponent(this.component, dontSync);
}
this.desktopManager.deregisterUpdateObserver(this.updateObserver);
document.removeEventListener(VISIBILITY_CHANGE_LISTENER_KEY, this.onVisibilityChange.bind(this));
}
}]);
return ComponentViewCtrl;
}();
var ComponentView = function ComponentView() {
_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2___default()(this, ComponentView);
this.restrict = 'E';
this.template = _directives_component_view_pug__WEBPACK_IMPORTED_MODULE_4___default.a;
this.scope = {
component: '=',
onLoad: '=?',
manualDealloc: '=?'
};
this.controller = ComponentViewCtrl;
this.controllerAs = 'ctrl';
this.bindToController = true;
};
/***/ }),
/***/ "./app/assets/javascripts/directives/views/conflictResolutionModal.js":
/*!****************************************************************************!*\
!*** ./app/assets/javascripts/directives/views/conflictResolutionModal.js ***!
\****************************************************************************/
/*! exports provided: ConflictResolutionModal */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ConflictResolutionModal", function() { return ConflictResolutionModal; });
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "./node_modules/@babel/runtime/helpers/classCallCheck.js");
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/helpers/createClass */ "./node_modules/@babel/runtime/helpers/createClass.js");
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _directives_conflict_resolution_modal_pug__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! %/directives/conflict-resolution-modal.pug */ "./app/assets/templates/directives/conflict-resolution-modal.pug");
/* harmony import */ var _directives_conflict_resolution_modal_pug__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_directives_conflict_resolution_modal_pug__WEBPACK_IMPORTED_MODULE_2__);
var ConflictResolutionCtrl =
/*#__PURE__*/
function () {
ConflictResolutionCtrl.$inject = ["$element", "archiveManager", "application"];
/* @ngInject */
function ConflictResolutionCtrl($element, archiveManager, application) {
_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0___default()(this, ConflictResolutionCtrl);
this.$element = $element;
this.application = application;
this.archiveManager = archiveManager;
}
_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1___default()(ConflictResolutionCtrl, [{
key: "$onInit",
value: function $onInit() {
this.contentType = this.item1.content_type;
this.item1Content = this.createContentString(this.item1);
this.item2Content = this.createContentString(this.item2);
}
}, {
key: "createContentString",
value: function createContentString(item) {
var data = Object.assign({
created_at: item.created_at,
updated_at: item.updated_at
}, item.content);
return JSON.stringify(data, null, 2);
}
}, {
key: "keepItem1",
value: function keepItem1() {
var _this = this;
this.application.alertManager.confirm({
text: "Are you sure you want to delete the item on the right?",
destructive: true,
onConfirm: function onConfirm() {
_this.application.deleteItem({
item: _this.item2
});
_this.triggerCallback();
_this.dismiss();
}
});
}
}, {
key: "keepItem2",
value: function keepItem2() {
var _this2 = this;
this.application.alertManager.confirm({
text: "Are you sure you want to delete the item on the left?",
destructive: true,
onConfirm: function onConfirm() {
_this2.application.deleteItem({
item: _this2.item1
});
_this2.triggerCallback();
_this2.dismiss();
}
});
}
}, {
key: "keepBoth",
value: function keepBoth() {
this.triggerCallback();
this.dismiss();
}
}, {
key: "export",
value: function _export() {
this.archiveManager.downloadBackupOfItems([this.item1, this.item2], true);
}
}, {
key: "triggerCallback",
value: function triggerCallback() {
this.callback && this.callback();
}
}, {
key: "dismiss",
value: function dismiss() {
this.$element.remove();
}
}]);
return ConflictResolutionCtrl;
}();
var ConflictResolutionModal = function ConflictResolutionModal() {
_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0___default()(this, ConflictResolutionModal);
this.restrict = 'E';
this.template = _directives_conflict_resolution_modal_pug__WEBPACK_IMPORTED_MODULE_2___default.a;
this.controller = ConflictResolutionCtrl;
this.controllerAs = 'ctrl';
this.bindToController = true;
this.scope = {
item1: '=',
item2: '=',
callback: '='
};
};
/***/ }),
/***/ "./app/assets/javascripts/directives/views/editorMenu.js":
/*!***************************************************************!*\
!*** ./app/assets/javascripts/directives/views/editorMenu.js ***!
\***************************************************************/
/*! exports provided: EditorMenu */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "EditorMenu", function() { return EditorMenu; });
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "./node_modules/@babel/runtime/helpers/classCallCheck.js");
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/helpers/createClass */ "./node_modules/@babel/runtime/helpers/createClass.js");
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "./node_modules/@babel/runtime/helpers/possibleConstructorReturn.js");
/* harmony import */ var _babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "./node_modules/@babel/runtime/helpers/getPrototypeOf.js");
/* harmony import */ var _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var _babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @babel/runtime/helpers/inherits */ "./node_modules/@babel/runtime/helpers/inherits.js");
/* harmony import */ var _babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_4__);
/* harmony import */ var _utils__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! @/utils */ "./app/assets/javascripts/utils.js");
/* harmony import */ var _directives_editor_menu_pug__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! %/directives/editor-menu.pug */ "./app/assets/templates/directives/editor-menu.pug");
/* harmony import */ var _directives_editor_menu_pug__WEBPACK_IMPORTED_MODULE_6___default = /*#__PURE__*/__webpack_require__.n(_directives_editor_menu_pug__WEBPACK_IMPORTED_MODULE_6__);
/* harmony import */ var _Controllers__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! @Controllers */ "./app/assets/javascripts/controllers/index.js");
var EditorMenuCtrl =
/*#__PURE__*/
function (_PureCtrl) {
EditorMenuCtrl.$inject = ["$timeout", "application"];
_babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_4___default()(EditorMenuCtrl, _PureCtrl);
/* @ngInject */
function EditorMenuCtrl($timeout, application) {
var _this;
_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0___default()(this, EditorMenuCtrl);
_this = _babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_2___default()(this, _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_3___default()(EditorMenuCtrl).call(this, $timeout));
_this.application = application;
_this.state = {
isDesktop: Object(_utils__WEBPACK_IMPORTED_MODULE_5__["isDesktopApplication"])()
};
return _this;
}
_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1___default()(EditorMenuCtrl, [{
key: "$onInit",
value: function $onInit() {
var editors = this.application.componentManager.componentsForArea('editor-editor').sort(function (a, b) {
return a.name.toLowerCase() < b.name.toLowerCase() ? -1 : 1;
});
var defaultEditor = editors.filter(function (e) {
return e.isDefaultEditor();
})[0];
this.setState({
editors: editors,
defaultEditor: defaultEditor
});
}
}, {
key: "selectComponent",
value: function selectComponent(component) {
var _this2 = this;
if (component) {
if (component.content.conflict_of) {
component.content.conflict_of = null;
this.application.saveItem({
item: component
});
}
}
this.$timeout(function () {
_this2.callback()(component);
});
}
}, {
key: "toggleDefaultForEditor",
value: function toggleDefaultForEditor(editor) {
if (this.defaultEditor === editor) {
this.removeEditorDefault(editor);
} else {
this.makeEditorDefault(editor);
}
}
}, {
key: "offlineAvailableForComponent",
value: function offlineAvailableForComponent(component) {
return component.local_url && this.state.isDesktop;
}
}, {
key: "makeEditorDefault",
value: function makeEditorDefault(component) {
var currentDefault = this.application.componentManager.componentsForArea('editor-editor').filter(function (e) {
return e.isDefaultEditor();
})[0];
if (currentDefault) {
currentDefault.setAppDataItem('defaultEditor', false);
this.application.setItemsNeedsSync({
item: currentDefault
});
}
component.setAppDataItem('defaultEditor', true);
this.application.saveItem({
item: component
});
this.setState({
defaultEditor: component
});
}
}, {
key: "removeEditorDefault",
value: function removeEditorDefault(component) {
component.setAppDataItem('defaultEditor', false);
this.application.saveItem({
item: component
});
this.setState({
defaultEditor: null
});
}
}, {
key: "shouldDisplayRunningLocallyLabel",
value: function shouldDisplayRunningLocallyLabel(component) {
if (!component.runningLocally) {
return false;
}
if (component === this.selectedEditor) {
return true;
} else {
return false;
}
}
}]);
return EditorMenuCtrl;
}(_Controllers__WEBPACK_IMPORTED_MODULE_7__["PureCtrl"]);
var EditorMenu = function EditorMenu() {
_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0___default()(this, EditorMenu);
this.restrict = 'E';
this.template = _directives_editor_menu_pug__WEBPACK_IMPORTED_MODULE_6___default.a;
this.controller = EditorMenuCtrl;
this.controllerAs = 'self';
this.bindToController = true;
this.scope = {
callback: '&',
selectedEditor: '=',
currentItem: '='
};
};
/***/ }),
/***/ "./app/assets/javascripts/directives/views/index.js":
/*!**********************************************************!*\
!*** ./app/assets/javascripts/directives/views/index.js ***!
\**********************************************************/
/*! exports provided: AccountMenu, ActionsMenu, ComponentModal, ComponentView, ConflictResolutionModal, EditorMenu, InputModal, MenuRow, PanelResizer, PasswordWizard, PermissionsModal, PrivilegesAuthModal, PrivilegesManagementModal, RevisionPreviewModal, SessionHistoryMenu, SyncResolutionMenu */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _accountMenu__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./accountMenu */ "./app/assets/javascripts/directives/views/accountMenu.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AccountMenu", function() { return _accountMenu__WEBPACK_IMPORTED_MODULE_0__["AccountMenu"]; });
/* harmony import */ var _actionsMenu__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./actionsMenu */ "./app/assets/javascripts/directives/views/actionsMenu.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ActionsMenu", function() { return _actionsMenu__WEBPACK_IMPORTED_MODULE_1__["ActionsMenu"]; });
/* harmony import */ var _componentModal__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./componentModal */ "./app/assets/javascripts/directives/views/componentModal.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ComponentModal", function() { return _componentModal__WEBPACK_IMPORTED_MODULE_2__["ComponentModal"]; });
/* harmony import */ var _componentView__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./componentView */ "./app/assets/javascripts/directives/views/componentView.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ComponentView", function() { return _componentView__WEBPACK_IMPORTED_MODULE_3__["ComponentView"]; });
/* harmony import */ var _conflictResolutionModal__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./conflictResolutionModal */ "./app/assets/javascripts/directives/views/conflictResolutionModal.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ConflictResolutionModal", function() { return _conflictResolutionModal__WEBPACK_IMPORTED_MODULE_4__["ConflictResolutionModal"]; });
/* harmony import */ var _editorMenu__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./editorMenu */ "./app/assets/javascripts/directives/views/editorMenu.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "EditorMenu", function() { return _editorMenu__WEBPACK_IMPORTED_MODULE_5__["EditorMenu"]; });
/* harmony import */ var _inputModal__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./inputModal */ "./app/assets/javascripts/directives/views/inputModal.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "InputModal", function() { return _inputModal__WEBPACK_IMPORTED_MODULE_6__["InputModal"]; });
/* harmony import */ var _menuRow__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./menuRow */ "./app/assets/javascripts/directives/views/menuRow.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "MenuRow", function() { return _menuRow__WEBPACK_IMPORTED_MODULE_7__["MenuRow"]; });
/* harmony import */ var _panelResizer__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./panelResizer */ "./app/assets/javascripts/directives/views/panelResizer.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PanelResizer", function() { return _panelResizer__WEBPACK_IMPORTED_MODULE_8__["PanelResizer"]; });
/* harmony import */ var _passwordWizard__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./passwordWizard */ "./app/assets/javascripts/directives/views/passwordWizard.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PasswordWizard", function() { return _passwordWizard__WEBPACK_IMPORTED_MODULE_9__["PasswordWizard"]; });
/* harmony import */ var _permissionsModal__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./permissionsModal */ "./app/assets/javascripts/directives/views/permissionsModal.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PermissionsModal", function() { return _permissionsModal__WEBPACK_IMPORTED_MODULE_10__["PermissionsModal"]; });
/* harmony import */ var _privilegesAuthModal__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./privilegesAuthModal */ "./app/assets/javascripts/directives/views/privilegesAuthModal.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PrivilegesAuthModal", function() { return _privilegesAuthModal__WEBPACK_IMPORTED_MODULE_11__["PrivilegesAuthModal"]; });
/* harmony import */ var _privilegesManagementModal__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ./privilegesManagementModal */ "./app/assets/javascripts/directives/views/privilegesManagementModal.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PrivilegesManagementModal", function() { return _privilegesManagementModal__WEBPACK_IMPORTED_MODULE_12__["PrivilegesManagementModal"]; });
/* harmony import */ var _revisionPreviewModal__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ./revisionPreviewModal */ "./app/assets/javascripts/directives/views/revisionPreviewModal.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "RevisionPreviewModal", function() { return _revisionPreviewModal__WEBPACK_IMPORTED_MODULE_13__["RevisionPreviewModal"]; });
/* harmony import */ var _sessionHistoryMenu__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ./sessionHistoryMenu */ "./app/assets/javascripts/directives/views/sessionHistoryMenu.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SessionHistoryMenu", function() { return _sessionHistoryMenu__WEBPACK_IMPORTED_MODULE_14__["SessionHistoryMenu"]; });
/* harmony import */ var _syncResolutionMenu__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ./syncResolutionMenu */ "./app/assets/javascripts/directives/views/syncResolutionMenu.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SyncResolutionMenu", function() { return _syncResolutionMenu__WEBPACK_IMPORTED_MODULE_15__["SyncResolutionMenu"]; });
/***/ }),
/***/ "./app/assets/javascripts/directives/views/inputModal.js":
/*!***************************************************************!*\
!*** ./app/assets/javascripts/directives/views/inputModal.js ***!
\***************************************************************/
/*! exports provided: InputModal */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "InputModal", function() { return InputModal; });
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "./node_modules/@babel/runtime/helpers/classCallCheck.js");
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/helpers/createClass */ "./node_modules/@babel/runtime/helpers/createClass.js");
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _directives_input_modal_pug__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! %/directives/input-modal.pug */ "./app/assets/templates/directives/input-modal.pug");
/* harmony import */ var _directives_input_modal_pug__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_directives_input_modal_pug__WEBPACK_IMPORTED_MODULE_2__);
var InputModalCtrl =
/*#__PURE__*/
function () {
InputModalCtrl.$inject = ["$scope", "$element"];
/* @ngInject */
function InputModalCtrl($scope, $element) {
_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0___default()(this, InputModalCtrl);
this.$element = $element;
this.formData = {};
}
_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1___default()(InputModalCtrl, [{
key: "dismiss",
value: function dismiss() {
this.$element.remove();
this.$scope.$destroy();
}
}, {
key: "submit",
value: function submit() {
this.callback()(this.formData.input);
this.dismiss();
}
}]);
return InputModalCtrl;
}();
var InputModal = function InputModal() {
_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0___default()(this, InputModal);
this.restrict = 'E';
this.template = _directives_input_modal_pug__WEBPACK_IMPORTED_MODULE_2___default.a;
this.controller = InputModalCtrl;
this.controllerAs = 'ctrl';
this.bindToController = true;
this.scope = {
type: '=',
title: '=',
message: '=',
placeholder: '=',
callback: '&'
};
};
/***/ }),
/***/ "./app/assets/javascripts/directives/views/menuRow.js":
/*!************************************************************!*\
!*** ./app/assets/javascripts/directives/views/menuRow.js ***!
\************************************************************/
/*! exports provided: MenuRow */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MenuRow", function() { return MenuRow; });
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "./node_modules/@babel/runtime/helpers/classCallCheck.js");
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/helpers/createClass */ "./node_modules/@babel/runtime/helpers/createClass.js");
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _directives_menu_row_pug__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! %/directives/menu-row.pug */ "./app/assets/templates/directives/menu-row.pug");
/* harmony import */ var _directives_menu_row_pug__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_directives_menu_row_pug__WEBPACK_IMPORTED_MODULE_2__);
var MenuRowCtrl =
/*#__PURE__*/
function () {
function MenuRowCtrl() {
_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0___default()(this, MenuRowCtrl);
}
_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1___default()(MenuRowCtrl, [{
key: "onClick",
value: function onClick($event) {
if (this.disabled) {
return;
}
$event.stopPropagation();
this.action();
}
}, {
key: "clickAccessoryButton",
value: function clickAccessoryButton($event) {
if (this.disabled) {
return;
}
$event.stopPropagation();
this.buttonAction();
}
}]);
return MenuRowCtrl;
}();
var MenuRow = function MenuRow() {
_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0___default()(this, MenuRow);
this.restrict = 'E';
this.transclude = true;
this.template = _directives_menu_row_pug__WEBPACK_IMPORTED_MODULE_2___default.a;
this.controller = MenuRowCtrl;
this.controllerAs = 'ctrl';
this.bindToController = true;
this.scope = {
action: '&',
buttonAction: '&',
buttonClass: '=',
buttonText: '=',
desc: '=',
disabled: '=',
circle: '=',
circleAlign: '=',
faded: '=',
hasButton: '=',
label: '=',
spinnerClass: '=',
stylekitClass: '=',
subRows: '=',
subtitle: '='
};
};
/***/ }),
/***/ "./app/assets/javascripts/directives/views/panelResizer.js":
/*!*****************************************************************!*\
!*** ./app/assets/javascripts/directives/views/panelResizer.js ***!
\*****************************************************************/
/*! exports provided: PanelResizer */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PanelResizer", function() { return PanelResizer; });
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "./node_modules/@babel/runtime/helpers/classCallCheck.js");
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/helpers/createClass */ "./node_modules/@babel/runtime/helpers/createClass.js");
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var angular__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! angular */ "./node_modules/angular/index.js");
/* harmony import */ var angular__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(angular__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _directives_panel_resizer_pug__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! %/directives/panel-resizer.pug */ "./app/assets/templates/directives/panel-resizer.pug");
/* harmony import */ var _directives_panel_resizer_pug__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_directives_panel_resizer_pug__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var _utils__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @/utils */ "./app/assets/javascripts/utils.js");
var PANEL_SIDE_RIGHT = 'right';
var PANEL_SIDE_LEFT = 'left';
var MOUSE_EVENT_MOVE = 'mousemove';
var MOUSE_EVENT_DOWN = 'mousedown';
var MOUSE_EVENT_UP = 'mouseup';
var WINDOW_EVENT_RESIZE = 'resize';
var PANEL_CSS_CLASS_HOVERABLE = 'hoverable';
var PANEL_CSS_CLASS_ALWAYS_VISIBLE = 'always-visible';
var PANEL_CSS_CLASS_DRAGGING = 'dragging';
var PANEL_CSS_CLASS_NO_SELECTION = 'no-selection';
var PANEL_CSS_CLASS_COLLAPSED = 'collapsed';
var PANEL_CSS_CLASS_ANIMATE_OPACITY = 'animate-opacity';
var PanelResizerCtrl =
/*#__PURE__*/
function () {
PanelResizerCtrl.$inject = ["$compile", "$element", "$scope", "$timeout"];
/* @ngInject */
function PanelResizerCtrl($compile, $element, $scope, $timeout) {
_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0___default()(this, PanelResizerCtrl);
this.$compile = $compile;
this.$element = $element;
this.$scope = $scope;
this.$timeout = $timeout;
}
_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1___default()(PanelResizerCtrl, [{
key: "$onInit",
value: function $onInit() {
this.configureControl();
this.configureDefaults();
this.addDoubleClickHandler();
this.reloadDefaultValues();
this.addMouseDownListener();
this.addMouseMoveListener();
this.addMouseUpListener();
}
}, {
key: "configureControl",
value: function configureControl() {
var _this = this;
this.control.setWidth = function (value) {
_this.setWidth(value, true);
};
this.control.setLeft = function (value) {
_this.setLeft(value);
};
this.control.flash = function () {
_this.flash();
};
this.control.isCollapsed = function () {
return _this.isCollapsed();
};
}
}, {
key: "configureDefaults",
value: function configureDefaults() {
this.panel = document.getElementById(this.panelId);
if (!this.panel) {
console.error('Panel not found for', this.panelId);
}
this.resizerColumn = this.$element[0];
this.currentMinWidth = this.minWidth || this.resizerColumn.offsetWidth;
this.pressed = false;
this.startWidth = this.panel.scrollWidth;
this.lastDownX = 0;
this.collapsed = false;
this.lastWidth = this.startWidth;
this.startLeft = this.panel.offsetLeft;
this.lastLeft = this.startLeft;
this.appFrame = null;
this.widthBeforeLastDblClick = 0;
if (this.property === PANEL_SIDE_RIGHT) {
this.configureRightPanel();
}
if (this.alwaysVisible) {
this.resizerColumn.classList.add(PANEL_CSS_CLASS_ALWAYS_VISIBLE);
}
if (this.hoverable) {
this.resizerColumn.classList.add(PANEL_CSS_CLASS_HOVERABLE);
}
}
}, {
key: "configureRightPanel",
value: function configureRightPanel() {
var _this2 = this;
var handleResize = Object(_utils__WEBPACK_IMPORTED_MODULE_4__["debounce"])(function (event) {
_this2.reloadDefaultValues();
_this2.handleWidthEvent();
_this2.$timeout(function () {
_this2.finishSettingWidth();
});
}, 250);
window.addEventListener(WINDOW_EVENT_RESIZE, handleResize);
this.$scope.$on('$destroy', function () {
window.removeEventListener(WINDOW_EVENT_RESIZE, handleResize);
});
}
}, {
key: "getParentRect",
value: function getParentRect() {
return this.panel.parentNode.getBoundingClientRect();
}
}, {
key: "reloadDefaultValues",
value: function reloadDefaultValues() {
this.startWidth = this.isAtMaxWidth() ? this.getParentRect().width : this.panel.scrollWidth;
this.lastWidth = this.startWidth;
this.appFrame = document.getElementById('app').getBoundingClientRect();
}
}, {
key: "addDoubleClickHandler",
value: function addDoubleClickHandler() {
var _this3 = this;
this.resizerColumn.ondblclick = function () {
_this3.$timeout(function () {
var preClickCollapseState = _this3.isCollapsed();
if (preClickCollapseState) {
_this3.setWidth(_this3.widthBeforeLastDblClick || _this3.defaultWidth);
} else {
_this3.widthBeforeLastDblClick = _this3.lastWidth;
_this3.setWidth(_this3.currentMinWidth);
}
_this3.finishSettingWidth();
var newCollapseState = !preClickCollapseState;
_this3.onResizeFinish()(_this3.lastWidth, _this3.lastLeft, _this3.isAtMaxWidth(), newCollapseState);
});
};
}
}, {
key: "addMouseDownListener",
value: function addMouseDownListener() {
var _this4 = this;
this.resizerColumn.addEventListener(MOUSE_EVENT_DOWN, function (event) {
_this4.addInvisibleOverlay();
_this4.pressed = true;
_this4.lastDownX = event.clientX;
_this4.startWidth = _this4.panel.scrollWidth;
_this4.startLeft = _this4.panel.offsetLeft;
_this4.panel.classList.add(PANEL_CSS_CLASS_NO_SELECTION);
if (_this4.hoverable) {
_this4.resizerColumn.classList.add(PANEL_CSS_CLASS_DRAGGING);
}
});
}
}, {
key: "addMouseMoveListener",
value: function addMouseMoveListener() {
var _this5 = this;
document.addEventListener(MOUSE_EVENT_MOVE, function (event) {
if (!_this5.pressed) {
return;
}
event.preventDefault();
if (_this5.property && _this5.property === PANEL_SIDE_LEFT) {
_this5.handleLeftEvent(event);
} else {
_this5.handleWidthEvent(event);
}
});
}
}, {
key: "handleWidthEvent",
value: function handleWidthEvent(event) {
var x;
if (event) {
x = event.clientX;
} else {
/** Coming from resize event */
x = 0;
this.lastDownX = 0;
}
var deltaX = x - this.lastDownX;
var newWidth = this.startWidth + deltaX;
this.setWidth(newWidth, false);
if (this.onResize()) {
this.onResize()(this.lastWidth, this.panel);
}
}
}, {
key: "handleLeftEvent",
value: function handleLeftEvent(event) {
var panelRect = this.panel.getBoundingClientRect();
var x = event.clientX || panelRect.x;
var deltaX = x - this.lastDownX;
var newLeft = this.startLeft + deltaX;
if (newLeft < 0) {
newLeft = 0;
deltaX = -this.startLeft;
}
var parentRect = this.getParentRect();
var newWidth = this.startWidth - deltaX;
if (newWidth < this.currentMinWidth) {
newWidth = this.currentMinWidth;
}
if (newWidth > parentRect.width) {
newWidth = parentRect.width;
}
if (newLeft + newWidth > parentRect.width) {
newLeft = parentRect.width - newWidth;
}
this.setLeft(newLeft, false);
this.setWidth(newWidth, false);
}
}, {
key: "addMouseUpListener",
value: function addMouseUpListener() {
var _this6 = this;
document.addEventListener(MOUSE_EVENT_UP, function (event) {
_this6.removeInvisibleOverlay();
if (_this6.pressed) {
_this6.pressed = false;
_this6.resizerColumn.classList.remove(PANEL_CSS_CLASS_DRAGGING);
_this6.panel.classList.remove(PANEL_CSS_CLASS_NO_SELECTION);
var isMaxWidth = _this6.isAtMaxWidth();
if (_this6.onResizeFinish) {
_this6.onResizeFinish()(_this6.lastWidth, _this6.lastLeft, isMaxWidth, _this6.isCollapsed());
}
_this6.finishSettingWidth();
}
});
}
}, {
key: "isAtMaxWidth",
value: function isAtMaxWidth() {
return Math.round(this.lastWidth + this.lastLeft) === Math.round(this.getParentRect().width);
}
}, {
key: "isCollapsed",
value: function isCollapsed() {
return this.lastWidth <= this.currentMinWidth;
}
}, {
key: "setWidth",
value: function setWidth(width, finish) {
if (width < this.currentMinWidth) {
width = this.currentMinWidth;
}
var parentRect = this.getParentRect();
if (width > parentRect.width) {
width = parentRect.width;
}
var maxWidth = this.appFrame.width - this.panel.getBoundingClientRect().x;
if (width > maxWidth) {
width = maxWidth;
}
if (Math.round(width + this.lastLeft) === Math.round(parentRect.width)) {
this.panel.style.width = "calc(100% - ".concat(this.lastLeft, "px)");
this.panel.style.flexBasis = "calc(100% - ".concat(this.lastLeft, "px)");
} else {
this.panel.style.flexBasis = width + 'px';
this.panel.style.width = width + 'px';
}
this.lastWidth = width;
if (finish) {
this.finishSettingWidth();
}
}
}, {
key: "setLeft",
value: function setLeft(left) {
this.panel.style.left = left + 'px';
this.lastLeft = left;
}
}, {
key: "finishSettingWidth",
value: function finishSettingWidth() {
if (!this.collapsable) {
return;
}
this.collapsed = this.isCollapsed();
if (this.collapsed) {
this.resizerColumn.classList.add(PANEL_CSS_CLASS_COLLAPSED);
} else {
this.resizerColumn.classList.remove(PANEL_CSS_CLASS_COLLAPSED);
}
}
/**
* If an iframe is displayed adjacent to our panel, and the mouse exits over the iframe,
* document[onmouseup] is not triggered because the document is no longer the same over
* the iframe. We add an invisible overlay while resizing so that the mouse context
* remains in our main document.
*/
}, {
key: "addInvisibleOverlay",
value: function addInvisibleOverlay() {
if (this.overlay) {
return;
}
this.overlay = this.$compile("")(this.$scope);
angular__WEBPACK_IMPORTED_MODULE_2___default.a.element(document.body).prepend(this.overlay);
}
}, {
key: "removeInvisibleOverlay",
value: function removeInvisibleOverlay() {
if (this.overlay) {
this.overlay.remove();
this.overlay = null;
}
}
}, {
key: "flash",
value: function flash() {
var _this7 = this;
var FLASH_DURATION = 3000;
this.resizerColumn.classList.add(PANEL_CSS_CLASS_ANIMATE_OPACITY);
this.$timeout(function () {
_this7.resizerColumn.classList.remove(PANEL_CSS_CLASS_ANIMATE_OPACITY);
}, FLASH_DURATION);
}
}]);
return PanelResizerCtrl;
}();
var PanelResizer = function PanelResizer() {
_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0___default()(this, PanelResizer);
this.restrict = 'E';
this.template = _directives_panel_resizer_pug__WEBPACK_IMPORTED_MODULE_3___default.a;
this.controller = PanelResizerCtrl;
this.controllerAs = 'ctrl';
this.bindToController = true;
this.scope = {
alwaysVisible: '=',
collapsable: '=',
control: '=',
defaultWidth: '=',
hoverable: '=',
index: '=',
minWidth: '=',
onResize: '&',
onResizeFinish: '&',
panelId: '=',
property: '='
};
};
/***/ }),
/***/ "./app/assets/javascripts/directives/views/passwordWizard.js":
/*!*******************************************************************!*\
!*** ./app/assets/javascripts/directives/views/passwordWizard.js ***!
\*******************************************************************/
/*! exports provided: PasswordWizard */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PasswordWizard", function() { return PasswordWizard; });
/* harmony import */ var _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/regenerator */ "./node_modules/@babel/runtime/regenerator/index.js");
/* harmony import */ var _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/helpers/asyncToGenerator */ "./node_modules/@babel/runtime/helpers/asyncToGenerator.js");
/* harmony import */ var _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "./node_modules/@babel/runtime/helpers/classCallCheck.js");
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @babel/runtime/helpers/createClass */ "./node_modules/@babel/runtime/helpers/createClass.js");
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var _directives_password_wizard_pug__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! %/directives/password-wizard.pug */ "./app/assets/templates/directives/password-wizard.pug");
/* harmony import */ var _directives_password_wizard_pug__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(_directives_password_wizard_pug__WEBPACK_IMPORTED_MODULE_4__);
/* harmony import */ var _strings__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! @/strings */ "./app/assets/javascripts/strings.js");
/* harmony import */ var _utils__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../../utils */ "./app/assets/javascripts/utils.js");
var DEFAULT_CONTINUE_TITLE = "Continue";
var Steps = {
IntroStep: 0,
BackupStep: 1,
SignoutStep: 2,
PasswordStep: 3,
SyncStep: 4,
FinishStep: 5
};
var PasswordWizardCtrl =
/*#__PURE__*/
function () {
PasswordWizardCtrl.$inject = ["$element", "$scope", "$timeout", "archiveManager"];
/* @ngInject */
function PasswordWizardCtrl($element, $scope, $timeout, archiveManager) {
_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2___default()(this, PasswordWizardCtrl);
this.$element = $element;
this.$timeout = $timeout;
this.$scope = $scope;
this.archiveManager = archiveManager;
this.registerWindowUnloadStopper();
}
_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3___default()(PasswordWizardCtrl, [{
key: "$onInit",
value: function $onInit() {
this.syncStatus = this.application.getSyncStatus();
this.formData = {};
this.configureDefaults();
}
}, {
key: "configureDefaults",
value: function configureDefaults() {
if (this.type === 'change-pw') {
this.title = "Change Password";
this.changePassword = true;
} else if (this.type === 'upgrade-security') {
this.title = "Security Update";
this.securityUpdate = true;
}
this.continueTitle = DEFAULT_CONTINUE_TITLE;
this.step = Steps.IntroStep;
}
/** Confirms with user before closing tab */
}, {
key: "registerWindowUnloadStopper",
value: function registerWindowUnloadStopper() {
window.onbeforeunload = function (e) {
return true;
};
this.$scope.$on("$destroy", function () {
window.onbeforeunload = null;
});
}
}, {
key: "titleForStep",
value: function titleForStep(step) {
switch (step) {
case Steps.BackupStep:
return "Download a backup of your data";
case Steps.SignoutStep:
return "Sign out of all your devices";
case Steps.PasswordStep:
return this.changePassword ? "Password information" : "Enter your current password";
case Steps.SyncStep:
return "Encrypt and sync data with new keys";
case Steps.FinishStep:
return "Sign back in to your devices";
default:
return null;
}
}
}, {
key: "nextStep",
value: function () {
var _nextStep = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee() {
var _this = this;
var next, preprocessor;
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
if (!(this.lockContinue || this.isContinuing)) {
_context.next = 2;
break;
}
return _context.abrupt("return");
case 2:
this.isContinuing = true;
if (!(this.step === Steps.FinishStep)) {
_context.next = 6;
break;
}
this.dismiss();
return _context.abrupt("return");
case 6:
next = function next() {
_this.step++;
_this.initializeStep(_this.step);
_this.isContinuing = false;
};
preprocessor = this.preprocessorForStep(this.step);
if (!preprocessor) {
_context.next = 13;
break;
}
_context.next = 11;
return preprocessor().then(next).catch(function () {
_this.isContinuing = false;
});
case 11:
_context.next = 14;
break;
case 13:
next();
case 14:
case "end":
return _context.stop();
}
}
}, _callee, this);
}));
function nextStep() {
return _nextStep.apply(this, arguments);
}
return nextStep;
}()
}, {
key: "preprocessorForStep",
value: function preprocessorForStep(step) {
var _this2 = this;
if (step === Steps.PasswordStep) {
return (
/*#__PURE__*/
_babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee2() {
var success;
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee2$(_context2) {
while (1) {
switch (_context2.prev = _context2.next) {
case 0:
_this2.showSpinner = true;
_this2.continueTitle = "Generating Keys...";
_context2.next = 4;
return _this2.validateCurrentPassword();
case 4:
success = _context2.sent;
_this2.showSpinner = false;
_this2.continueTitle = DEFAULT_CONTINUE_TITLE;
return _context2.abrupt("return", success);
case 8:
case "end":
return _context2.stop();
}
}
}, _callee2);
}))
);
}
}
}, {
key: "initializeStep",
value: function () {
var _initializeStep = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee3(step) {
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee3$(_context3) {
while (1) {
switch (_context3.prev = _context3.next) {
case 0:
if (!(step === Steps.SyncStep)) {
_context3.next = 5;
break;
}
_context3.next = 3;
return this.initializeSyncingStep();
case 3:
_context3.next = 6;
break;
case 5:
if (step === Steps.FinishStep) {
this.continueTitle = "Finish";
}
case 6:
case "end":
return _context3.stop();
}
}
}, _callee3, this);
}));
function initializeStep(_x) {
return _initializeStep.apply(this, arguments);
}
return initializeStep;
}()
}, {
key: "initializeSyncingStep",
value: function () {
var _initializeSyncingStep = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee4() {
var passwordSuccess;
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee4$(_context4) {
while (1) {
switch (_context4.prev = _context4.next) {
case 0:
this.lockContinue = true;
this.formData.status = "Processing encryption keys...";
this.formData.processing = true;
_context4.next = 5;
return this.processPasswordChange();
case 5:
passwordSuccess = _context4.sent;
this.formData.statusError = !passwordSuccess;
this.formData.processing = passwordSuccess;
if (passwordSuccess) {
_context4.next = 11;
break;
}
this.formData.status = "Unable to process your password. Please try again.";
return _context4.abrupt("return");
case 11:
this.lockContinue = false;
if (this.changePassword) {
this.formData.status = "Successfully changed password.";
} else if (this.securityUpdate) {
this.formData.status = "Successfully performed security update.";
}
case 13:
case "end":
return _context4.stop();
}
}
}, _callee4, this);
}));
function initializeSyncingStep() {
return _initializeSyncingStep.apply(this, arguments);
}
return initializeSyncingStep;
}()
}, {
key: "validateCurrentPassword",
value: function () {
var _validateCurrentPassword = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee5() {
var currentPassword, newPass, key;
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee5$(_context5) {
while (1) {
switch (_context5.prev = _context5.next) {
case 0:
currentPassword = this.formData.currentPassword;
newPass = this.securityUpdate ? currentPassword : this.formData.newPassword;
if (!(!currentPassword || currentPassword.length === 0)) {
_context5.next = 5;
break;
}
this.application.alertManager.alert({
text: "Please enter your current password."
});
return _context5.abrupt("return", false);
case 5:
if (!this.changePassword) {
_context5.next = 13;
break;
}
if (!(!newPass || newPass.length === 0)) {
_context5.next = 9;
break;
}
this.application.alertManager.alert({
text: "Please enter a new password."
});
return _context5.abrupt("return", false);
case 9:
if (!(newPass !== this.formData.newPasswordConfirmation)) {
_context5.next = 13;
break;
}
this.application.alertManager.alert({
text: "Your new password does not match its confirmation."
});
this.formData.status = null;
return _context5.abrupt("return", false);
case 13:
if (this.application.getUser().email) {
_context5.next = 17;
break;
}
this.application.alertManager.alert({
text: "We don't have your email stored. Please log out then log back in to fix this issue."
});
this.formData.status = null;
return _context5.abrupt("return", false);
case 17:
_context5.next = 19;
return this.application.validateAccountPassword({
password: this.formData.currentPassword
});
case 19:
key = _context5.sent;
if (key) {
this.currentServerPassword = key.serverPassword;
} else {
this.application.alertManager.alert({
text: "The current password you entered is not correct. Please try again."
});
}
return _context5.abrupt("return", !Object(_utils__WEBPACK_IMPORTED_MODULE_6__["isNullOrUndefined"])(key));
case 22:
case "end":
return _context5.stop();
}
}
}, _callee5, this);
}));
function validateCurrentPassword() {
return _validateCurrentPassword.apply(this, arguments);
}
return validateCurrentPassword;
}()
}, {
key: "processPasswordChange",
value: function () {
var _processPasswordChange = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee6() {
var newPassword, response;
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee6$(_context6) {
while (1) {
switch (_context6.prev = _context6.next) {
case 0:
newPassword = this.securityUpdate ? this.formData.currentPassword : this.formData.newPassword;
_context6.next = 3;
return this.application.changePassword({
email: this.application.getUser().email,
currentPassword: this.formData.currentPassword,
newPassword: newPassword
});
case 3:
response = _context6.sent;
if (!response.error) {
_context6.next = 9;
break;
}
this.application.alertManager.alert({
text: response.error.message ? response.error.message : "There was an error changing your password. Please try again."
});
return _context6.abrupt("return", false);
case 9:
return _context6.abrupt("return", true);
case 10:
case "end":
return _context6.stop();
}
}
}, _callee6, this);
}));
function processPasswordChange() {
return _processPasswordChange.apply(this, arguments);
}
return processPasswordChange;
}()
}, {
key: "downloadBackup",
value: function downloadBackup(encrypted) {
this.archiveManager.downloadBackup(encrypted);
}
}, {
key: "dismiss",
value: function dismiss() {
if (this.lockContinue) {
this.application.alertManager.alert({
text: "Cannot close window until pending tasks are complete."
});
} else {
this.$element.remove();
this.$scope.$destroy();
}
}
}]);
return PasswordWizardCtrl;
}();
var PasswordWizard = function PasswordWizard() {
_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2___default()(this, PasswordWizard);
this.restrict = 'E';
this.template = _directives_password_wizard_pug__WEBPACK_IMPORTED_MODULE_4___default.a;
this.controller = PasswordWizardCtrl;
this.controllerAs = 'ctrl';
this.bindToController = true;
this.scope = {
type: '='
};
};
/***/ }),
/***/ "./app/assets/javascripts/directives/views/permissionsModal.js":
/*!*********************************************************************!*\
!*** ./app/assets/javascripts/directives/views/permissionsModal.js ***!
\*********************************************************************/
/*! exports provided: PermissionsModal */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PermissionsModal", function() { return PermissionsModal; });
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "./node_modules/@babel/runtime/helpers/classCallCheck.js");
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/helpers/createClass */ "./node_modules/@babel/runtime/helpers/createClass.js");
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _directives_permissions_modal_pug__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! %/directives/permissions-modal.pug */ "./app/assets/templates/directives/permissions-modal.pug");
/* harmony import */ var _directives_permissions_modal_pug__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_directives_permissions_modal_pug__WEBPACK_IMPORTED_MODULE_2__);
var PermissionsModalCtrl =
/*#__PURE__*/
function () {
PermissionsModalCtrl.$inject = ["$element"];
/* @ngInject */
function PermissionsModalCtrl($element) {
_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0___default()(this, PermissionsModalCtrl);
this.$element = $element;
}
_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1___default()(PermissionsModalCtrl, [{
key: "dismiss",
value: function dismiss() {
this.$element.remove();
}
}, {
key: "accept",
value: function accept() {
this.callback(true);
this.dismiss();
}
}, {
key: "deny",
value: function deny() {
this.callback(false);
this.dismiss();
}
}]);
return PermissionsModalCtrl;
}();
var PermissionsModal = function PermissionsModal() {
_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0___default()(this, PermissionsModal);
this.restrict = 'E';
this.template = _directives_permissions_modal_pug__WEBPACK_IMPORTED_MODULE_2___default.a;
this.controller = PermissionsModalCtrl;
this.controllerAs = 'ctrl';
this.bindToController = true;
this.scope = {
show: '=',
component: '=',
permissionsString: '=',
callback: '='
};
};
/***/ }),
/***/ "./app/assets/javascripts/directives/views/privilegesAuthModal.js":
/*!************************************************************************!*\
!*** ./app/assets/javascripts/directives/views/privilegesAuthModal.js ***!
\************************************************************************/
/*! exports provided: PrivilegesAuthModal */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PrivilegesAuthModal", function() { return PrivilegesAuthModal; });
/* harmony import */ var _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/regenerator */ "./node_modules/@babel/runtime/regenerator/index.js");
/* harmony import */ var _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/helpers/asyncToGenerator */ "./node_modules/@babel/runtime/helpers/asyncToGenerator.js");
/* harmony import */ var _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "./node_modules/@babel/runtime/helpers/classCallCheck.js");
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @babel/runtime/helpers/createClass */ "./node_modules/@babel/runtime/helpers/createClass.js");
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var _directives_privileges_auth_modal_pug__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! %/directives/privileges-auth-modal.pug */ "./app/assets/templates/directives/privileges-auth-modal.pug");
/* harmony import */ var _directives_privileges_auth_modal_pug__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(_directives_privileges_auth_modal_pug__WEBPACK_IMPORTED_MODULE_4__);
var PrivilegesAuthModalCtrl =
/*#__PURE__*/
function () {
PrivilegesAuthModalCtrl.$inject = ["$element", "$timeout", "application"];
/* @ngInject */
function PrivilegesAuthModalCtrl($element, $timeout, application) {
_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2___default()(this, PrivilegesAuthModalCtrl);
this.$element = $element;
this.$timeout = $timeout;
this.application = application;
}
_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3___default()(PrivilegesAuthModalCtrl, [{
key: "$onInit",
value: function $onInit() {
var _this = this;
this.authParameters = {};
this.sessionLengthOptions = this.application.privilegesManager.getSessionLengthOptions();
this.application.privilegesManager.getSelectedSessionLength().then(function (length) {
_this.$timeout(function () {
_this.selectedSessionLength = length;
});
});
this.application.privilegesManager.netCredentialsForAction(this.action).then(function (credentials) {
_this.$timeout(function () {
_this.requiredCredentials = credentials.sort();
});
});
}
}, {
key: "selectSessionLength",
value: function selectSessionLength(length) {
this.selectedSessionLength = length;
}
}, {
key: "promptForCredential",
value: function promptForCredential(credential) {
return this.application.privilegesManager.displayInfoForCredential(credential).prompt;
}
}, {
key: "cancel",
value: function cancel() {
this.dismiss();
this.onCancel && this.onCancel();
}
}, {
key: "isCredentialInFailureState",
value: function isCredentialInFailureState(credential) {
if (!this.failedCredentials) {
return false;
}
return this.failedCredentials.find(function (candidate) {
return candidate === credential;
}) != null;
}
}, {
key: "validate",
value: function validate() {
var failed = [];
var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = undefined;
try {
for (var _iterator = this.requiredCredentials[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
var cred = _step.value;
var value = this.authParameters[cred];
if (!value || value.length === 0) {
failed.push(cred);
}
}
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
} finally {
try {
if (!_iteratorNormalCompletion && _iterator.return != null) {
_iterator.return();
}
} finally {
if (_didIteratorError) {
throw _iteratorError;
}
}
}
this.failedCredentials = failed;
return failed.length === 0;
}
}, {
key: "submit",
value: function () {
var _submit = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee() {
var _this2 = this;
var result;
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
if (this.validate()) {
_context.next = 2;
break;
}
return _context.abrupt("return");
case 2:
_context.next = 4;
return this.application.privilegesManager.authenticateAction(this.action, this.authParameters);
case 4:
result = _context.sent;
this.$timeout(function () {
if (result.success) {
_this2.application.privilegesManager.setSessionLength(_this2.selectedSessionLength);
_this2.onSuccess();
_this2.dismiss();
} else {
_this2.failedCredentials = result.failedCredentials;
}
});
case 6:
case "end":
return _context.stop();
}
}
}, _callee, this);
}));
function submit() {
return _submit.apply(this, arguments);
}
return submit;
}()
}, {
key: "dismiss",
value: function dismiss() {
this.$element.remove();
}
}]);
return PrivilegesAuthModalCtrl;
}();
var PrivilegesAuthModal = function PrivilegesAuthModal() {
_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2___default()(this, PrivilegesAuthModal);
this.restrict = 'E';
this.template = _directives_privileges_auth_modal_pug__WEBPACK_IMPORTED_MODULE_4___default.a;
this.controller = PrivilegesAuthModalCtrl;
this.controllerAs = 'ctrl';
this.bindToController = true;
this.scope = {
action: '=',
onSuccess: '=',
onCancel: '='
};
};
/***/ }),
/***/ "./app/assets/javascripts/directives/views/privilegesManagementModal.js":
/*!******************************************************************************!*\
!*** ./app/assets/javascripts/directives/views/privilegesManagementModal.js ***!
\******************************************************************************/
/*! exports provided: PrivilegesManagementModal */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PrivilegesManagementModal", function() { return PrivilegesManagementModal; });
/* harmony import */ var _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/regenerator */ "./node_modules/@babel/runtime/regenerator/index.js");
/* harmony import */ var _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/helpers/asyncToGenerator */ "./node_modules/@babel/runtime/helpers/asyncToGenerator.js");
/* harmony import */ var _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "./node_modules/@babel/runtime/helpers/classCallCheck.js");
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @babel/runtime/helpers/createClass */ "./node_modules/@babel/runtime/helpers/createClass.js");
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var _services_privilegesManager__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @/services/privilegesManager */ "./app/assets/javascripts/services/privilegesManager.js");
/* harmony import */ var _directives_privileges_management_modal_pug__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! %/directives/privileges-management-modal.pug */ "./app/assets/templates/directives/privileges-management-modal.pug");
/* harmony import */ var _directives_privileges_management_modal_pug__WEBPACK_IMPORTED_MODULE_5___default = /*#__PURE__*/__webpack_require__.n(_directives_privileges_management_modal_pug__WEBPACK_IMPORTED_MODULE_5__);
var PrivilegesManagementModalCtrl =
/*#__PURE__*/
function () {
PrivilegesManagementModalCtrl.$inject = ["$timeout", "$element", "application"];
/* @ngInject */
function PrivilegesManagementModalCtrl($timeout, $element, application) {
_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2___default()(this, PrivilegesManagementModalCtrl);
this.$element = $element;
this.$timeout = $timeout;
this.application = application;
this.hasPasscode = application.hasPasscode();
this.hasAccount = !application.noUser();
this.reloadPrivileges();
}
_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3___default()(PrivilegesManagementModalCtrl, [{
key: "displayInfoForCredential",
value: function displayInfoForCredential(credential) {
var info = this.application.privilegesManager.displayInfoForCredential(credential);
if (credential === _services_privilegesManager__WEBPACK_IMPORTED_MODULE_4__["PrivilegesManager"].CredentialLocalPasscode) {
info.availability = this.hasPasscode;
} else if (credential === _services_privilegesManager__WEBPACK_IMPORTED_MODULE_4__["PrivilegesManager"].CredentialAccountPassword) {
info.availability = this.hasAccount;
} else {
info.availability = true;
}
return info;
}
}, {
key: "displayInfoForAction",
value: function displayInfoForAction(action) {
return this.application.privilegesManager.displayInfoForAction(action).label;
}
}, {
key: "isCredentialRequiredForAction",
value: function isCredentialRequiredForAction(action, credential) {
if (!this.privileges) {
return false;
}
return this.privileges.isCredentialRequiredForAction(action, credential);
}
}, {
key: "clearSession",
value: function () {
var _clearSession = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee() {
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
_context.next = 2;
return this.application.privilegesManager.clearSession();
case 2:
this.reloadPrivileges();
case 3:
case "end":
return _context.stop();
}
}
}, _callee, this);
}));
function clearSession() {
return _clearSession.apply(this, arguments);
}
return clearSession;
}()
}, {
key: "reloadPrivileges",
value: function () {
var _reloadPrivileges = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee2() {
var _this = this;
var sessionEndDate, _iteratorNormalCompletion, _didIteratorError, _iteratorError, _iterator, _step, cred, privs;
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee2$(_context2) {
while (1) {
switch (_context2.prev = _context2.next) {
case 0:
this.availableActions = this.application.privilegesManager.getAvailableActions();
this.availableCredentials = this.application.privilegesManager.getAvailableCredentials();
_context2.next = 4;
return this.application.privilegesManager.getSessionExpirey();
case 4:
sessionEndDate = _context2.sent;
this.sessionExpirey = sessionEndDate.toLocaleString();
this.sessionExpired = new Date() >= sessionEndDate;
this.credentialDisplayInfo = {};
_iteratorNormalCompletion = true;
_didIteratorError = false;
_iteratorError = undefined;
_context2.prev = 11;
for (_iterator = this.availableCredentials[Symbol.iterator](); !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
cred = _step.value;
this.credentialDisplayInfo[cred] = this.displayInfoForCredential(cred);
}
_context2.next = 19;
break;
case 15:
_context2.prev = 15;
_context2.t0 = _context2["catch"](11);
_didIteratorError = true;
_iteratorError = _context2.t0;
case 19:
_context2.prev = 19;
_context2.prev = 20;
if (!_iteratorNormalCompletion && _iterator.return != null) {
_iterator.return();
}
case 22:
_context2.prev = 22;
if (!_didIteratorError) {
_context2.next = 25;
break;
}
throw _iteratorError;
case 25:
return _context2.finish(22);
case 26:
return _context2.finish(19);
case 27:
_context2.next = 29;
return this.application.privilegesManager.getPrivileges();
case 29:
privs = _context2.sent;
this.$timeout(function () {
_this.privileges = privs;
});
case 31:
case "end":
return _context2.stop();
}
}
}, _callee2, this, [[11, 15, 19, 27], [20,, 22, 26]]);
}));
function reloadPrivileges() {
return _reloadPrivileges.apply(this, arguments);
}
return reloadPrivileges;
}()
}, {
key: "checkboxValueChanged",
value: function checkboxValueChanged(action, credential) {
this.privileges.toggleCredentialForAction(action, credential);
this.application.privilegesManager.savePrivileges();
}
}, {
key: "cancel",
value: function cancel() {
this.dismiss();
this.onCancel && this.onCancel();
}
}, {
key: "dismiss",
value: function dismiss() {
this.$element.remove();
}
}]);
return PrivilegesManagementModalCtrl;
}();
var PrivilegesManagementModal = function PrivilegesManagementModal() {
_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2___default()(this, PrivilegesManagementModal);
this.restrict = 'E';
this.template = _directives_privileges_management_modal_pug__WEBPACK_IMPORTED_MODULE_5___default.a;
this.controller = PrivilegesManagementModalCtrl;
this.controllerAs = 'ctrl';
this.bindToController = true;
this.scope = {};
};
/***/ }),
/***/ "./app/assets/javascripts/directives/views/revisionPreviewModal.js":
/*!*************************************************************************!*\
!*** ./app/assets/javascripts/directives/views/revisionPreviewModal.js ***!
\*************************************************************************/
/*! exports provided: RevisionPreviewModal */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RevisionPreviewModal", function() { return RevisionPreviewModal; });
/* harmony import */ var _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/regenerator */ "./node_modules/@babel/runtime/regenerator/index.js");
/* harmony import */ var _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/helpers/asyncToGenerator */ "./node_modules/@babel/runtime/helpers/asyncToGenerator.js");
/* harmony import */ var _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "./node_modules/@babel/runtime/helpers/classCallCheck.js");
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @babel/runtime/helpers/createClass */ "./node_modules/@babel/runtime/helpers/createClass.js");
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var snjs__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! snjs */ "../snjs/dist/snjs.js");
/* harmony import */ var snjs__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(snjs__WEBPACK_IMPORTED_MODULE_4__);
/* harmony import */ var _directives_revision_preview_modal_pug__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! %/directives/revision-preview-modal.pug */ "./app/assets/templates/directives/revision-preview-modal.pug");
/* harmony import */ var _directives_revision_preview_modal_pug__WEBPACK_IMPORTED_MODULE_5___default = /*#__PURE__*/__webpack_require__.n(_directives_revision_preview_modal_pug__WEBPACK_IMPORTED_MODULE_5__);
var RevisionPreviewModalCtrl =
/*#__PURE__*/
function () {
RevisionPreviewModalCtrl.$inject = ["$element", "$scope", "$timeout"];
/* @ngInject */
function RevisionPreviewModalCtrl($element, $scope, $timeout) {
var _this = this;
_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2___default()(this, RevisionPreviewModalCtrl);
this.$element = $element;
this.$scope = $scope;
this.$timeout = $timeout;
this.configure();
$scope.$on('$destroy', function () {
if (_this.identifier) {
_this.application.componentManager.deregisterHandler(_this.identifier);
}
});
}
_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3___default()(RevisionPreviewModalCtrl, [{
key: "configure",
value: function () {
var _configure = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee() {
var _this2 = this;
var editorForNote, editorCopy;
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
_context.next = 2;
return this.application.createItem({
contentType: snjs__WEBPACK_IMPORTED_MODULE_4__["CONTENT_TYPE_NOTE"],
content: this.content
});
case 2:
this.note = _context.sent;
/**
* Set UUID so editoForNote can find proper editor, but then generate new uuid
* for note as not to save changes to original, if editor makes changes.
*/
this.note.uuid = this.uuid;
editorForNote = this.application.componentManager.editorForNote(this.note);
_context.next = 7;
return this.application.generateUuid();
case 7:
this.note.uuid = _context.sent;
if (!editorForNote) {
_context.next = 17;
break;
}
_context.next = 11;
return this.application.createItem({
contentType: snjs__WEBPACK_IMPORTED_MODULE_4__["CONTENT_TYPE_COMPONENT"],
content: editorForNote.content
});
case 11:
editorCopy = _context.sent;
editorCopy.readonly = true;
editorCopy.lockReadonly = true;
this.identifier = editorCopy.uuid;
this.application.componentManager.registerHandler({
identifier: this.identifier,
areas: ['editor-editor'],
contextRequestHandler: function contextRequestHandler(component) {
if (component === _this2.editor) {
return _this2.note;
}
},
componentForSessionKeyHandler: function componentForSessionKeyHandler(key) {
if (key === _this2.editor.sessionKey) {
return _this2.editor;
}
}
});
this.editor = editorCopy;
case 17:
case "end":
return _context.stop();
}
}
}, _callee, this);
}));
function configure() {
return _configure.apply(this, arguments);
}
return configure;
}()
}, {
key: "restore",
value: function restore(asCopy) {
var _this3 = this;
var run =
/*#__PURE__*/
function () {
var _ref = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee2() {
var item, contentCopy, uuid;
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee2$(_context2) {
while (1) {
switch (_context2.prev = _context2.next) {
case 0:
if (!asCopy) {
_context2.next = 8;
break;
}
contentCopy = Object.assign({}, _this3.content);
if (contentCopy.title) {
contentCopy.title += " (copy)";
}
_context2.next = 5;
return _this3.application.createItem({
contentType: 'Note',
content: contentCopy,
needsSync: true
});
case 5:
item = _context2.sent;
_context2.next = 13;
break;
case 8:
uuid = _this3.uuid;
item = _this3.application.findItem({
uuid: uuid
});
item.content = Object.assign({}, _this3.content);
_context2.next = 13;
return _this3.application.mergeItem({
item: item,
source: snjs__WEBPACK_IMPORTED_MODULE_4__["PAYLOAD_SOURCE_REMOTE_ACTION_RETRIEVED"]
});
case 13:
_this3.application.saveItem({
item: item
});
_this3.dismiss();
case 15:
case "end":
return _context2.stop();
}
}
}, _callee2);
}));
return function run() {
return _ref.apply(this, arguments);
};
}();
if (!asCopy) {
this.application.alertManager.confirm({
text: "Are you sure you want to replace the current note's contents with what you see in this preview?",
destructive: true,
onConfirm: run
});
} else {
run();
}
}
}, {
key: "dismiss",
value: function dismiss() {
this.$element.remove();
this.$scope.$destroy();
}
}]);
return RevisionPreviewModalCtrl;
}();
var RevisionPreviewModal = function RevisionPreviewModal() {
_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2___default()(this, RevisionPreviewModal);
this.restrict = 'E';
this.template = _directives_revision_preview_modal_pug__WEBPACK_IMPORTED_MODULE_5___default.a;
this.controller = RevisionPreviewModalCtrl;
this.controllerAs = 'ctrl';
this.bindToController = true;
this.scope = {
uuid: '=',
content: '='
};
};
/***/ }),
/***/ "./app/assets/javascripts/directives/views/sessionHistoryMenu.js":
/*!***********************************************************************!*\
!*** ./app/assets/javascripts/directives/views/sessionHistoryMenu.js ***!
\***********************************************************************/
/*! exports provided: SessionHistoryMenu */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SessionHistoryMenu", function() { return SessionHistoryMenu; });
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "./node_modules/@babel/runtime/helpers/classCallCheck.js");
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/helpers/createClass */ "./node_modules/@babel/runtime/helpers/createClass.js");
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _directives_session_history_menu_pug__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! %/directives/session-history-menu.pug */ "./app/assets/templates/directives/session-history-menu.pug");
/* harmony import */ var _directives_session_history_menu_pug__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_directives_session_history_menu_pug__WEBPACK_IMPORTED_MODULE_2__);
var SessionHistoryMenuCtrl =
/*#__PURE__*/
function () {
SessionHistoryMenuCtrl.$inject = ["$timeout", "godService", "application"];
/* @ngInject */
function SessionHistoryMenuCtrl($timeout, godService, application) {
_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0___default()(this, SessionHistoryMenuCtrl);
this.$timeout = $timeout;
this.godService = godService;
this.application = application;
this.diskEnabled = this.application.historyManager.isDiskEnabled();
this.autoOptimize = this.application.historyManager.isAutoOptimizeEnabled();
}
_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1___default()(SessionHistoryMenuCtrl, [{
key: "$onInit",
value: function $onInit() {
this.reloadHistory();
}
}, {
key: "reloadHistory",
value: function reloadHistory() {
var history = this.application.historyManager.historyForItem(this.item);
this.entries = history.entries.slice(0).sort(function (a, b) {
return a.item.updated_at < b.item.updated_at ? 1 : -1;
});
this.history = history;
}
}, {
key: "openRevision",
value: function openRevision(revision) {
this.godService.presentRevisionPreviewModal(revision.item.uuid, revision.item.content);
}
}, {
key: "classForRevision",
value: function classForRevision(revision) {
var vector = revision.operationVector();
if (vector === 0) {
return 'default';
} else if (vector === 1) {
return 'success';
} else if (vector === -1) {
return 'danger';
}
}
}, {
key: "clearItemHistory",
value: function clearItemHistory() {
var _this = this;
this.application.alertManager.confirm({
text: "Are you sure you want to delete the local session history for this note?",
destructive: true,
onConfirm: function onConfirm() {
_this.application.historyManager.clearHistoryForItem(_this.item).then(function () {
_this.$timeout(function () {
_this.reloadHistory();
});
});
}
});
}
}, {
key: "clearAllHistory",
value: function clearAllHistory() {
var _this2 = this;
this.application.alertManager.confirm({
text: "Are you sure you want to delete the local session history for all notes?",
destructive: true,
onConfirm: function onConfirm() {
_this2.application.historyManager.clearAllHistory().then(function () {
_this2.$timeout(function () {
_this2.reloadHistory();
});
});
}
});
}
}, {
key: "toggleDiskSaving",
value: function toggleDiskSaving() {
var _this3 = this;
var run = function run() {
_this3.application.historyManager.toggleDiskSaving().then(function () {
_this3.$timeout(function () {
_this3.diskEnabled = _this3.application.historyManager.diskEnabled;
});
});
};
if (!this.application.historyManager.diskEnabled) {
this.application.alertManager.confirm({
text: "Are you sure you want to save history to disk? This will decrease general \n performance, especially as you type. You are advised to disable this feature \n if you experience any lagging.",
destructive: true,
onConfirm: run
});
} else {
run();
}
}
}, {
key: "toggleAutoOptimize",
value: function toggleAutoOptimize() {
var _this4 = this;
this.application.historyManager.toggleAutoOptimize().then(function () {
_this4.$timeout(function () {
_this4.autoOptimize = _this4.application.historyManager.autoOptimize;
});
});
}
}]);
return SessionHistoryMenuCtrl;
}();
var SessionHistoryMenu = function SessionHistoryMenu() {
_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0___default()(this, SessionHistoryMenu);
this.restrict = 'E';
this.template = _directives_session_history_menu_pug__WEBPACK_IMPORTED_MODULE_2___default.a;
this.controller = SessionHistoryMenuCtrl;
this.controllerAs = 'ctrl';
this.bindToController = true;
this.scope = {
item: '='
};
};
/***/ }),
/***/ "./app/assets/javascripts/directives/views/syncResolutionMenu.js":
/*!***********************************************************************!*\
!*** ./app/assets/javascripts/directives/views/syncResolutionMenu.js ***!
\***********************************************************************/
/*! exports provided: SyncResolutionMenu */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SyncResolutionMenu", function() { return SyncResolutionMenu; });
/* harmony import */ var _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/regenerator */ "./node_modules/@babel/runtime/regenerator/index.js");
/* harmony import */ var _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/helpers/asyncToGenerator */ "./node_modules/@babel/runtime/helpers/asyncToGenerator.js");
/* harmony import */ var _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "./node_modules/@babel/runtime/helpers/classCallCheck.js");
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @babel/runtime/helpers/createClass */ "./node_modules/@babel/runtime/helpers/createClass.js");
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var _directives_sync_resolution_menu_pug__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! %/directives/sync-resolution-menu.pug */ "./app/assets/templates/directives/sync-resolution-menu.pug");
/* harmony import */ var _directives_sync_resolution_menu_pug__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(_directives_sync_resolution_menu_pug__WEBPACK_IMPORTED_MODULE_4__);
var SyncResolutionMenuCtrl =
/*#__PURE__*/
function () {
SyncResolutionMenuCtrl.$inject = ["$timeout", "archiveManager", "application"];
/* @ngInject */
function SyncResolutionMenuCtrl($timeout, archiveManager, application) {
_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2___default()(this, SyncResolutionMenuCtrl);
this.$timeout = $timeout;
this.archiveManager = archiveManager;
this.application = application;
this.status = {};
}
_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3___default()(SyncResolutionMenuCtrl, [{
key: "downloadBackup",
value: function downloadBackup(encrypted) {
this.archiveManager.downloadBackup(encrypted);
this.status.backupFinished = true;
}
}, {
key: "skipBackup",
value: function skipBackup() {
this.status.backupFinished = true;
}
}, {
key: "performSyncResolution",
value: function () {
var _performSyncResolution = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee() {
var _this = this;
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
this.status.resolving = true;
_context.next = 3;
return this.application.resolveOutOfSync();
case 3:
this.$timeout(function () {
_this.status.resolving = false;
_this.status.attemptedResolution = true;
if (_this.application.getSyncStatus().isOutOfSync()) {
_this.status.fail = true;
} else {
_this.status.success = true;
}
});
case 4:
case "end":
return _context.stop();
}
}
}, _callee, this);
}));
function performSyncResolution() {
return _performSyncResolution.apply(this, arguments);
}
return performSyncResolution;
}()
}, {
key: "close",
value: function close() {
var _this2 = this;
this.$timeout(function () {
_this2.closeFunction()();
});
}
}]);
return SyncResolutionMenuCtrl;
}();
var SyncResolutionMenu = function SyncResolutionMenu() {
_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2___default()(this, SyncResolutionMenu);
this.restrict = 'E';
this.template = _directives_sync_resolution_menu_pug__WEBPACK_IMPORTED_MODULE_4___default.a;
this.controller = SyncResolutionMenuCtrl;
this.controllerAs = 'ctrl';
this.bindToController = true;
this.scope = {
closeFunction: '&'
};
};
/***/ }),
/***/ "./app/assets/javascripts/filters/index.js":
/*!*************************************************!*\
!*** ./app/assets/javascripts/filters/index.js ***!
\*************************************************/
/*! exports provided: trusted */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _trusted__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./trusted */ "./app/assets/javascripts/filters/trusted.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "trusted", function() { return _trusted__WEBPACK_IMPORTED_MODULE_0__["trusted"]; });
/***/ }),
/***/ "./app/assets/javascripts/filters/trusted.js":
/*!***************************************************!*\
!*** ./app/assets/javascripts/filters/trusted.js ***!
\***************************************************/
/*! exports provided: trusted */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "trusted", function() { return trusted; });
trusted.$inject = ["$sce"];
/* @ngInject */
function trusted($sce) {
return function (url) {
return $sce.trustAsResourceUrl(url);
};
}
/***/ }),
/***/ "./app/assets/javascripts/index.js":
/*!*****************************************!*\
!*** ./app/assets/javascripts/index.js ***!
\*****************************************/
/*! no exports provided */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var sn_stylekit_dist_stylekit_css__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! sn-stylekit/dist/stylekit.css */ "./node_modules/sn-stylekit/dist/stylekit.css");
/* harmony import */ var sn_stylekit_dist_stylekit_css__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(sn_stylekit_dist_stylekit_css__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _stylesheets_index_css_scss__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../stylesheets/index.css.scss */ "./app/assets/stylesheets/index.css.scss");
/* harmony import */ var _stylesheets_index_css_scss__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_stylesheets_index_css_scss__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var angular__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! angular */ "./node_modules/angular/index.js");
/* harmony import */ var angular__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(angular__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _vendor_assets_javascripts_angular_sanitize__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../../vendor/assets/javascripts/angular-sanitize */ "./vendor/assets/javascripts/angular-sanitize.js");
/* harmony import */ var _vendor_assets_javascripts_angular_sanitize__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_vendor_assets_javascripts_angular_sanitize__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var _vendor_assets_javascripts_zip_deflate__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../../vendor/assets/javascripts/zip/deflate */ "./vendor/assets/javascripts/zip/deflate.js");
/* harmony import */ var _vendor_assets_javascripts_zip_deflate__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(_vendor_assets_javascripts_zip_deflate__WEBPACK_IMPORTED_MODULE_4__);
/* harmony import */ var _vendor_assets_javascripts_zip_inflate__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../../../vendor/assets/javascripts/zip/inflate */ "./vendor/assets/javascripts/zip/inflate.js");
/* harmony import */ var _vendor_assets_javascripts_zip_inflate__WEBPACK_IMPORTED_MODULE_5___default = /*#__PURE__*/__webpack_require__.n(_vendor_assets_javascripts_zip_inflate__WEBPACK_IMPORTED_MODULE_5__);
/* harmony import */ var _vendor_assets_javascripts_zip_zip__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../../../vendor/assets/javascripts/zip/zip */ "./vendor/assets/javascripts/zip/zip.js");
/* harmony import */ var _vendor_assets_javascripts_zip_zip__WEBPACK_IMPORTED_MODULE_6___default = /*#__PURE__*/__webpack_require__.n(_vendor_assets_javascripts_zip_zip__WEBPACK_IMPORTED_MODULE_6__);
/* harmony import */ var _vendor_assets_javascripts_zip_z_worker__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../../../vendor/assets/javascripts/zip/z-worker */ "./vendor/assets/javascripts/zip/z-worker.js");
/* harmony import */ var _vendor_assets_javascripts_zip_z_worker__WEBPACK_IMPORTED_MODULE_7___default = /*#__PURE__*/__webpack_require__.n(_vendor_assets_javascripts_zip_z_worker__WEBPACK_IMPORTED_MODULE_7__);
/* harmony import */ var _app__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./app */ "./app/assets/javascripts/app.js");
//= require_tree ./app
// css
// Vendor
// entry point
// eslint-disable-next-line import/first
/***/ }),
/***/ "./app/assets/javascripts/routes.js":
/*!******************************************!*\
!*** ./app/assets/javascripts/routes.js ***!
\******************************************/
/*! exports provided: configRoutes */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "configRoutes", function() { return configRoutes; });
/* harmony import */ var _utils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./utils */ "./app/assets/javascripts/utils.js");
configRoutes.$inject = ["$locationProvider"];
/* @ngInject */
function configRoutes($locationProvider) {
if (!Object(_utils__WEBPACK_IMPORTED_MODULE_0__["isDesktopApplication"])()) {
if (window.history && window.history.pushState) {
$locationProvider.html5Mode({
enabled: true,
requireBase: false
});
}
} else {
$locationProvider.html5Mode(false);
}
}
/***/ }),
/***/ "./app/assets/javascripts/services/actionsManager.js":
/*!***********************************************************!*\
!*** ./app/assets/javascripts/services/actionsManager.js ***!
\***********************************************************/
/*! exports provided: ActionsManager */
/***/ (function(module, exports) {
throw new Error("Module build failed (from ./node_modules/babel-loader/lib/index.js):\nError: ENOENT: no such file or directory, open '/Users/mo/Desktop/sn/dev/web/app/assets/javascripts/services/actionsManager.js'");
/***/ }),
/***/ "./app/assets/javascripts/services/alertManager.js":
/*!*********************************************************!*\
!*** ./app/assets/javascripts/services/alertManager.js ***!
\*********************************************************/
/*! exports provided: AlertManager */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AlertManager", function() { return AlertManager; });
/* harmony import */ var _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/regenerator */ "./node_modules/@babel/runtime/regenerator/index.js");
/* harmony import */ var _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/helpers/asyncToGenerator */ "./node_modules/@babel/runtime/helpers/asyncToGenerator.js");
/* harmony import */ var _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "./node_modules/@babel/runtime/helpers/classCallCheck.js");
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @babel/runtime/helpers/createClass */ "./node_modules/@babel/runtime/helpers/createClass.js");
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var _babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "./node_modules/@babel/runtime/helpers/possibleConstructorReturn.js");
/* harmony import */ var _babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_4__);
/* harmony import */ var _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "./node_modules/@babel/runtime/helpers/getPrototypeOf.js");
/* harmony import */ var _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_5___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_5__);
/* harmony import */ var _babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! @babel/runtime/helpers/inherits */ "./node_modules/@babel/runtime/helpers/inherits.js");
/* harmony import */ var _babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_6___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_6__);
/* harmony import */ var snjs__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! snjs */ "../snjs/dist/snjs.js");
/* harmony import */ var snjs__WEBPACK_IMPORTED_MODULE_7___default = /*#__PURE__*/__webpack_require__.n(snjs__WEBPACK_IMPORTED_MODULE_7__);
/* harmony import */ var sn_stylekit__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! sn-stylekit */ "./node_modules/sn-stylekit/dist/stylekit.js");
/* harmony import */ var sn_stylekit__WEBPACK_IMPORTED_MODULE_8___default = /*#__PURE__*/__webpack_require__.n(sn_stylekit__WEBPACK_IMPORTED_MODULE_8__);
var AlertManager =
/*#__PURE__*/
function (_SNAlertManager) {
AlertManager.$inject = ["$timeout"];
_babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_6___default()(AlertManager, _SNAlertManager);
/* @ngInject */
function AlertManager($timeout) {
var _this;
_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2___default()(this, AlertManager);
_this = _babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_4___default()(this, _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_5___default()(AlertManager).call(this));
_this.$timeout = $timeout;
return _this;
}
_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3___default()(AlertManager, [{
key: "alert",
value: function () {
var _alert = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee2() {
var _this2 = this;
var _ref,
title,
text,
_ref$closeButtonText,
closeButtonText,
onClose,
_args2 = arguments;
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee2$(_context2) {
while (1) {
switch (_context2.prev = _context2.next) {
case 0:
_ref = _args2.length > 0 && _args2[0] !== undefined ? _args2[0] : {}, title = _ref.title, text = _ref.text, _ref$closeButtonText = _ref.closeButtonText, closeButtonText = _ref$closeButtonText === void 0 ? "OK" : _ref$closeButtonText, onClose = _ref.onClose;
return _context2.abrupt("return", new Promise(function (resolve, reject) {
var buttons = [{
text: closeButtonText,
style: "neutral",
action: function () {
var _action = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee() {
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
if (onClose) {
_this2.$timeout(onClose);
}
resolve(true);
case 2:
case "end":
return _context.stop();
}
}
}, _callee);
}));
function action() {
return _action.apply(this, arguments);
}
return action;
}()
}];
var alert = new sn_stylekit__WEBPACK_IMPORTED_MODULE_8__["SKAlert"]({
title: title,
text: text,
buttons: buttons
});
alert.present();
}));
case 2:
case "end":
return _context2.stop();
}
}
}, _callee2);
}));
function alert() {
return _alert.apply(this, arguments);
}
return alert;
}()
}, {
key: "confirm",
value: function () {
var _confirm = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee5() {
var _this3 = this;
var _ref2,
title,
text,
_ref2$confirmButtonTe,
confirmButtonText,
_ref2$cancelButtonTex,
cancelButtonText,
onConfirm,
onCancel,
_ref2$destructive,
destructive,
_args5 = arguments;
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee5$(_context5) {
while (1) {
switch (_context5.prev = _context5.next) {
case 0:
_ref2 = _args5.length > 0 && _args5[0] !== undefined ? _args5[0] : {}, title = _ref2.title, text = _ref2.text, _ref2$confirmButtonTe = _ref2.confirmButtonText, confirmButtonText = _ref2$confirmButtonTe === void 0 ? "Confirm" : _ref2$confirmButtonTe, _ref2$cancelButtonTex = _ref2.cancelButtonText, cancelButtonText = _ref2$cancelButtonTex === void 0 ? "Cancel" : _ref2$cancelButtonTex, onConfirm = _ref2.onConfirm, onCancel = _ref2.onCancel, _ref2$destructive = _ref2.destructive, destructive = _ref2$destructive === void 0 ? false : _ref2$destructive;
return _context5.abrupt("return", new Promise(function (resolve, reject) {
var buttons = [{
text: cancelButtonText,
style: "neutral",
action: function () {
var _action2 = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee3() {
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee3$(_context3) {
while (1) {
switch (_context3.prev = _context3.next) {
case 0:
if (onCancel) {
_this3.$timeout(onCancel);
}
reject(false);
case 2:
case "end":
return _context3.stop();
}
}
}, _callee3);
}));
function action() {
return _action2.apply(this, arguments);
}
return action;
}()
}, {
text: confirmButtonText,
style: destructive ? "danger" : "info",
action: function () {
var _action3 = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee4() {
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee4$(_context4) {
while (1) {
switch (_context4.prev = _context4.next) {
case 0:
if (onConfirm) {
_this3.$timeout(onConfirm);
}
resolve(true);
case 2:
case "end":
return _context4.stop();
}
}
}, _callee4);
}));
function action() {
return _action3.apply(this, arguments);
}
return action;
}()
}];
var alert = new sn_stylekit__WEBPACK_IMPORTED_MODULE_8__["SKAlert"]({
title: title,
text: text,
buttons: buttons
});
alert.present();
}));
case 2:
case "end":
return _context5.stop();
}
}
}, _callee5);
}));
function confirm() {
return _confirm.apply(this, arguments);
}
return confirm;
}()
}]);
return AlertManager;
}(snjs__WEBPACK_IMPORTED_MODULE_7__["SNAlertManager"]);
/***/ }),
/***/ "./app/assets/javascripts/services/archiveManager.js":
/*!***********************************************************!*\
!*** ./app/assets/javascripts/services/archiveManager.js ***!
\***********************************************************/
/*! exports provided: ArchiveManager */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ArchiveManager", function() { return ArchiveManager; });
/* harmony import */ var _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/regenerator */ "./node_modules/@babel/runtime/regenerator/index.js");
/* harmony import */ var _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/helpers/asyncToGenerator */ "./node_modules/@babel/runtime/helpers/asyncToGenerator.js");
/* harmony import */ var _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "./node_modules/@babel/runtime/helpers/classCallCheck.js");
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @babel/runtime/helpers/createClass */ "./node_modules/@babel/runtime/helpers/createClass.js");
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var _services_privilegesManager__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @/services/privilegesManager */ "./app/assets/javascripts/services/privilegesManager.js");
var ArchiveManager =
/*#__PURE__*/
function () {
ArchiveManager.$inject = ["lockManager", "authManager", "modelManager", "privilegesManager"];
/* @ngInject */
function ArchiveManager(lockManager, authManager, modelManager, privilegesManager) {
_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2___default()(this, ArchiveManager);
this.lockManager = lockManager;
this.authManager = authManager;
this.modelManager = modelManager;
this.privilegesManager = privilegesManager;
}
/*
Public
*/
_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3___default()(ArchiveManager, [{
key: "downloadBackup",
value: function () {
var _downloadBackup = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee(encrypted) {
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
return _context.abrupt("return", this.downloadBackupOfItems(this.modelManager.allItems, encrypted));
case 1:
case "end":
return _context.stop();
}
}
}, _callee, this);
}));
function downloadBackup(_x) {
return _downloadBackup.apply(this, arguments);
}
return downloadBackup;
}()
}, {
key: "downloadBackupOfItems",
value: function () {
var _downloadBackupOfItems = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee3(items, encrypted) {
var _this = this;
var run;
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee3$(_context3) {
while (1) {
switch (_context3.prev = _context3.next) {
case 0:
run =
/*#__PURE__*/
function () {
var _ref = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee2() {
var keys, authParams;
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee2$(_context2) {
while (1) {
switch (_context2.prev = _context2.next) {
case 0:
if (!encrypted) {
_context2.next = 12;
break;
}
if (!(_this.authManager.offline() && _this.lockManager.hasPasscode())) {
_context2.next = 6;
break;
}
keys = _this.lockManager.keys();
authParams = _this.lockManager.passcodeAuthParams();
_context2.next = 12;
break;
case 6:
_context2.next = 8;
return _this.authManager.keys();
case 8:
keys = _context2.sent;
_context2.next = 11;
return _this.authManager.getAuthParams();
case 11:
authParams = _context2.sent;
case 12:
_this.__itemsData(items, keys, authParams).then(function (data) {
var modifier = encrypted ? "Encrypted" : "Decrypted";
_this.__downloadData(data, "Standard Notes ".concat(modifier, " Backup - ").concat(_this.__formattedDate(), ".txt")); // download as zipped plain text files
if (!keys) {
_this.__downloadZippedItems(items);
}
});
case 13:
case "end":
return _context2.stop();
}
}
}, _callee2);
}));
return function run() {
return _ref.apply(this, arguments);
};
}();
_context3.next = 3;
return this.privilegesManager.actionRequiresPrivilege(_services_privilegesManager__WEBPACK_IMPORTED_MODULE_4__["PrivilegesManager"].ActionManageBackups);
case 3:
if (!_context3.sent) {
_context3.next = 7;
break;
}
this.godService.presentPrivilegesModal(_services_privilegesManager__WEBPACK_IMPORTED_MODULE_4__["PrivilegesManager"].ActionManageBackups, function () {
run();
});
_context3.next = 8;
break;
case 7:
run();
case 8:
case "end":
return _context3.stop();
}
}
}, _callee3, this);
}));
function downloadBackupOfItems(_x2, _x3) {
return _downloadBackupOfItems.apply(this, arguments);
}
return downloadBackupOfItems;
}()
/*
Private
*/
}, {
key: "__formattedDate",
value: function __formattedDate() {
var string = "".concat(new Date()); // Match up to the first parenthesis, i.e do not include '(Central Standard Time)'
var matches = string.match(/^(.*?) \(/);
if (matches.length >= 2) {
return matches[1];
}
return string;
}
}, {
key: "__itemsData",
value: function () {
var _itemsData = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee4(items, keys, authParams) {
var data, blobData;
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee4$(_context4) {
while (1) {
switch (_context4.prev = _context4.next) {
case 0:
_context4.next = 2;
return this.modelManager.getJSONDataForItems(items, keys, authParams);
case 2:
data = _context4.sent;
blobData = new Blob([data], {
type: 'text/json'
});
return _context4.abrupt("return", blobData);
case 5:
case "end":
return _context4.stop();
}
}
}, _callee4, this);
}));
function __itemsData(_x4, _x5, _x6) {
return _itemsData.apply(this, arguments);
}
return __itemsData;
}()
}, {
key: "__loadZip",
value: function __loadZip(callback) {
if (window.zip) {
callback();
return;
}
var scriptTag = document.createElement('script');
scriptTag.src = "/assets/zip/zip.js";
scriptTag.async = false;
var headTag = document.getElementsByTagName('head')[0];
headTag.appendChild(scriptTag);
scriptTag.onload = function () {
zip.workerScriptsPath = "assets/zip/";
callback();
};
}
}, {
key: "__downloadZippedItems",
value: function __downloadZippedItems(items) {
var _this2 = this;
this.__loadZip(function () {
zip.createWriter(new zip.BlobWriter("application/zip"), function (zipWriter) {
var index = 0;
var nextFile = function nextFile() {
var item = items[index];
var name, contents;
if (item.content_type === "Note") {
name = item.content.title;
contents = item.content.text;
} else {
name = item.content_type;
contents = JSON.stringify(item.content, null, 2);
}
if (!name) {
name = "";
}
var blob = new Blob([contents], {
type: 'text/plain'
});
var filePrefix = name.replace(/\//g, "").replace(/\\+/g, "");
var fileSuffix = "-".concat(item.uuid.split("-")[0], ".txt"); // Standard max filename length is 255. Slice the note name down to allow filenameEnd
filePrefix = filePrefix.slice(0, 255 - fileSuffix.length);
var fileName = "".concat(item.content_type, "/").concat(filePrefix).concat(fileSuffix);
zipWriter.add(fileName, new zip.BlobReader(blob), function () {
index++;
if (index < items.length) {
nextFile();
} else {
zipWriter.close(function (blob) {
_this2.__downloadData(blob, "Standard Notes Backup - ".concat(_this2.__formattedDate(), ".zip"));
zipWriter = null;
});
}
});
};
nextFile();
}, onerror);
});
}
}, {
key: "__hrefForData",
value: function __hrefForData(data) {
// If we are replacing a previously generated file we need to
// manually revoke the object URL to avoid memory leaks.
if (this.textFile !== null) {
window.URL.revokeObjectURL(this.textFile);
}
this.textFile = window.URL.createObjectURL(data); // returns a URL you can use as a href
return this.textFile;
}
}, {
key: "__downloadData",
value: function __downloadData(data, fileName) {
var link = document.createElement('a');
link.setAttribute('download', fileName);
link.href = this.__hrefForData(data);
document.body.appendChild(link);
link.click();
link.remove();
}
}]);
return ArchiveManager;
}();
/***/ }),
/***/ "./app/assets/javascripts/services/authManager.js":
/*!********************************************************!*\
!*** ./app/assets/javascripts/services/authManager.js ***!
\********************************************************/
/*! exports provided: AuthManager */
/***/ (function(module, exports) {
throw new Error("Module build failed (from ./node_modules/babel-loader/lib/index.js):\nError: ENOENT: no such file or directory, open '/Users/mo/Desktop/sn/dev/web/app/assets/javascripts/services/authManager.js'");
/***/ }),
/***/ "./app/assets/javascripts/services/componentManager.js":
/*!*************************************************************!*\
!*** ./app/assets/javascripts/services/componentManager.js ***!
\*************************************************************/
/*! exports provided: ComponentManager */
/***/ (function(module, exports) {
throw new Error("Module build failed (from ./node_modules/babel-loader/lib/index.js):\nError: ENOENT: no such file or directory, open '/Users/mo/Desktop/sn/dev/web/app/assets/javascripts/services/componentManager.js'");
/***/ }),
/***/ "./app/assets/javascripts/services/databaseManager.js":
/*!************************************************************!*\
!*** ./app/assets/javascripts/services/databaseManager.js ***!
\************************************************************/
/*! exports provided: DatabaseManager */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DatabaseManager", function() { return DatabaseManager; });
/* harmony import */ var _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/regenerator */ "./node_modules/@babel/runtime/regenerator/index.js");
/* harmony import */ var _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/helpers/asyncToGenerator */ "./node_modules/@babel/runtime/helpers/asyncToGenerator.js");
/* harmony import */ var _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "./node_modules/@babel/runtime/helpers/classCallCheck.js");
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @babel/runtime/helpers/createClass */ "./node_modules/@babel/runtime/helpers/createClass.js");
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3__);
var DatabaseManager =
/*#__PURE__*/
function () {
DatabaseManager.$inject = ["alertManager"];
/* @ngInject */
function DatabaseManager(alertManager) {
_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2___default()(this, DatabaseManager);
this.locked = true;
this.alertManager = alertManager;
}
_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3___default()(DatabaseManager, [{
key: "displayOfflineAlert",
value: function displayOfflineAlert() {
var message = "There was an issue loading your offline database. This could happen for two reasons:";
message += "\n\n1. You're in a private window in your browser. We can't save your data without access to the local database. Please use a non-private window.";
message += "\n\n2. You have two windows of the app open at the same time. Please close any other app instances and reload the page.";
this.alertManager.alert({
text: message
});
}
}, {
key: "setLocked",
value: function setLocked(locked) {
this.locked = locked;
}
}, {
key: "openDatabase",
value: function () {
var _openDatabase = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee() {
var _this = this;
var _ref,
onUpgradeNeeded,
request,
_args = arguments;
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
_ref = _args.length > 0 && _args[0] !== undefined ? _args[0] : {}, onUpgradeNeeded = _ref.onUpgradeNeeded;
if (!this.locked) {
_context.next = 3;
break;
}
return _context.abrupt("return");
case 3:
request = window.indexedDB.open("standardnotes", 1);
return _context.abrupt("return", new Promise(function (resolve, reject) {
request.onerror = function (event) {
if (event.target.errorCode) {
_this.alertManager.alert({
text: "Offline database issue: " + event.target.errorCode
});
} else {
_this.displayOfflineAlert();
}
console.error("Offline database issue:", event);
resolve(null);
};
request.onsuccess = function (event) {
var db = event.target.result;
db.onversionchange = function (event) {
db.close();
};
db.onerror = function (errorEvent) {
console.error("Database error: " + errorEvent.target.errorCode);
};
resolve(db);
};
request.onblocked = function (event) {
console.error("Request blocked error:", event.target.errorCode);
};
request.onupgradeneeded = function (event) {
var db = event.target.result;
db.onversionchange = function (event) {
db.close();
}; // Create an objectStore for this database
var objectStore = db.createObjectStore("items", {
keyPath: "uuid"
});
objectStore.createIndex("uuid", "uuid", {
unique: true
});
objectStore.transaction.oncomplete = function (event) {
// Ready to store values in the newly created objectStore.
if (db.version === 1 && onUpgradeNeeded) {
onUpgradeNeeded();
}
};
};
}));
case 5:
case "end":
return _context.stop();
}
}
}, _callee, this);
}));
function openDatabase() {
return _openDatabase.apply(this, arguments);
}
return openDatabase;
}()
}, {
key: "getAllModels",
value: function () {
var _getAllModels = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee3() {
var db, objectStore, items;
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee3$(_context3) {
while (1) {
switch (_context3.prev = _context3.next) {
case 0:
_context3.next = 2;
return this.openDatabase();
case 2:
db = _context3.sent;
objectStore = db.transaction("items").objectStore("items");
items = [];
return _context3.abrupt("return", new Promise(
/*#__PURE__*/
function () {
var _ref2 = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee2(resolve, reject) {
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee2$(_context2) {
while (1) {
switch (_context2.prev = _context2.next) {
case 0:
objectStore.openCursor().onsuccess = function (event) {
var cursor = event.target.result;
if (cursor) {
items.push(cursor.value);
cursor.continue();
} else {
resolve(items);
}
};
case 1:
case "end":
return _context2.stop();
}
}
}, _callee2);
}));
return function (_x, _x2) {
return _ref2.apply(this, arguments);
};
}()));
case 6:
case "end":
return _context3.stop();
}
}
}, _callee3, this);
}));
function getAllModels() {
return _getAllModels.apply(this, arguments);
}
return getAllModels;
}()
}, {
key: "saveModel",
value: function () {
var _saveModel = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee4(item) {
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee4$(_context4) {
while (1) {
switch (_context4.prev = _context4.next) {
case 0:
this.saveModels([item]);
case 1:
case "end":
return _context4.stop();
}
}
}, _callee4, this);
}));
function saveModel(_x3) {
return _saveModel.apply(this, arguments);
}
return saveModel;
}()
}, {
key: "saveModels",
value: function () {
var _saveModels = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee7(items) {
var _this2 = this;
var showGenericError;
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee7$(_context7) {
while (1) {
switch (_context7.prev = _context7.next) {
case 0:
showGenericError = function showGenericError(error) {
_this2.alertManager.alert({
text: "Unable to save changes locally due to an unknown system issue. Issue Code: ".concat(error.code, " Issue Name: ").concat(error.name, ".")
});
};
return _context7.abrupt("return", new Promise(
/*#__PURE__*/
function () {
var _ref3 = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee6(resolve, reject) {
var db, transaction, itemObjectStore, putItem, _iteratorNormalCompletion, _didIteratorError, _iteratorError, _iterator, _step, item;
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee6$(_context6) {
while (1) {
switch (_context6.prev = _context6.next) {
case 0:
if (!(items.length === 0)) {
_context6.next = 3;
break;
}
resolve();
return _context6.abrupt("return");
case 3:
_context6.next = 5;
return _this2.openDatabase();
case 5:
db = _context6.sent;
transaction = db.transaction("items", "readwrite");
transaction.oncomplete = function (event) {};
transaction.onerror = function (event) {
console.error("Transaction error:", event.target.errorCode);
showGenericError(event.target.error);
};
transaction.onblocked = function (event) {
console.error("Transaction blocked error:", event.target.errorCode);
showGenericError(event.target.error);
};
transaction.onabort = function (event) {
console.error("Offline saving aborted:", event);
var error = event.target.error;
if (error.name == "QuotaExceededError") {
this.alertManager.alert({
text: "Unable to save changes locally because your device is out of space. Please free up some disk space and try again, otherwise, your data may end up in an inconsistent state."
});
} else {
showGenericError(error);
}
reject(error);
};
itemObjectStore = transaction.objectStore("items");
putItem =
/*#__PURE__*/
function () {
var _ref4 = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee5(item) {
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee5$(_context5) {
while (1) {
switch (_context5.prev = _context5.next) {
case 0:
return _context5.abrupt("return", new Promise(function (resolve, reject) {
var request = itemObjectStore.put(item);
request.onerror = function (event) {
console.error("DB put error:", event.target.error);
resolve();
};
request.onsuccess = resolve;
}));
case 1:
case "end":
return _context5.stop();
}
}
}, _callee5);
}));
return function putItem(_x7) {
return _ref4.apply(this, arguments);
};
}();
_iteratorNormalCompletion = true;
_didIteratorError = false;
_iteratorError = undefined;
_context6.prev = 16;
_iterator = items[Symbol.iterator]();
case 18:
if (_iteratorNormalCompletion = (_step = _iterator.next()).done) {
_context6.next = 25;
break;
}
item = _step.value;
_context6.next = 22;
return putItem(item);
case 22:
_iteratorNormalCompletion = true;
_context6.next = 18;
break;
case 25:
_context6.next = 31;
break;
case 27:
_context6.prev = 27;
_context6.t0 = _context6["catch"](16);
_didIteratorError = true;
_iteratorError = _context6.t0;
case 31:
_context6.prev = 31;
_context6.prev = 32;
if (!_iteratorNormalCompletion && _iterator.return != null) {
_iterator.return();
}
case 34:
_context6.prev = 34;
if (!_didIteratorError) {
_context6.next = 37;
break;
}
throw _iteratorError;
case 37:
return _context6.finish(34);
case 38:
return _context6.finish(31);
case 39:
resolve();
case 40:
case "end":
return _context6.stop();
}
}
}, _callee6, null, [[16, 27, 31, 39], [32,, 34, 38]]);
}));
return function (_x5, _x6) {
return _ref3.apply(this, arguments);
};
}()));
case 2:
case "end":
return _context7.stop();
}
}
}, _callee7);
}));
function saveModels(_x4) {
return _saveModels.apply(this, arguments);
}
return saveModels;
}()
}, {
key: "deleteModel",
value: function () {
var _deleteModel = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee9(item) {
var _this3 = this;
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee9$(_context9) {
while (1) {
switch (_context9.prev = _context9.next) {
case 0:
return _context9.abrupt("return", new Promise(
/*#__PURE__*/
function () {
var _ref5 = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee8(resolve, reject) {
var db, request;
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee8$(_context8) {
while (1) {
switch (_context8.prev = _context8.next) {
case 0:
_context8.next = 2;
return _this3.openDatabase();
case 2:
db = _context8.sent;
request = db.transaction("items", "readwrite").objectStore("items").delete(item.uuid);
request.onsuccess = function (event) {
resolve();
};
request.onerror = function (event) {
reject();
};
case 6:
case "end":
return _context8.stop();
}
}
}, _callee8);
}));
return function (_x9, _x10) {
return _ref5.apply(this, arguments);
};
}()));
case 1:
case "end":
return _context9.stop();
}
}
}, _callee9);
}));
function deleteModel(_x8) {
return _deleteModel.apply(this, arguments);
}
return deleteModel;
}()
}, {
key: "clearAllModels",
value: function () {
var _clearAllModels = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee10() {
var deleteRequest;
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee10$(_context10) {
while (1) {
switch (_context10.prev = _context10.next) {
case 0:
deleteRequest = window.indexedDB.deleteDatabase("standardnotes");
return _context10.abrupt("return", new Promise(function (resolve, reject) {
deleteRequest.onerror = function (event) {
console.error("Error deleting database.");
resolve();
};
deleteRequest.onsuccess = function (event) {
resolve();
};
deleteRequest.onblocked = function (event) {
console.error("Delete request blocked");
this.alertManager.alert({
text: "Your browser is blocking Standard Notes from deleting the local database. Make sure there are no other open windows of this app and try again. If the issue persists, please manually delete app data to sign out."
});
resolve();
};
}));
case 2:
case "end":
return _context10.stop();
}
}
}, _callee10);
}));
function clearAllModels() {
return _clearAllModels.apply(this, arguments);
}
return clearAllModels;
}()
}]);
return DatabaseManager;
}();
/***/ }),
/***/ "./app/assets/javascripts/services/desktopManager.js":
/*!***********************************************************!*\
!*** ./app/assets/javascripts/services/desktopManager.js ***!
\***********************************************************/
/*! exports provided: DesktopManager */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DesktopManager", function() { return DesktopManager; });
/* harmony import */ var _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/regenerator */ "./node_modules/@babel/runtime/regenerator/index.js");
/* harmony import */ var _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/helpers/asyncToGenerator */ "./node_modules/@babel/runtime/helpers/asyncToGenerator.js");
/* harmony import */ var _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "./node_modules/@babel/runtime/helpers/classCallCheck.js");
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @babel/runtime/helpers/createClass */ "./node_modules/@babel/runtime/helpers/createClass.js");
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! lodash */ "./node_modules/lodash/lodash.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(lodash__WEBPACK_IMPORTED_MODULE_4__);
/* harmony import */ var _utils__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! @/utils */ "./app/assets/javascripts/utils.js");
/* harmony import */ var snjs__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! snjs */ "../snjs/dist/snjs.js");
/* harmony import */ var snjs__WEBPACK_IMPORTED_MODULE_6___default = /*#__PURE__*/__webpack_require__.n(snjs__WEBPACK_IMPORTED_MODULE_6__);
// An interface used by the Desktop app to interact with SN
var COMPONENT_DATA_KEY_INSTALL_ERROR = 'installError';
var COMPONENT_CONTENT_KEY_PACKAGE_INFO = 'package_info';
var COMPONENT_CONTENT_KEY_LOCAL_URL = 'local_url';
var DesktopManager =
/*#__PURE__*/
function () {
DesktopManager.$inject = ["$rootScope", "$timeout", "modelManager", "syncManager", "authManager", "lockManager", "appState"];
/* @ngInject */
function DesktopManager($rootScope, $timeout, modelManager, syncManager, authManager, lockManager, appState) {
var _this = this;
_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2___default()(this, DesktopManager);
this.lockManager = lockManager;
this.modelManager = modelManager;
this.authManager = authManager;
this.syncManager = syncManager;
this.$rootScope = $rootScope;
this.appState = appState;
this.timeout = $timeout;
this.updateObservers = [];
this.componentActivationObservers = [];
this.isDesktop = Object(_utils__WEBPACK_IMPORTED_MODULE_5__["isDesktopApplication"])();
$rootScope.$on("initial-data-loaded", function () {
_this.dataLoaded = true;
if (_this.dataLoadHandler) {
_this.dataLoadHandler();
}
});
$rootScope.$on("major-data-change", function () {
if (_this.majorDataChangeHandler) {
_this.majorDataChangeHandler();
}
});
}
_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3___default()(DesktopManager, [{
key: "saveBackup",
value: function saveBackup() {
this.majorDataChangeHandler && this.majorDataChangeHandler();
}
}, {
key: "getExtServerHost",
value: function getExtServerHost() {
console.assert(this.extServerHost, 'extServerHost is null');
return this.extServerHost;
}
/*
Sending a component in its raw state is really slow for the desktop app
Keys are not passed into ItemParams, so the result is not encrypted
*/
}, {
key: "convertComponentForTransmission",
value: function () {
var _convertComponentForTransmission = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee(component) {
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
return _context.abrupt("return", new snjs__WEBPACK_IMPORTED_MODULE_6__["SFItemParams"](component).paramsForExportFile(true));
case 1:
case "end":
return _context.stop();
}
}
}, _callee);
}));
function convertComponentForTransmission(_x) {
return _convertComponentForTransmission.apply(this, arguments);
}
return convertComponentForTransmission;
}() // All `components` should be installed
}, {
key: "syncComponentsInstallation",
value: function syncComponentsInstallation(components) {
var _this2 = this;
if (!this.isDesktop) {
return;
}
Promise.all(components.map(function (component) {
return _this2.convertComponentForTransmission(component);
})).then(function (data) {
_this2.installationSyncHandler(data);
});
}
}, {
key: "installComponent",
value: function () {
var _installComponent = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee2(component) {
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee2$(_context2) {
while (1) {
switch (_context2.prev = _context2.next) {
case 0:
_context2.t0 = this;
_context2.next = 3;
return this.convertComponentForTransmission(component);
case 3:
_context2.t1 = _context2.sent;
_context2.t0.installComponentHandler.call(_context2.t0, _context2.t1);
case 5:
case "end":
return _context2.stop();
}
}
}, _callee2, this);
}));
function installComponent(_x2) {
return _installComponent.apply(this, arguments);
}
return installComponent;
}()
}, {
key: "registerUpdateObserver",
value: function registerUpdateObserver(callback) {
var observer = {
callback: callback
};
this.updateObservers.push(observer);
return observer;
}
}, {
key: "searchText",
value: function searchText(text) {
if (!this.isDesktop) {
return;
}
this.lastSearchedText = text;
this.searchHandler && this.searchHandler(text);
}
}, {
key: "redoSearch",
value: function redoSearch() {
if (this.lastSearchedText) {
this.searchText(this.lastSearchedText);
}
}
}, {
key: "deregisterUpdateObserver",
value: function deregisterUpdateObserver(observer) {
lodash__WEBPACK_IMPORTED_MODULE_4___default.a.pull(this.updateObservers, observer);
} // Pass null to cancel search
}, {
key: "desktop_setSearchHandler",
value: function desktop_setSearchHandler(handler) {
this.searchHandler = handler;
}
}, {
key: "desktop_windowGainedFocus",
value: function desktop_windowGainedFocus() {
this.$rootScope.$broadcast("window-gained-focus");
}
}, {
key: "desktop_windowLostFocus",
value: function desktop_windowLostFocus() {
this.$rootScope.$broadcast("window-lost-focus");
}
}, {
key: "desktop_onComponentInstallationComplete",
value: function desktop_onComponentInstallationComplete(componentData, error) {
var _this3 = this;
var component = this.modelManager.findItem(componentData.uuid);
if (!component) {
return;
}
if (error) {
component.setAppDataItem(COMPONENT_DATA_KEY_INSTALL_ERROR, error);
} else {
var permissableKeys = [COMPONENT_CONTENT_KEY_PACKAGE_INFO, COMPONENT_CONTENT_KEY_LOCAL_URL];
for (var _i = 0, _permissableKeys = permissableKeys; _i < _permissableKeys.length; _i++) {
var key = _permissableKeys[_i];
component[key] = componentData.content[key];
}
this.modelManager.notifySyncObserversOfModels([component], snjs__WEBPACK_IMPORTED_MODULE_6__["SFModelManager"].MappingSourceDesktopInstalled);
component.setAppDataItem(COMPONENT_DATA_KEY_INSTALL_ERROR, null);
}
this.modelManager.setItemDirty(component);
this.syncManager.sync();
this.timeout(function () {
var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = undefined;
try {
for (var _iterator = _this3.updateObservers[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
var observer = _step.value;
observer.callback(component);
}
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
} finally {
try {
if (!_iteratorNormalCompletion && _iterator.return != null) {
_iterator.return();
}
} finally {
if (_didIteratorError) {
throw _iteratorError;
}
}
}
});
}
}, {
key: "desktop_registerComponentActivationObserver",
value: function desktop_registerComponentActivationObserver(callback) {
var observer = {
id: Math.random,
callback: callback
};
this.componentActivationObservers.push(observer);
return observer;
}
}, {
key: "desktop_deregisterComponentActivationObserver",
value: function desktop_deregisterComponentActivationObserver(observer) {
lodash__WEBPACK_IMPORTED_MODULE_4___default.a.pull(this.componentActivationObservers, observer);
}
/* Notify observers that a component has been registered/activated */
}, {
key: "notifyComponentActivation",
value: function () {
var _notifyComponentActivation = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee3(component) {
var _this4 = this;
var serializedComponent;
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee3$(_context3) {
while (1) {
switch (_context3.prev = _context3.next) {
case 0:
_context3.next = 2;
return this.convertComponentForTransmission(component);
case 2:
serializedComponent = _context3.sent;
this.timeout(function () {
var _iteratorNormalCompletion2 = true;
var _didIteratorError2 = false;
var _iteratorError2 = undefined;
try {
for (var _iterator2 = _this4.componentActivationObservers[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
var observer = _step2.value;
observer.callback(serializedComponent);
}
} catch (err) {
_didIteratorError2 = true;
_iteratorError2 = err;
} finally {
try {
if (!_iteratorNormalCompletion2 && _iterator2.return != null) {
_iterator2.return();
}
} finally {
if (_didIteratorError2) {
throw _iteratorError2;
}
}
}
});
case 4:
case "end":
return _context3.stop();
}
}
}, _callee3, this);
}));
function notifyComponentActivation(_x3) {
return _notifyComponentActivation.apply(this, arguments);
}
return notifyComponentActivation;
}()
/* Used to resolve "sn://" */
}, {
key: "desktop_setExtServerHost",
value: function desktop_setExtServerHost(host) {
this.extServerHost = host;
this.appState.desktopExtensionsReady();
}
}, {
key: "desktop_setComponentInstallationSyncHandler",
value: function desktop_setComponentInstallationSyncHandler(handler) {
this.installationSyncHandler = handler;
}
}, {
key: "desktop_setInstallComponentHandler",
value: function desktop_setInstallComponentHandler(handler) {
this.installComponentHandler = handler;
}
}, {
key: "desktop_setInitialDataLoadHandler",
value: function desktop_setInitialDataLoadHandler(handler) {
this.dataLoadHandler = handler;
if (this.dataLoaded) {
this.dataLoadHandler();
}
}
}, {
key: "desktop_requestBackupFile",
value: function () {
var _desktop_requestBackupFile = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee4(callback) {
var keys, authParams, nullOnEmpty;
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee4$(_context4) {
while (1) {
switch (_context4.prev = _context4.next) {
case 0:
if (!(this.authManager.offline() && this.lockManager.hasPasscode())) {
_context4.next = 5;
break;
}
keys = this.lockManager.keys();
authParams = this.lockManager.passcodeAuthParams();
_context4.next = 11;
break;
case 5:
_context4.next = 7;
return this.authManager.keys();
case 7:
keys = _context4.sent;
_context4.next = 10;
return this.authManager.getAuthParams();
case 10:
authParams = _context4.sent;
case 11:
nullOnEmpty = true;
this.modelManager.getAllItemsJSONData(keys, authParams, nullOnEmpty).then(function (data) {
callback(data);
});
case 13:
case "end":
return _context4.stop();
}
}
}, _callee4, this);
}));
function desktop_requestBackupFile(_x4) {
return _desktop_requestBackupFile.apply(this, arguments);
}
return desktop_requestBackupFile;
}()
}, {
key: "desktop_setMajorDataChangeHandler",
value: function desktop_setMajorDataChangeHandler(handler) {
this.majorDataChangeHandler = handler;
}
}, {
key: "desktop_didBeginBackup",
value: function desktop_didBeginBackup() {
this.appState.beganBackupDownload();
}
}, {
key: "desktop_didFinishBackup",
value: function desktop_didFinishBackup(success) {
this.appState.endedBackupDownload({
success: success
});
}
}]);
return DesktopManager;
}();
/***/ }),
/***/ "./app/assets/javascripts/services/httpManager.js":
/*!********************************************************!*\
!*** ./app/assets/javascripts/services/httpManager.js ***!
\********************************************************/
/*! exports provided: HttpManager */
/***/ (function(module, exports) {
throw new Error("Module build failed (from ./node_modules/babel-loader/lib/index.js):\nError: ENOENT: no such file or directory, open '/Users/mo/Desktop/sn/dev/web/app/assets/javascripts/services/httpManager.js'");
/***/ }),
/***/ "./app/assets/javascripts/services/index.js":
/*!**************************************************!*\
!*** ./app/assets/javascripts/services/index.js ***!
\**************************************************/
/*! exports provided: ActionsManager, ArchiveManager, AuthManager, ComponentManager, DatabaseManager, DesktopManager, HttpManager, KeyboardManager, MigrationManager, ModelManager, NativeExtManager, LockManager, PrivilegesManager, SessionHistory, SingletonManager, StatusManager, StorageManager, SyncManager, ThemeManager, AlertManager, PreferencesManager */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _actionsManager__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./actionsManager */ "./app/assets/javascripts/services/actionsManager.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ActionsManager", function() { return _actionsManager__WEBPACK_IMPORTED_MODULE_0__["ActionsManager"]; });
/* harmony import */ var _archiveManager__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./archiveManager */ "./app/assets/javascripts/services/archiveManager.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ArchiveManager", function() { return _archiveManager__WEBPACK_IMPORTED_MODULE_1__["ArchiveManager"]; });
/* harmony import */ var _authManager__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./authManager */ "./app/assets/javascripts/services/authManager.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AuthManager", function() { return _authManager__WEBPACK_IMPORTED_MODULE_2__["AuthManager"]; });
/* harmony import */ var _componentManager__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./componentManager */ "./app/assets/javascripts/services/componentManager.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ComponentManager", function() { return _componentManager__WEBPACK_IMPORTED_MODULE_3__["ComponentManager"]; });
/* harmony import */ var _databaseManager__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./databaseManager */ "./app/assets/javascripts/services/databaseManager.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DatabaseManager", function() { return _databaseManager__WEBPACK_IMPORTED_MODULE_4__["DatabaseManager"]; });
/* harmony import */ var _desktopManager__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./desktopManager */ "./app/assets/javascripts/services/desktopManager.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DesktopManager", function() { return _desktopManager__WEBPACK_IMPORTED_MODULE_5__["DesktopManager"]; });
/* harmony import */ var _httpManager__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./httpManager */ "./app/assets/javascripts/services/httpManager.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "HttpManager", function() { return _httpManager__WEBPACK_IMPORTED_MODULE_6__["HttpManager"]; });
/* harmony import */ var _keyboardManager__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./keyboardManager */ "./app/assets/javascripts/services/keyboardManager.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "KeyboardManager", function() { return _keyboardManager__WEBPACK_IMPORTED_MODULE_7__["KeyboardManager"]; });
/* harmony import */ var _migrationManager__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./migrationManager */ "./app/assets/javascripts/services/migrationManager.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "MigrationManager", function() { return _migrationManager__WEBPACK_IMPORTED_MODULE_8__["MigrationManager"]; });
/* harmony import */ var _modelManager__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./modelManager */ "./app/assets/javascripts/services/modelManager.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ModelManager", function() { return _modelManager__WEBPACK_IMPORTED_MODULE_9__["ModelManager"]; });
/* harmony import */ var _nativeExtManager__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./nativeExtManager */ "./app/assets/javascripts/services/nativeExtManager.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "NativeExtManager", function() { return _nativeExtManager__WEBPACK_IMPORTED_MODULE_10__["NativeExtManager"]; });
/* harmony import */ var _lockManager__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./lockManager */ "./app/assets/javascripts/services/lockManager.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "LockManager", function() { return _lockManager__WEBPACK_IMPORTED_MODULE_11__["LockManager"]; });
/* harmony import */ var _privilegesManager__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ./privilegesManager */ "./app/assets/javascripts/services/privilegesManager.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PrivilegesManager", function() { return _privilegesManager__WEBPACK_IMPORTED_MODULE_12__["PrivilegesManager"]; });
/* harmony import */ var _sessionHistory__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ./sessionHistory */ "./app/assets/javascripts/services/sessionHistory.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SessionHistory", function() { return _sessionHistory__WEBPACK_IMPORTED_MODULE_13__["SessionHistory"]; });
/* harmony import */ var _singletonManager__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ./singletonManager */ "./app/assets/javascripts/services/singletonManager.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SingletonManager", function() { return _singletonManager__WEBPACK_IMPORTED_MODULE_14__["SingletonManager"]; });
/* harmony import */ var _statusManager__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ./statusManager */ "./app/assets/javascripts/services/statusManager.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "StatusManager", function() { return _statusManager__WEBPACK_IMPORTED_MODULE_15__["StatusManager"]; });
/* harmony import */ var _storageManager__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! ./storageManager */ "./app/assets/javascripts/services/storageManager.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "StorageManager", function() { return _storageManager__WEBPACK_IMPORTED_MODULE_16__["StorageManager"]; });
/* harmony import */ var _syncManager__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(/*! ./syncManager */ "./app/assets/javascripts/services/syncManager.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SyncManager", function() { return _syncManager__WEBPACK_IMPORTED_MODULE_17__["SyncManager"]; });
/* harmony import */ var _themeManager__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(/*! ./themeManager */ "./app/assets/javascripts/services/themeManager.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ThemeManager", function() { return _themeManager__WEBPACK_IMPORTED_MODULE_18__["ThemeManager"]; });
/* harmony import */ var _alertManager__WEBPACK_IMPORTED_MODULE_19__ = __webpack_require__(/*! ./alertManager */ "./app/assets/javascripts/services/alertManager.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AlertManager", function() { return _alertManager__WEBPACK_IMPORTED_MODULE_19__["AlertManager"]; });
/* harmony import */ var _preferencesManager__WEBPACK_IMPORTED_MODULE_20__ = __webpack_require__(/*! ./preferencesManager */ "./app/assets/javascripts/services/preferencesManager.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PreferencesManager", function() { return _preferencesManager__WEBPACK_IMPORTED_MODULE_20__["PreferencesManager"]; });
/***/ }),
/***/ "./app/assets/javascripts/services/keyboardManager.js":
/*!************************************************************!*\
!*** ./app/assets/javascripts/services/keyboardManager.js ***!
\************************************************************/
/*! exports provided: KeyboardManager */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "KeyboardManager", function() { return KeyboardManager; });
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "./node_modules/@babel/runtime/helpers/classCallCheck.js");
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/helpers/createClass */ "./node_modules/@babel/runtime/helpers/createClass.js");
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1__);
var KeyboardManager =
/*#__PURE__*/
function () {
function KeyboardManager() {
_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0___default()(this, KeyboardManager);
this.observers = [];
KeyboardManager.KeyTab = "Tab";
KeyboardManager.KeyBackspace = "Backspace";
KeyboardManager.KeyUp = "ArrowUp";
KeyboardManager.KeyDown = "ArrowDown";
KeyboardManager.KeyModifierShift = "Shift";
KeyboardManager.KeyModifierCtrl = "Control"; // ⌘ key on Mac, ⊞ key on Windows
KeyboardManager.KeyModifierMeta = "Meta";
KeyboardManager.KeyModifierAlt = "Alt";
KeyboardManager.KeyEventDown = "KeyEventDown";
KeyboardManager.KeyEventUp = "KeyEventUp";
KeyboardManager.AllModifiers = [KeyboardManager.KeyModifierShift, KeyboardManager.KeyModifierCtrl, KeyboardManager.KeyModifierMeta, KeyboardManager.KeyModifierAlt];
window.addEventListener('keydown', this.handleKeyDown.bind(this));
window.addEventListener('keyup', this.handleKeyUp.bind(this));
}
_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1___default()(KeyboardManager, [{
key: "modifiersForEvent",
value: function modifiersForEvent(event) {
var eventModifiers = KeyboardManager.AllModifiers.filter(function (modifier) {
// For a modifier like ctrlKey, must check both event.ctrlKey and event.key.
// That's because on keyup, event.ctrlKey would be false, but event.key == Control would be true.
var matches = (event.ctrlKey || event.key == KeyboardManager.KeyModifierCtrl) && modifier === KeyboardManager.KeyModifierCtrl || (event.metaKey || event.key == KeyboardManager.KeyModifierMeta) && modifier === KeyboardManager.KeyModifierMeta || (event.altKey || event.key == KeyboardManager.KeyModifierAlt) && modifier === KeyboardManager.KeyModifierAlt || (event.shiftKey || event.key == KeyboardManager.KeyModifierShift) && modifier === KeyboardManager.KeyModifierShift;
return matches;
});
return eventModifiers;
}
}, {
key: "eventMatchesKeyAndModifiers",
value: function eventMatchesKeyAndModifiers(event, key) {
var modifiers = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : [];
var eventModifiers = this.modifiersForEvent(event);
if (eventModifiers.length != modifiers.length) {
return false;
}
var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = undefined;
try {
for (var _iterator = modifiers[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
var modifier = _step.value;
if (!eventModifiers.includes(modifier)) {
return false;
}
} // Modifers match, check key
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
} finally {
try {
if (!_iteratorNormalCompletion && _iterator.return != null) {
_iterator.return();
}
} finally {
if (_didIteratorError) {
throw _iteratorError;
}
}
}
if (!key) {
return true;
} // In the browser, shift + f results in key 'f', but in Electron, shift + f results in 'F'
// In our case we don't differentiate between the two.
return key.toLowerCase() == event.key.toLowerCase();
}
}, {
key: "notifyObserver",
value: function notifyObserver(event, keyEventType) {
var _iteratorNormalCompletion2 = true;
var _didIteratorError2 = false;
var _iteratorError2 = undefined;
try {
for (var _iterator2 = this.observers[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
var observer = _step2.value;
if (observer.element && event.target != observer.element) {
continue;
}
if (observer.elements && !observer.elements.includes(event.target)) {
continue;
}
if (observer.notElement && observer.notElement == event.target) {
continue;
}
if (observer.notElementIds && observer.notElementIds.includes(event.target.id)) {
continue;
}
if (this.eventMatchesKeyAndModifiers(event, observer.key, observer.modifiers)) {
var callback = keyEventType == KeyboardManager.KeyEventDown ? observer.onKeyDown : observer.onKeyUp;
if (callback) {
callback(event);
}
}
}
} catch (err) {
_didIteratorError2 = true;
_iteratorError2 = err;
} finally {
try {
if (!_iteratorNormalCompletion2 && _iterator2.return != null) {
_iterator2.return();
}
} finally {
if (_didIteratorError2) {
throw _iteratorError2;
}
}
}
}
}, {
key: "handleKeyDown",
value: function handleKeyDown(event) {
this.notifyObserver(event, KeyboardManager.KeyEventDown);
}
}, {
key: "handleKeyUp",
value: function handleKeyUp(event) {
this.notifyObserver(event, KeyboardManager.KeyEventUp);
}
}, {
key: "addKeyObserver",
value: function addKeyObserver(_ref) {
var key = _ref.key,
modifiers = _ref.modifiers,
onKeyDown = _ref.onKeyDown,
onKeyUp = _ref.onKeyUp,
element = _ref.element,
elements = _ref.elements,
notElement = _ref.notElement,
notElementIds = _ref.notElementIds;
var observer = {
key: key,
modifiers: modifiers,
onKeyDown: onKeyDown,
onKeyUp: onKeyUp,
element: element,
elements: elements,
notElement: notElement,
notElementIds: notElementIds
};
this.observers.push(observer);
return observer;
}
}, {
key: "removeKeyObserver",
value: function removeKeyObserver(observer) {
this.observers.splice(this.observers.indexOf(observer), 1);
}
}]);
return KeyboardManager;
}();
/***/ }),
/***/ "./app/assets/javascripts/services/lockManager.js":
/*!********************************************************!*\
!*** ./app/assets/javascripts/services/lockManager.js ***!
\********************************************************/
/*! exports provided: LockManager */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "LockManager", function() { return LockManager; });
/* harmony import */ var _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/regenerator */ "./node_modules/@babel/runtime/regenerator/index.js");
/* harmony import */ var _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/helpers/asyncToGenerator */ "./node_modules/@babel/runtime/helpers/asyncToGenerator.js");
/* harmony import */ var _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "./node_modules/@babel/runtime/helpers/classCallCheck.js");
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @babel/runtime/helpers/createClass */ "./node_modules/@babel/runtime/helpers/createClass.js");
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! lodash */ "./node_modules/lodash/lodash.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(lodash__WEBPACK_IMPORTED_MODULE_4__);
/* harmony import */ var _utils__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! @/utils */ "./app/assets/javascripts/utils.js");
/* harmony import */ var _state__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../state */ "./app/assets/javascripts/state.js");
var MILLISECONDS_PER_SECOND = 1000;
var FOCUS_POLL_INTERVAL = 1 * MILLISECONDS_PER_SECOND;
var LOCK_INTERVAL_NONE = 0;
var LOCK_INTERVAL_IMMEDIATE = 1;
var LOCK_INTERVAL_ONE_MINUTE = 60 * MILLISECONDS_PER_SECOND;
var LOCK_INTERVAL_FIVE_MINUTES = 300 * MILLISECONDS_PER_SECOND;
var LOCK_INTERVAL_ONE_HOUR = 3600 * MILLISECONDS_PER_SECOND;
var STORAGE_KEY_AUTOLOCK_INTERVAL = "AutoLockIntervalKey";
var LockManager =
/*#__PURE__*/
function () {
LockManager.$inject = ["$rootScope", "application", "appState"];
/* @ngInject */
function LockManager($rootScope, application, appState) {
_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2___default()(this, LockManager);
this.$rootScope = $rootScope;
this.application = application;
this.appState = appState;
this.observeVisibility();
}
_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3___default()(LockManager, [{
key: "observeVisibility",
value: function observeVisibility() {
var _this = this;
this.appState.addObserver(function (eventName, data) {
if (eventName === _state__WEBPACK_IMPORTED_MODULE_6__["APP_STATE_EVENT_WINDOW_DID_BLUR"]) {
_this.documentVisibilityChanged(false);
} else if (eventName === _state__WEBPACK_IMPORTED_MODULE_6__["APP_STATE_EVENT_WINDOW_DID_FOCUS"]) {
_this.documentVisibilityChanged(true);
}
});
if (!Object(_utils__WEBPACK_IMPORTED_MODULE_5__["isDesktopApplication"])()) {
this.beginWebFocusPolling();
}
}
}, {
key: "setAutoLockInterval",
value: function () {
var _setAutoLockInterval = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee(interval) {
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
return _context.abrupt("return", this.application.setValue(STORAGE_KEY_AUTOLOCK_INTERVAL, JSON.stringify(interval)));
case 1:
case "end":
return _context.stop();
}
}
}, _callee, this);
}));
function setAutoLockInterval(_x) {
return _setAutoLockInterval.apply(this, arguments);
}
return setAutoLockInterval;
}()
}, {
key: "getAutoLockInterval",
value: function () {
var _getAutoLockInterval = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee2() {
var interval;
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee2$(_context2) {
while (1) {
switch (_context2.prev = _context2.next) {
case 0:
_context2.next = 2;
return this.application.getValue(STORAGE_KEY_AUTOLOCK_INTERVAL);
case 2:
interval = _context2.sent;
if (!interval) {
_context2.next = 7;
break;
}
return _context2.abrupt("return", JSON.parse(interval));
case 7:
return _context2.abrupt("return", LOCK_INTERVAL_NONE);
case 8:
case "end":
return _context2.stop();
}
}
}, _callee2, this);
}));
function getAutoLockInterval() {
return _getAutoLockInterval.apply(this, arguments);
}
return getAutoLockInterval;
}()
/**
* Verify document is in focus every so often as visibilitychange event is
* not triggered on a typical window blur event but rather on tab changes.
*/
}, {
key: "beginWebFocusPolling",
value: function beginWebFocusPolling() {
var _this2 = this;
this.pollFocusTimeout = setInterval(function () {
var hasFocus = document.hasFocus();
if (hasFocus && _this2.lastFocusState === 'hidden') {
_this2.documentVisibilityChanged(true);
} else if (!hasFocus && _this2.lastFocusState === 'visible') {
_this2.documentVisibilityChanged(false);
}
/* Save this to compare against next time around */
_this2.lastFocusState = hasFocus ? 'visible' : 'hidden';
}, FOCUS_POLL_INTERVAL);
}
}, {
key: "getAutoLockIntervalOptions",
value: function getAutoLockIntervalOptions() {
return [{
value: LOCK_INTERVAL_NONE,
label: "Off"
}, {
value: LOCK_INTERVAL_IMMEDIATE,
label: "Immediately"
}, {
value: LOCK_INTERVAL_ONE_MINUTE,
label: "1m"
}, {
value: LOCK_INTERVAL_FIVE_MINUTES,
label: "5m"
}, {
value: LOCK_INTERVAL_ONE_HOUR,
label: "1h"
}];
}
}, {
key: "documentVisibilityChanged",
value: function documentVisibilityChanged(visible) {
if (visible) {
if (!this.isLocked() && this.lockAfterDate && new Date() > this.lockAfterDate) {
this.application.passcodeLock();
}
this.cancelAutoLockTimer();
} else {
this.beginAutoLockTimer();
}
}
}, {
key: "beginAutoLockTimer",
value: function () {
var _beginAutoLockTimer = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee3() {
var _this3 = this;
var interval, addToNow;
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee3$(_context3) {
while (1) {
switch (_context3.prev = _context3.next) {
case 0:
_context3.next = 2;
return this.getAutoLockInterval();
case 2:
interval = _context3.sent;
if (!(interval === LOCK_INTERVAL_NONE)) {
_context3.next = 5;
break;
}
return _context3.abrupt("return");
case 5:
/**
* Use a timeout if possible, but if the computer is put to sleep, timeouts won't
* work. Need to set a date as backup. this.lockAfterDate does not need to be
* persisted, as living in memory is sufficient. If memory is cleared, then the
* application will lock anyway.
*/
addToNow = function addToNow(seconds) {
var date = new Date();
date.setSeconds(date.getSeconds() + seconds);
return date;
};
this.lockAfterDate = addToNow(interval / MILLISECONDS_PER_SECOND);
this.lockTimeout = setTimeout(function () {
_this3.cancelAutoLockTimer();
_this3.application.passcodeLock();
_this3.lockAfterDate = null;
}, interval);
case 8:
case "end":
return _context3.stop();
}
}
}, _callee3, this);
}));
function beginAutoLockTimer() {
return _beginAutoLockTimer.apply(this, arguments);
}
return beginAutoLockTimer;
}()
}, {
key: "cancelAutoLockTimer",
value: function cancelAutoLockTimer() {
clearTimeout(this.lockTimeout);
this.lockAfterDate = null;
}
}]);
return LockManager;
}();
/***/ }),
/***/ "./app/assets/javascripts/services/migrationManager.js":
/*!*************************************************************!*\
!*** ./app/assets/javascripts/services/migrationManager.js ***!
\*************************************************************/
/*! exports provided: MigrationManager */
/***/ (function(module, exports) {
throw new Error("Module build failed (from ./node_modules/babel-loader/lib/index.js):\nError: ENOENT: no such file or directory, open '/Users/mo/Desktop/sn/dev/web/app/assets/javascripts/services/migrationManager.js'");
/***/ }),
/***/ "./app/assets/javascripts/services/modelManager.js":
/*!*********************************************************!*\
!*** ./app/assets/javascripts/services/modelManager.js ***!
\*********************************************************/
/*! exports provided: ModelManager */
/***/ (function(module, exports) {
throw new Error("Module build failed (from ./node_modules/babel-loader/lib/index.js):\nError: ENOENT: no such file or directory, open '/Users/mo/Desktop/sn/dev/web/app/assets/javascripts/services/modelManager.js'");
/***/ }),
/***/ "./app/assets/javascripts/services/nativeExtManager.js":
/*!*************************************************************!*\
!*** ./app/assets/javascripts/services/nativeExtManager.js ***!
\*************************************************************/
/*! exports provided: NativeExtManager */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "NativeExtManager", function() { return NativeExtManager; });
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "./node_modules/@babel/runtime/helpers/classCallCheck.js");
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/helpers/createClass */ "./node_modules/@babel/runtime/helpers/createClass.js");
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _utils__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @/utils */ "./app/assets/javascripts/utils.js");
/* harmony import */ var snjs__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! snjs */ "../snjs/dist/snjs.js");
/* harmony import */ var snjs__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(snjs__WEBPACK_IMPORTED_MODULE_3__);
/* A class for handling installation of system extensions */
var NativeExtManager =
/*#__PURE__*/
function () {
NativeExtManager.$inject = ["modelManager", "syncManager", "singletonManager"];
/* @ngInject */
function NativeExtManager(modelManager, syncManager, singletonManager) {
_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0___default()(this, NativeExtManager);
this.modelManager = modelManager;
this.syncManager = syncManager;
this.singletonManager = singletonManager;
this.extManagerId = "org.standardnotes.extensions-manager";
this.batchManagerId = "org.standardnotes.batch-manager";
this.systemExtensions = [];
this.resolveExtensionsManager();
this.resolveBatchManager();
}
_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1___default()(NativeExtManager, [{
key: "isSystemExtension",
value: function isSystemExtension(extension) {
return this.systemExtensions.includes(extension.uuid);
}
}, {
key: "resolveExtensionsManager",
value: function resolveExtensionsManager() {
var _this = this;
var contentTypePredicate = new snjs__WEBPACK_IMPORTED_MODULE_3__["SFPredicate"]("content_type", "=", "SN|Component");
var packagePredicate = new snjs__WEBPACK_IMPORTED_MODULE_3__["SFPredicate"]("package_info.identifier", "=", this.extManagerId);
this.singletonManager.registerSingleton([contentTypePredicate, packagePredicate], function (resolvedSingleton) {
// Resolved Singleton
_this.systemExtensions.push(resolvedSingleton.uuid);
var needsSync = false;
if (Object(_utils__WEBPACK_IMPORTED_MODULE_2__["isDesktopApplication"])()) {
if (!resolvedSingleton.local_url) {
resolvedSingleton.local_url = window._extensions_manager_location;
needsSync = true;
}
} else {
if (!resolvedSingleton.hosted_url) {
resolvedSingleton.hosted_url = window._extensions_manager_location;
needsSync = true;
}
} // Handle addition of SN|ExtensionRepo permission
var permission = resolvedSingleton.content.permissions.find(function (p) {
return p.name == "stream-items";
});
if (!permission.content_types.includes("SN|ExtensionRepo")) {
permission.content_types.push("SN|ExtensionRepo");
needsSync = true;
}
if (needsSync) {
_this.modelManager.setItemDirty(resolvedSingleton, true);
_this.syncManager.sync();
}
}, function (valueCallback) {
// Safe to create. Create and return object.
var url = window._extensions_manager_location;
if (!url) {
console.error("window._extensions_manager_location must be set.");
return;
}
var packageInfo = {
name: "Extensions",
identifier: _this.extManagerId
};
var item = {
content_type: "SN|Component",
content: {
name: packageInfo.name,
area: "rooms",
package_info: packageInfo,
permissions: [{
name: "stream-items",
content_types: ["SN|Component", "SN|Theme", "SF|Extension", "Extension", "SF|MFA", "SN|Editor", "SN|ExtensionRepo"]
}]
}
};
if (Object(_utils__WEBPACK_IMPORTED_MODULE_2__["isDesktopApplication"])()) {
item.content.local_url = window._extensions_manager_location;
} else {
item.content.hosted_url = window._extensions_manager_location;
}
var component = _this.modelManager.createItem(item);
_this.modelManager.addItem(component);
_this.modelManager.setItemDirty(component, true);
_this.syncManager.sync();
_this.systemExtensions.push(component.uuid);
valueCallback(component);
});
}
}, {
key: "resolveBatchManager",
value: function resolveBatchManager() {
var _this2 = this;
var contentTypePredicate = new snjs__WEBPACK_IMPORTED_MODULE_3__["SFPredicate"]("content_type", "=", "SN|Component");
var packagePredicate = new snjs__WEBPACK_IMPORTED_MODULE_3__["SFPredicate"]("package_info.identifier", "=", this.batchManagerId);
this.singletonManager.registerSingleton([contentTypePredicate, packagePredicate], function (resolvedSingleton) {
// Resolved Singleton
_this2.systemExtensions.push(resolvedSingleton.uuid);
var needsSync = false;
if (Object(_utils__WEBPACK_IMPORTED_MODULE_2__["isDesktopApplication"])()) {
if (!resolvedSingleton.local_url) {
resolvedSingleton.local_url = window._batch_manager_location;
needsSync = true;
}
} else {
if (!resolvedSingleton.hosted_url) {
resolvedSingleton.hosted_url = window._batch_manager_location;
needsSync = true;
}
}
if (needsSync) {
_this2.modelManager.setItemDirty(resolvedSingleton, true);
_this2.syncManager.sync();
}
}, function (valueCallback) {
// Safe to create. Create and return object.
var url = window._batch_manager_location;
if (!url) {
console.error("window._batch_manager_location must be set.");
return;
}
var packageInfo = {
name: "Batch Manager",
identifier: _this2.batchManagerId
};
var item = {
content_type: "SN|Component",
content: {
name: packageInfo.name,
area: "modal",
package_info: packageInfo,
permissions: [{
name: "stream-items",
content_types: ["Note", "Tag", "SN|SmartTag", "SN|Component", "SN|Theme", "SN|UserPreferences", "SF|Extension", "Extension", "SF|MFA", "SN|Editor", "SN|FileSafe|Credentials", "SN|FileSafe|FileMetadata", "SN|FileSafe|Integration"]
}]
}
};
if (Object(_utils__WEBPACK_IMPORTED_MODULE_2__["isDesktopApplication"])()) {
item.content.local_url = window._batch_manager_location;
} else {
item.content.hosted_url = window._batch_manager_location;
}
var component = _this2.modelManager.createItem(item);
_this2.modelManager.addItem(component);
_this2.modelManager.setItemDirty(component, true);
_this2.syncManager.sync();
_this2.systemExtensions.push(component.uuid);
valueCallback(component);
});
}
}]);
return NativeExtManager;
}();
/***/ }),
/***/ "./app/assets/javascripts/services/preferencesManager.js":
/*!***************************************************************!*\
!*** ./app/assets/javascripts/services/preferencesManager.js ***!
\***************************************************************/
/*! exports provided: PREF_TAGS_PANEL_WIDTH, PREF_NOTES_PANEL_WIDTH, PREF_EDITOR_WIDTH, PREF_EDITOR_LEFT, PREF_EDITOR_MONOSPACE_ENABLED, PREF_EDITOR_SPELLCHECK, PREF_EDITOR_RESIZERS_ENABLED, PREF_SORT_NOTES_BY, PREF_SORT_NOTES_REVERSE, PREF_NOTES_SHOW_ARCHIVED, PREF_NOTES_HIDE_PINNED, PREF_NOTES_HIDE_NOTE_PREVIEW, PREF_NOTES_HIDE_DATE, PREF_NOTES_HIDE_TAGS, PreferencesManager */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PREF_TAGS_PANEL_WIDTH", function() { return PREF_TAGS_PANEL_WIDTH; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PREF_NOTES_PANEL_WIDTH", function() { return PREF_NOTES_PANEL_WIDTH; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PREF_EDITOR_WIDTH", function() { return PREF_EDITOR_WIDTH; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PREF_EDITOR_LEFT", function() { return PREF_EDITOR_LEFT; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PREF_EDITOR_MONOSPACE_ENABLED", function() { return PREF_EDITOR_MONOSPACE_ENABLED; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PREF_EDITOR_SPELLCHECK", function() { return PREF_EDITOR_SPELLCHECK; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PREF_EDITOR_RESIZERS_ENABLED", function() { return PREF_EDITOR_RESIZERS_ENABLED; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PREF_SORT_NOTES_BY", function() { return PREF_SORT_NOTES_BY; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PREF_SORT_NOTES_REVERSE", function() { return PREF_SORT_NOTES_REVERSE; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PREF_NOTES_SHOW_ARCHIVED", function() { return PREF_NOTES_SHOW_ARCHIVED; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PREF_NOTES_HIDE_PINNED", function() { return PREF_NOTES_HIDE_PINNED; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PREF_NOTES_HIDE_NOTE_PREVIEW", function() { return PREF_NOTES_HIDE_NOTE_PREVIEW; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PREF_NOTES_HIDE_DATE", function() { return PREF_NOTES_HIDE_DATE; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PREF_NOTES_HIDE_TAGS", function() { return PREF_NOTES_HIDE_TAGS; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PreferencesManager", function() { return PreferencesManager; });
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "./node_modules/@babel/runtime/helpers/classCallCheck.js");
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/helpers/createClass */ "./node_modules/@babel/runtime/helpers/createClass.js");
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var snjs__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! snjs */ "../snjs/dist/snjs.js");
/* harmony import */ var snjs__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(snjs__WEBPACK_IMPORTED_MODULE_2__);
var PREF_TAGS_PANEL_WIDTH = 'tagsPanelWidth';
var PREF_NOTES_PANEL_WIDTH = 'notesPanelWidth';
var PREF_EDITOR_WIDTH = 'editorWidth';
var PREF_EDITOR_LEFT = 'editorLeft';
var PREF_EDITOR_MONOSPACE_ENABLED = 'monospaceFont';
var PREF_EDITOR_SPELLCHECK = 'spellcheck';
var PREF_EDITOR_RESIZERS_ENABLED = 'marginResizersEnabled';
var PREF_SORT_NOTES_BY = 'sortBy';
var PREF_SORT_NOTES_REVERSE = 'sortReverse';
var PREF_NOTES_SHOW_ARCHIVED = 'showArchived';
var PREF_NOTES_HIDE_PINNED = 'hidePinned';
var PREF_NOTES_HIDE_NOTE_PREVIEW = 'hideNotePreview';
var PREF_NOTES_HIDE_DATE = 'hideDate';
var PREF_NOTES_HIDE_TAGS = 'hideTags';
var PreferencesManager =
/*#__PURE__*/
function () {
PreferencesManager.$inject = ["modelManager", "singletonManager", "appState", "syncManager"];
/* @ngInject */
function PreferencesManager(modelManager, singletonManager, appState, syncManager) {
var _this = this;
_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0___default()(this, PreferencesManager);
this.singletonManager = singletonManager;
this.modelManager = modelManager;
this.syncManager = syncManager;
this.appState = appState;
this.modelManager.addItemSyncObserver('user-prefs', 'SN|UserPreferences', function (allItems, validItems, deletedItems, source, sourceKey) {
_this.preferencesDidChange();
});
}
_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1___default()(PreferencesManager, [{
key: "load",
value: function load() {
var _this2 = this;
var prefsContentType = 'SN|UserPreferences';
var contentTypePredicate = new snjs__WEBPACK_IMPORTED_MODULE_2__["SFPredicate"]('content_type', '=', prefsContentType);
this.singletonManager.registerSingleton([contentTypePredicate], function (resolvedSingleton) {
_this2.userPreferences = resolvedSingleton;
}, function (valueCallback) {
// Safe to create. Create and return object.
var prefs = new snjs__WEBPACK_IMPORTED_MODULE_2__["SFItem"]({
content_type: prefsContentType
});
_this2.modelManager.addItem(prefs);
_this2.modelManager.setItemDirty(prefs);
_this2.syncManager.sync();
valueCallback(prefs);
});
}
}, {
key: "preferencesDidChange",
value: function preferencesDidChange() {
this.appState.setUserPreferences(this.userPreferences);
}
}, {
key: "syncUserPreferences",
value: function syncUserPreferences() {
if (this.userPreferences) {
this.modelManager.setItemDirty(this.userPreferences);
this.syncManager.sync();
}
}
}, {
key: "getValue",
value: function getValue(key, defaultValue) {
if (!this.userPreferences) {
return defaultValue;
}
var value = this.userPreferences.getAppDataItem(key);
return value !== undefined && value != null ? value : defaultValue;
}
}, {
key: "setUserPrefValue",
value: function setUserPrefValue(key, value, sync) {
this.userPreferences.setAppDataItem(key, value);
if (sync) {
this.syncUserPreferences();
}
}
}]);
return PreferencesManager;
}();
/***/ }),
/***/ "./app/assets/javascripts/services/privilegesManager.js":
/*!**************************************************************!*\
!*** ./app/assets/javascripts/services/privilegesManager.js ***!
\**************************************************************/
/*! exports provided: PrivilegesManager */
/***/ (function(module, exports) {
throw new Error("Module build failed (from ./node_modules/babel-loader/lib/index.js):\nError: ENOENT: no such file or directory, open '/Users/mo/Desktop/sn/dev/web/app/assets/javascripts/services/privilegesManager.js'");
/***/ }),
/***/ "./app/assets/javascripts/services/sessionHistory.js":
/*!***********************************************************!*\
!*** ./app/assets/javascripts/services/sessionHistory.js ***!
\***********************************************************/
/*! exports provided: SessionHistory */
/***/ (function(module, exports) {
throw new Error("Module build failed (from ./node_modules/babel-loader/lib/index.js):\nError: ENOENT: no such file or directory, open '/Users/mo/Desktop/sn/dev/web/app/assets/javascripts/services/sessionHistory.js'");
/***/ }),
/***/ "./app/assets/javascripts/services/singletonManager.js":
/*!*************************************************************!*\
!*** ./app/assets/javascripts/services/singletonManager.js ***!
\*************************************************************/
/*! exports provided: SingletonManager */
/***/ (function(module, exports) {
throw new Error("Module build failed (from ./node_modules/babel-loader/lib/index.js):\nError: ENOENT: no such file or directory, open '/Users/mo/Desktop/sn/dev/web/app/assets/javascripts/services/singletonManager.js'");
/***/ }),
/***/ "./app/assets/javascripts/services/statusManager.js":
/*!**********************************************************!*\
!*** ./app/assets/javascripts/services/statusManager.js ***!
\**********************************************************/
/*! exports provided: StatusManager */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "StatusManager", function() { return StatusManager; });
/* harmony import */ var _babel_runtime_helpers_typeof__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/helpers/typeof */ "./node_modules/@babel/runtime/helpers/typeof.js");
/* harmony import */ var _babel_runtime_helpers_typeof__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_typeof__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "./node_modules/@babel/runtime/helpers/classCallCheck.js");
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @babel/runtime/helpers/createClass */ "./node_modules/@babel/runtime/helpers/createClass.js");
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! lodash */ "./node_modules/lodash/lodash.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(lodash__WEBPACK_IMPORTED_MODULE_3__);
var StatusManager =
/*#__PURE__*/
function () {
function StatusManager() {
_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_1___default()(this, StatusManager);
this.statuses = [];
this.observers = [];
}
_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_2___default()(StatusManager, [{
key: "statusFromString",
value: function statusFromString(string) {
return {
string: string
};
}
}, {
key: "replaceStatusWithString",
value: function replaceStatusWithString(status, string) {
this.removeStatus(status);
return this.addStatusFromString(string);
}
}, {
key: "addStatusFromString",
value: function addStatusFromString(string) {
return this.addStatus(this.statusFromString(string));
}
}, {
key: "addStatus",
value: function addStatus(status) {
if (_babel_runtime_helpers_typeof__WEBPACK_IMPORTED_MODULE_0___default()(status) !== "object") {
console.error("Attempting to set non-object status", status);
return;
}
this.statuses.push(status);
this.notifyObservers();
return status;
}
}, {
key: "removeStatus",
value: function removeStatus(status) {
lodash__WEBPACK_IMPORTED_MODULE_3___default.a.pull(this.statuses, status);
this.notifyObservers();
return null;
}
}, {
key: "getStatusString",
value: function getStatusString() {
var result = "";
this.statuses.forEach(function (status, index) {
if (index > 0) {
result += " ";
}
result += status.string;
});
return result;
}
}, {
key: "notifyObservers",
value: function notifyObservers() {
var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = undefined;
try {
for (var _iterator = this.observers[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
var observer = _step.value;
observer(this.getStatusString());
}
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
} finally {
try {
if (!_iteratorNormalCompletion && _iterator.return != null) {
_iterator.return();
}
} finally {
if (_didIteratorError) {
throw _iteratorError;
}
}
}
}
}, {
key: "addStatusObserver",
value: function addStatusObserver(callback) {
this.observers.push(callback);
}
}, {
key: "removeStatusObserver",
value: function removeStatusObserver(callback) {
lodash__WEBPACK_IMPORTED_MODULE_3___default.a.pull(this.statuses, callback);
}
}]);
return StatusManager;
}();
/***/ }),
/***/ "./app/assets/javascripts/services/storageManager.js":
/*!***********************************************************!*\
!*** ./app/assets/javascripts/services/storageManager.js ***!
\***********************************************************/
/*! exports provided: MemoryStorage, StorageManager */
/***/ (function(module, exports) {
throw new Error("Module build failed (from ./node_modules/babel-loader/lib/index.js):\nError: ENOENT: no such file or directory, open '/Users/mo/Desktop/sn/dev/web/app/assets/javascripts/services/storageManager.js'");
/***/ }),
/***/ "./app/assets/javascripts/services/syncManager.js":
/*!********************************************************!*\
!*** ./app/assets/javascripts/services/syncManager.js ***!
\********************************************************/
/*! exports provided: SyncManager */
/***/ (function(module, exports) {
throw new Error("Module build failed (from ./node_modules/babel-loader/lib/index.js):\nError: ENOENT: no such file or directory, open '/Users/mo/Desktop/sn/dev/web/app/assets/javascripts/services/syncManager.js'");
/***/ }),
/***/ "./app/assets/javascripts/services/themeManager.js":
/*!*********************************************************!*\
!*** ./app/assets/javascripts/services/themeManager.js ***!
\*********************************************************/
/*! exports provided: ThemeManager */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ThemeManager", function() { return ThemeManager; });
/* harmony import */ var _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/regenerator */ "./node_modules/@babel/runtime/regenerator/index.js");
/* harmony import */ var _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/helpers/asyncToGenerator */ "./node_modules/@babel/runtime/helpers/asyncToGenerator.js");
/* harmony import */ var _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "./node_modules/@babel/runtime/helpers/classCallCheck.js");
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @babel/runtime/helpers/createClass */ "./node_modules/@babel/runtime/helpers/createClass.js");
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! lodash */ "./node_modules/lodash/lodash.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(lodash__WEBPACK_IMPORTED_MODULE_4__);
/* harmony import */ var angular__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! angular */ "./node_modules/angular/index.js");
/* harmony import */ var angular__WEBPACK_IMPORTED_MODULE_5___default = /*#__PURE__*/__webpack_require__.n(angular__WEBPACK_IMPORTED_MODULE_5__);
/* harmony import */ var snjs__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! snjs */ "../snjs/dist/snjs.js");
/* harmony import */ var snjs__WEBPACK_IMPORTED_MODULE_6___default = /*#__PURE__*/__webpack_require__.n(snjs__WEBPACK_IMPORTED_MODULE_6__);
/* harmony import */ var _storageManager__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./storageManager */ "./app/assets/javascripts/services/storageManager.js");
/* harmony import */ var _state__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! @/state */ "./app/assets/javascripts/state.js");
var ThemeManager =
/*#__PURE__*/
function () {
ThemeManager.$inject = ["componentManager", "desktopManager", "storageManager", "lockManager", "appState"];
/* @ngInject */
function ThemeManager(componentManager, desktopManager, storageManager, lockManager, appState) {
var _this = this;
_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2___default()(this, ThemeManager);
this.componentManager = componentManager;
this.storageManager = storageManager;
this.desktopManager = desktopManager;
this.activeThemes = [];
ThemeManager.CachedThemesKey = "cachedThemes";
this.registerObservers();
if (desktopManager.isDesktop) {
appState.addObserver(function (eventName, data) {
if (eventName === _state__WEBPACK_IMPORTED_MODULE_8__["APP_STATE_EVENT_DESKTOP_EXTS_READY"]) {
_this.activateCachedThemes();
}
});
} else {
this.activateCachedThemes();
}
}
_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3___default()(ThemeManager, [{
key: "activateCachedThemes",
value: function activateCachedThemes() {
var cachedThemes = this.getCachedThemes();
var writeToCache = false;
var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = undefined;
try {
for (var _iterator = cachedThemes[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
var theme = _step.value;
this.activateTheme(theme, writeToCache);
}
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
} finally {
try {
if (!_iteratorNormalCompletion && _iterator.return != null) {
_iterator.return();
}
} finally {
if (_didIteratorError) {
throw _iteratorError;
}
}
}
}
}, {
key: "registerObservers",
value: function registerObservers() {
var _this2 = this;
this.desktopManager.registerUpdateObserver(function (component) {
// Reload theme if active
if (component.active && component.isTheme()) {
_this2.deactivateTheme(component);
setTimeout(function () {
_this2.activateTheme(component);
}, 10);
}
});
this.componentManager.registerHandler({
identifier: "themeManager",
areas: ["themes"],
activationHandler: function activationHandler(component) {
if (component.active) {
_this2.activateTheme(component);
} else {
_this2.deactivateTheme(component);
}
}
});
}
}, {
key: "hasActiveTheme",
value: function hasActiveTheme() {
return this.componentManager.getActiveThemes().length > 0;
}
}, {
key: "deactivateAllThemes",
value: function deactivateAllThemes() {
var activeThemes = this.componentManager.getActiveThemes();
var _iteratorNormalCompletion2 = true;
var _didIteratorError2 = false;
var _iteratorError2 = undefined;
try {
for (var _iterator2 = activeThemes[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
var theme = _step2.value;
if (theme) {
this.componentManager.deactivateComponent(theme);
}
}
} catch (err) {
_didIteratorError2 = true;
_iteratorError2 = err;
} finally {
try {
if (!_iteratorNormalCompletion2 && _iterator2.return != null) {
_iterator2.return();
}
} finally {
if (_didIteratorError2) {
throw _iteratorError2;
}
}
}
this.decacheThemes();
}
}, {
key: "activateTheme",
value: function activateTheme(theme) {
var writeToCache = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
if (lodash__WEBPACK_IMPORTED_MODULE_4___default.a.find(this.activeThemes, {
uuid: theme.uuid
})) {
return;
}
this.activeThemes.push(theme);
var url = this.componentManager.urlForComponent(theme);
var link = document.createElement("link");
link.href = url;
link.type = "text/css";
link.rel = "stylesheet";
link.media = "screen,print";
link.id = theme.uuid;
document.getElementsByTagName("head")[0].appendChild(link);
if (writeToCache) {
this.cacheThemes();
}
}
}, {
key: "deactivateTheme",
value: function deactivateTheme(theme) {
var element = document.getElementById(theme.uuid);
if (element) {
element.disabled = true;
element.parentNode.removeChild(element);
}
lodash__WEBPACK_IMPORTED_MODULE_4___default.a.remove(this.activeThemes, {
uuid: theme.uuid
});
this.cacheThemes();
}
}, {
key: "cacheThemes",
value: function () {
var _cacheThemes = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee2() {
var mapped, data;
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee2$(_context2) {
while (1) {
switch (_context2.prev = _context2.next) {
case 0:
_context2.next = 2;
return Promise.all(this.activeThemes.map(
/*#__PURE__*/
function () {
var _ref = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee(theme) {
var transformer, params;
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
transformer = new snjs__WEBPACK_IMPORTED_MODULE_6__["SFItemParams"](theme);
_context.next = 3;
return transformer.paramsForLocalStorage();
case 3:
params = _context.sent;
return _context.abrupt("return", params);
case 5:
case "end":
return _context.stop();
}
}
}, _callee);
}));
return function (_x) {
return _ref.apply(this, arguments);
};
}()));
case 2:
mapped = _context2.sent;
data = JSON.stringify(mapped);
return _context2.abrupt("return", this.storageManager.setItem(ThemeManager.CachedThemesKey, data, _storageManager__WEBPACK_IMPORTED_MODULE_7__["StorageManager"].Fixed));
case 5:
case "end":
return _context2.stop();
}
}
}, _callee2, this);
}));
function cacheThemes() {
return _cacheThemes.apply(this, arguments);
}
return cacheThemes;
}()
}, {
key: "decacheThemes",
value: function () {
var _decacheThemes = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee3() {
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee3$(_context3) {
while (1) {
switch (_context3.prev = _context3.next) {
case 0:
return _context3.abrupt("return", this.storageManager.removeItem(ThemeManager.CachedThemesKey, _storageManager__WEBPACK_IMPORTED_MODULE_7__["StorageManager"].Fixed));
case 1:
case "end":
return _context3.stop();
}
}
}, _callee3, this);
}));
function decacheThemes() {
return _decacheThemes.apply(this, arguments);
}
return decacheThemes;
}()
}, {
key: "getCachedThemes",
value: function getCachedThemes() {
var cachedThemes = this.storageManager.getItemSync(ThemeManager.CachedThemesKey, _storageManager__WEBPACK_IMPORTED_MODULE_7__["StorageManager"].Fixed);
if (cachedThemes) {
var parsed = JSON.parse(cachedThemes);
return parsed.map(function (theme) {
return new snjs__WEBPACK_IMPORTED_MODULE_6__["SNTheme"](theme);
});
} else {
return [];
}
}
}]);
return ThemeManager;
}();
/***/ }),
/***/ "./app/assets/javascripts/state.js":
/*!*****************************************!*\
!*** ./app/assets/javascripts/state.js ***!
\*****************************************/
/*! exports provided: APP_STATE_EVENT_TAG_CHANGED, APP_STATE_EVENT_NOTE_CHANGED, APP_STATE_EVENT_PREFERENCES_CHANGED, APP_STATE_EVENT_PANEL_RESIZED, APP_STATE_EVENT_EDITOR_FOCUSED, APP_STATE_EVENT_BEGAN_BACKUP_DOWNLOAD, APP_STATE_EVENT_ENDED_BACKUP_DOWNLOAD, APP_STATE_EVENT_DESKTOP_EXTS_READY, APP_STATE_EVENT_WINDOW_DID_FOCUS, APP_STATE_EVENT_WINDOW_DID_BLUR, EVENT_SOURCE_USER_INTERACTION, EVENT_SOURCE_SCRIPT, AppState */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "APP_STATE_EVENT_TAG_CHANGED", function() { return APP_STATE_EVENT_TAG_CHANGED; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "APP_STATE_EVENT_NOTE_CHANGED", function() { return APP_STATE_EVENT_NOTE_CHANGED; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "APP_STATE_EVENT_PREFERENCES_CHANGED", function() { return APP_STATE_EVENT_PREFERENCES_CHANGED; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "APP_STATE_EVENT_PANEL_RESIZED", function() { return APP_STATE_EVENT_PANEL_RESIZED; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "APP_STATE_EVENT_EDITOR_FOCUSED", function() { return APP_STATE_EVENT_EDITOR_FOCUSED; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "APP_STATE_EVENT_BEGAN_BACKUP_DOWNLOAD", function() { return APP_STATE_EVENT_BEGAN_BACKUP_DOWNLOAD; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "APP_STATE_EVENT_ENDED_BACKUP_DOWNLOAD", function() { return APP_STATE_EVENT_ENDED_BACKUP_DOWNLOAD; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "APP_STATE_EVENT_DESKTOP_EXTS_READY", function() { return APP_STATE_EVENT_DESKTOP_EXTS_READY; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "APP_STATE_EVENT_WINDOW_DID_FOCUS", function() { return APP_STATE_EVENT_WINDOW_DID_FOCUS; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "APP_STATE_EVENT_WINDOW_DID_BLUR", function() { return APP_STATE_EVENT_WINDOW_DID_BLUR; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "EVENT_SOURCE_USER_INTERACTION", function() { return EVENT_SOURCE_USER_INTERACTION; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "EVENT_SOURCE_SCRIPT", function() { return EVENT_SOURCE_SCRIPT; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AppState", function() { return AppState; });
/* harmony import */ var _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/regenerator */ "./node_modules/@babel/runtime/regenerator/index.js");
/* harmony import */ var _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/helpers/asyncToGenerator */ "./node_modules/@babel/runtime/helpers/asyncToGenerator.js");
/* harmony import */ var _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "./node_modules/@babel/runtime/helpers/classCallCheck.js");
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @babel/runtime/helpers/createClass */ "./node_modules/@babel/runtime/helpers/createClass.js");
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var _services_privilegesManager__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @/services/privilegesManager */ "./app/assets/javascripts/services/privilegesManager.js");
/* harmony import */ var _utils__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! @/utils */ "./app/assets/javascripts/utils.js");
/* harmony import */ var lodash_pull__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! lodash/pull */ "./node_modules/lodash/pull.js");
/* harmony import */ var lodash_pull__WEBPACK_IMPORTED_MODULE_6___default = /*#__PURE__*/__webpack_require__.n(lodash_pull__WEBPACK_IMPORTED_MODULE_6__);
var APP_STATE_EVENT_TAG_CHANGED = 1;
var APP_STATE_EVENT_NOTE_CHANGED = 2;
var APP_STATE_EVENT_PREFERENCES_CHANGED = 3;
var APP_STATE_EVENT_PANEL_RESIZED = 4;
var APP_STATE_EVENT_EDITOR_FOCUSED = 5;
var APP_STATE_EVENT_BEGAN_BACKUP_DOWNLOAD = 6;
var APP_STATE_EVENT_ENDED_BACKUP_DOWNLOAD = 7;
var APP_STATE_EVENT_DESKTOP_EXTS_READY = 8;
var APP_STATE_EVENT_WINDOW_DID_FOCUS = 9;
var APP_STATE_EVENT_WINDOW_DID_BLUR = 10;
var EVENT_SOURCE_USER_INTERACTION = 1;
var EVENT_SOURCE_SCRIPT = 2;
var AppState =
/*#__PURE__*/
function () {
AppState.$inject = ["$timeout", "$rootScope", "privilegesManager"];
/* @ngInject */
function AppState($timeout, $rootScope, privilegesManager) {
_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2___default()(this, AppState);
this.$timeout = $timeout;
this.$rootScope = $rootScope;
this.privilegesManager = privilegesManager;
this.observers = [];
this.registerVisibilityObservers();
}
_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3___default()(AppState, [{
key: "registerVisibilityObservers",
value: function registerVisibilityObservers() {
var _this = this;
if (Object(_utils__WEBPACK_IMPORTED_MODULE_5__["isDesktopApplication"])()) {
this.$rootScope.$on('window-lost-focus', function () {
_this.notifyEvent(APP_STATE_EVENT_WINDOW_DID_BLUR);
});
this.$rootScope.$on('window-gained-focus', function () {
_this.notifyEvent(APP_STATE_EVENT_WINDOW_DID_FOCUS);
});
} else {
/* Tab visibility listener, web only */
document.addEventListener('visibilitychange', function (e) {
var visible = document.visibilityState === "visible";
var event = visible ? APP_STATE_EVENT_WINDOW_DID_FOCUS : APP_STATE_EVENT_WINDOW_DID_BLUR;
_this.notifyEvent(event);
});
}
}
/** @returns A function that unregisters this observer */
}, {
key: "addObserver",
value: function addObserver(callback) {
var _this2 = this;
this.observers.push(callback);
return function () {
lodash_pull__WEBPACK_IMPORTED_MODULE_6___default()(_this2.observers, callback);
};
}
}, {
key: "notifyEvent",
value: function () {
var _notifyEvent = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee2(eventName, data) {
var _this3 = this;
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee2$(_context2) {
while (1) {
switch (_context2.prev = _context2.next) {
case 0:
return _context2.abrupt("return", new Promise(function (resolve) {
_this3.$timeout(
/*#__PURE__*/
_babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee() {
var _iteratorNormalCompletion, _didIteratorError, _iteratorError, _iterator, _step, callback;
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
_iteratorNormalCompletion = true;
_didIteratorError = false;
_iteratorError = undefined;
_context.prev = 3;
_iterator = _this3.observers[Symbol.iterator]();
case 5:
if (_iteratorNormalCompletion = (_step = _iterator.next()).done) {
_context.next = 12;
break;
}
callback = _step.value;
_context.next = 9;
return callback(eventName, data);
case 9:
_iteratorNormalCompletion = true;
_context.next = 5;
break;
case 12:
_context.next = 18;
break;
case 14:
_context.prev = 14;
_context.t0 = _context["catch"](3);
_didIteratorError = true;
_iteratorError = _context.t0;
case 18:
_context.prev = 18;
_context.prev = 19;
if (!_iteratorNormalCompletion && _iterator.return != null) {
_iterator.return();
}
case 21:
_context.prev = 21;
if (!_didIteratorError) {
_context.next = 24;
break;
}
throw _iteratorError;
case 24:
return _context.finish(21);
case 25:
return _context.finish(18);
case 26:
resolve();
case 27:
case "end":
return _context.stop();
}
}
}, _callee, null, [[3, 14, 18, 26], [19,, 21, 25]]);
})));
}));
case 1:
case "end":
return _context2.stop();
}
}
}, _callee2);
}));
function notifyEvent(_x, _x2) {
return _notifyEvent.apply(this, arguments);
}
return notifyEvent;
}()
}, {
key: "setSelectedTag",
value: function setSelectedTag(tag) {
if (this.selectedTag === tag) {
return;
}
var previousTag = this.selectedTag;
this.selectedTag = tag;
this.notifyEvent(APP_STATE_EVENT_TAG_CHANGED, {
previousTag: previousTag
});
}
}, {
key: "setSelectedNote",
value: function () {
var _setSelectedNote = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee4(note) {
var _this4 = this;
var run;
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee4$(_context4) {
while (1) {
switch (_context4.prev = _context4.next) {
case 0:
run =
/*#__PURE__*/
function () {
var _ref2 = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee3() {
var previousNote;
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee3$(_context3) {
while (1) {
switch (_context3.prev = _context3.next) {
case 0:
previousNote = _this4.selectedNote;
_this4.selectedNote = note;
_context3.next = 4;
return _this4.notifyEvent(APP_STATE_EVENT_NOTE_CHANGED, {
previousNote: previousNote
});
case 4:
case "end":
return _context3.stop();
}
}
}, _callee3);
}));
return function run() {
return _ref2.apply(this, arguments);
};
}();
_context4.t0 = note && note.content.protected;
if (!_context4.t0) {
_context4.next = 6;
break;
}
_context4.next = 5;
return this.privilegesManager.actionRequiresPrivilege(_services_privilegesManager__WEBPACK_IMPORTED_MODULE_4__["PrivilegesManager"].ActionViewProtectedNotes);
case 5:
_context4.t0 = _context4.sent;
case 6:
if (!_context4.t0) {
_context4.next = 10;
break;
}
this.godService.presentPrivilegesModal(_services_privilegesManager__WEBPACK_IMPORTED_MODULE_4__["PrivilegesManager"].ActionViewProtectedNotes, run);
_context4.next = 11;
break;
case 10:
run();
case 11:
case "end":
return _context4.stop();
}
}
}, _callee4, this);
}));
function setSelectedNote(_x3) {
return _setSelectedNote.apply(this, arguments);
}
return setSelectedNote;
}()
}, {
key: "getSelectedTag",
value: function getSelectedTag() {
return this.selectedTag;
}
}, {
key: "getSelectedNote",
value: function getSelectedNote() {
return this.selectedNote;
}
}, {
key: "setUserPreferences",
value: function setUserPreferences(preferences) {
this.userPreferences = preferences;
this.notifyEvent(APP_STATE_EVENT_PREFERENCES_CHANGED);
}
}, {
key: "panelDidResize",
value: function panelDidResize(_ref3) {
var name = _ref3.name,
collapsed = _ref3.collapsed;
this.notifyEvent(APP_STATE_EVENT_PANEL_RESIZED, {
panel: name,
collapsed: collapsed
});
}
}, {
key: "editorDidFocus",
value: function editorDidFocus(eventSource) {
this.notifyEvent(APP_STATE_EVENT_EDITOR_FOCUSED, {
eventSource: eventSource
});
}
}, {
key: "beganBackupDownload",
value: function beganBackupDownload() {
this.notifyEvent(APP_STATE_EVENT_BEGAN_BACKUP_DOWNLOAD);
}
}, {
key: "endedBackupDownload",
value: function endedBackupDownload(_ref4) {
var success = _ref4.success;
this.notifyEvent(APP_STATE_EVENT_ENDED_BACKUP_DOWNLOAD, {
success: success
});
}
/**
* When the desktop appplication extension server is ready.
*/
}, {
key: "desktopExtensionsReady",
value: function desktopExtensionsReady() {
this.notifyEvent(APP_STATE_EVENT_DESKTOP_EXTS_READY);
}
}]);
return AppState;
}();
/***/ }),
/***/ "./app/assets/javascripts/strings.js":
/*!*******************************************!*\
!*** ./app/assets/javascripts/strings.js ***!
\*******************************************/
/*! exports provided: STRING_SESSION_EXPIRED, STRING_DEFAULT_FILE_ERROR, STRING_GENERIC_SYNC_ERROR, StringSyncException, STRING_NEW_UPDATE_READY, STRING_DELETE_TAG, STRING_DELETED_NOTE, STRING_INVALID_NOTE, STRING_ELLIPSES, STRING_GENERIC_SAVE_ERROR, STRING_DELETE_PLACEHOLDER_ATTEMPT, STRING_DELETE_LOCKED_ATTEMPT, StringDeleteNote, StringEmptyTrash, STRING_ACCOUNT_MENU_UNCHECK_MERGE, STRING_SIGN_OUT_CONFIRMATION, STRING_ERROR_DECRYPTING_IMPORT, STRING_E2E_ENABLED, STRING_LOCAL_ENC_ENABLED, STRING_ENC_NOT_ENABLED, STRING_IMPORT_SUCCESS, STRING_REMOVE_PASSCODE_CONFIRMATION, STRING_REMOVE_PASSCODE_OFFLINE_ADDENDUM, STRING_NON_MATCHING_PASSCODES, STRING_NON_MATCHING_PASSWORDS, STRING_GENERATING_LOGIN_KEYS, STRING_GENERATING_REGISTER_KEYS, STRING_INVALID_IMPORT_FILE, StringImportError, STRING_FAILED_PASSWORD_CHANGE */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "STRING_SESSION_EXPIRED", function() { return STRING_SESSION_EXPIRED; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "STRING_DEFAULT_FILE_ERROR", function() { return STRING_DEFAULT_FILE_ERROR; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "STRING_GENERIC_SYNC_ERROR", function() { return STRING_GENERIC_SYNC_ERROR; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "StringSyncException", function() { return StringSyncException; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "STRING_NEW_UPDATE_READY", function() { return STRING_NEW_UPDATE_READY; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "STRING_DELETE_TAG", function() { return STRING_DELETE_TAG; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "STRING_DELETED_NOTE", function() { return STRING_DELETED_NOTE; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "STRING_INVALID_NOTE", function() { return STRING_INVALID_NOTE; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "STRING_ELLIPSES", function() { return STRING_ELLIPSES; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "STRING_GENERIC_SAVE_ERROR", function() { return STRING_GENERIC_SAVE_ERROR; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "STRING_DELETE_PLACEHOLDER_ATTEMPT", function() { return STRING_DELETE_PLACEHOLDER_ATTEMPT; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "STRING_DELETE_LOCKED_ATTEMPT", function() { return STRING_DELETE_LOCKED_ATTEMPT; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "StringDeleteNote", function() { return StringDeleteNote; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "StringEmptyTrash", function() { return StringEmptyTrash; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "STRING_ACCOUNT_MENU_UNCHECK_MERGE", function() { return STRING_ACCOUNT_MENU_UNCHECK_MERGE; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "STRING_SIGN_OUT_CONFIRMATION", function() { return STRING_SIGN_OUT_CONFIRMATION; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "STRING_ERROR_DECRYPTING_IMPORT", function() { return STRING_ERROR_DECRYPTING_IMPORT; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "STRING_E2E_ENABLED", function() { return STRING_E2E_ENABLED; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "STRING_LOCAL_ENC_ENABLED", function() { return STRING_LOCAL_ENC_ENABLED; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "STRING_ENC_NOT_ENABLED", function() { return STRING_ENC_NOT_ENABLED; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "STRING_IMPORT_SUCCESS", function() { return STRING_IMPORT_SUCCESS; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "STRING_REMOVE_PASSCODE_CONFIRMATION", function() { return STRING_REMOVE_PASSCODE_CONFIRMATION; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "STRING_REMOVE_PASSCODE_OFFLINE_ADDENDUM", function() { return STRING_REMOVE_PASSCODE_OFFLINE_ADDENDUM; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "STRING_NON_MATCHING_PASSCODES", function() { return STRING_NON_MATCHING_PASSCODES; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "STRING_NON_MATCHING_PASSWORDS", function() { return STRING_NON_MATCHING_PASSWORDS; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "STRING_GENERATING_LOGIN_KEYS", function() { return STRING_GENERATING_LOGIN_KEYS; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "STRING_GENERATING_REGISTER_KEYS", function() { return STRING_GENERATING_REGISTER_KEYS; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "STRING_INVALID_IMPORT_FILE", function() { return STRING_INVALID_IMPORT_FILE; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "StringImportError", function() { return StringImportError; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "STRING_FAILED_PASSWORD_CHANGE", function() { return STRING_FAILED_PASSWORD_CHANGE; });
/** @generic */
var STRING_SESSION_EXPIRED = "Your session has expired. New changes will not be pulled in. Please sign out and sign back in to refresh your session.";
var STRING_DEFAULT_FILE_ERROR = "Please use FileSafe or the Bold Editor to attach images and files. Learn more at standardnotes.org/filesafe.";
var STRING_GENERIC_SYNC_ERROR = "There was an error syncing. Please try again. If all else fails, try signing out and signing back in.";
function StringSyncException(data) {
return "There was an error while trying to save your items. Please contact support and share this message: ".concat(data, ".");
}
/** @footer */
var STRING_NEW_UPDATE_READY = "A new update is ready to install. Please use the top-level 'Updates' menu to manage installation.";
/** @tags */
var STRING_DELETE_TAG = "Are you sure you want to delete this tag? Note: deleting a tag will not delete its notes.";
/** @editor */
var STRING_DELETED_NOTE = "The note you are attempting to edit has been deleted, and is awaiting sync. Changes you make will be disregarded.";
var STRING_INVALID_NOTE = "The note you are attempting to save can not be found or has been deleted. Changes you make will not be synced. Please copy this note's text and start a new note.";
var STRING_ELLIPSES = "...";
var STRING_GENERIC_SAVE_ERROR = "There was an error saving your note. Please try again.";
var STRING_DELETE_PLACEHOLDER_ATTEMPT = "This note is a placeholder and cannot be deleted. To remove from your list, simply navigate to a different note.";
var STRING_DELETE_LOCKED_ATTEMPT = "This note is locked. If you'd like to delete it, unlock it, and try again.";
function StringDeleteNote(_ref) {
var title = _ref.title,
permanently = _ref.permanently;
return permanently ? "Are you sure you want to permanently delete ".concat(title, "?") : "Are you sure you want to move ".concat(title, " to the trash?");
}
function StringEmptyTrash(_ref2) {
var count = _ref2.count;
return "Are you sure you want to permanently delete ".concat(count, " note(s)?");
}
/** @account */
var STRING_ACCOUNT_MENU_UNCHECK_MERGE = "Unchecking this option means any of the notes you have written while you were signed out will be deleted. Are you sure you want to discard these notes?";
var STRING_SIGN_OUT_CONFIRMATION = "Are you sure you want to end your session? This will delete all local items and extensions.";
var STRING_ERROR_DECRYPTING_IMPORT = "There was an error decrypting your items. Make sure the password you entered is correct and try again.";
var STRING_E2E_ENABLED = "End-to-end encryption is enabled. Your data is encrypted on your device first, then synced to your private cloud.";
var STRING_LOCAL_ENC_ENABLED = "Encryption is enabled. Your data is encrypted using your passcode before it is saved to your device storage.";
var STRING_ENC_NOT_ENABLED = "Encryption is not enabled. Sign in, register, or add a passcode lock to enable encryption.";
var STRING_IMPORT_SUCCESS = "Your data has been successfully imported.";
var STRING_REMOVE_PASSCODE_CONFIRMATION = "Are you sure you want to remove your local passcode?";
var STRING_REMOVE_PASSCODE_OFFLINE_ADDENDUM = " This will remove encryption from your local data.";
var STRING_NON_MATCHING_PASSCODES = "The two passcodes you entered do not match. Please try again.";
var STRING_NON_MATCHING_PASSWORDS = "The two passwords you entered do not match. Please try again.";
var STRING_GENERATING_LOGIN_KEYS = "Generating Login Keys...";
var STRING_GENERATING_REGISTER_KEYS = "Generating Account Keys...";
var STRING_INVALID_IMPORT_FILE = "Unable to open file. Ensure it is a proper JSON file and try again.";
function StringImportError(_ref3) {
var errorCount = _ref3.errorCount;
return "Import complete. ".concat(errorCount, " items were not imported because there was an error decrypting them. Make sure the password is correct and try again.");
}
/** @password_change */
var STRING_FAILED_PASSWORD_CHANGE = "There was an error re-encrypting your items. Your password was changed, but not all your items were properly re-encrypted and synced. You should try syncing again. If all else fails, you should restore your notes from backup.";
/***/ }),
/***/ "./app/assets/javascripts/utils.js":
/*!*****************************************!*\
!*** ./app/assets/javascripts/utils.js ***!
\*****************************************/
/*! exports provided: getParameterByName, parametersFromURL, isNullOrUndefined, getPlatformString, dateToLocalizedString, debounce, isDesktopApplication */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getParameterByName", function() { return getParameterByName; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "parametersFromURL", function() { return parametersFromURL; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isNullOrUndefined", function() { return isNullOrUndefined; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getPlatformString", function() { return getPlatformString; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "dateToLocalizedString", function() { return dateToLocalizedString; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "debounce", function() { return debounce; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isDesktopApplication", function() { return isDesktopApplication; });
function getParameterByName(name, url) {
name = name.replace(/[[\]]/g, '\\$&');
var regex = new RegExp('[?&]' + name + '(=([^]*)|&|#|$)');
var results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, ' '));
}
function parametersFromURL(url) {
url = url.split('?').slice(-1)[0];
var obj = {};
url.replace(/([^=&]+)=([^&]*)/g, function (m, key, value) {
obj[decodeURIComponent(key)] = decodeURIComponent(value);
});
return obj;
}
function isNullOrUndefined(value) {
return value === null || value === undefined;
}
function getPlatformString() {
try {
var platform = navigator.platform.toLowerCase();
var trimmed = '';
if (platform.indexOf('mac') !== -1) {
trimmed = 'mac';
} else if (platform.indexOf('win') !== -1) {
trimmed = 'windows';
}
if (platform.indexOf('linux') !== -1) {
trimmed = 'linux';
}
return trimmed + (isDesktopApplication() ? '-desktop' : '-web');
} catch (e) {
return null;
}
}
var sharedDateFormatter;
function dateToLocalizedString(date) {
if (typeof Intl !== 'undefined' && Intl.DateTimeFormat) {
if (!sharedDateFormatter) {
var locale = navigator.languages && navigator.languages.length ? navigator.languages[0] : navigator.language;
sharedDateFormatter = new Intl.DateTimeFormat(locale, {
year: 'numeric',
month: 'numeric',
day: '2-digit',
hour: '2-digit',
minute: '2-digit'
});
}
return sharedDateFormatter.format(date);
} else {
// IE < 11, Safari <= 9.0.
// In English, this generates the string most similar to
// the toLocaleDateString() result above.
return date.toDateString() + ' ' + date.toLocaleTimeString();
}
}
/** Via https://davidwalsh.name/javascript-debounce-function */
function debounce(func, wait, immediate) {
var timeout;
return function () {
var context = this;
var args = arguments;
var later = function later() {
timeout = null;
if (!immediate) func.apply(context, args);
};
var callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) func.apply(context, args);
};
}
;
function isDesktopApplication() {
return window.isElectron;
}
/* Use with numbers and strings, not objects */
// eslint-disable-next-line no-extend-native
Array.prototype.containsPrimitiveSubset = function (array) {
var _this = this;
return !array.some(function (val) {
return _this.indexOf(val) === -1;
});
}; // https://tc39.github.io/ecma262/#sec-array.prototype.includes
if (!Array.prototype.includes) {
// eslint-disable-next-line no-extend-native
Object.defineProperty(Array.prototype, 'includes', {
value: function value(searchElement, fromIndex) {
if (this == null) {
throw new TypeError('"this" is null or not defined');
} // 1. Let O be ? ToObject(this value).
var o = Object(this); // 2. Let len be ? ToLength(? Get(O, "length")).
var len = o.length >>> 0; // 3. If len is 0, return false.
if (len === 0) {
return false;
} // 4. Let n be ? ToInteger(fromIndex).
// (If fromIndex is undefined, this step produces the value 0.)
var n = fromIndex | 0; // 5. If n ≥ 0, then
// a. Let k be n.
// 6. Else n < 0,
// a. Let k be len + n.
// b. If k < 0, let k be 0.
var k = Math.max(n >= 0 ? n : len - Math.abs(n), 0);
function sameValueZero(x, y) {
return x === y || typeof x === 'number' && typeof y === 'number' && isNaN(x) && isNaN(y);
} // 7. Repeat, while k < len
while (k < len) {
// a. Let elementK be the result of ? Get(O, ! ToString(k)).
// b. If SameValueZero(searchElement, elementK) is true, return true.
if (sameValueZero(o[k], searchElement)) {
return true;
} // c. Increase k by 1.
k++;
} // 8. Return false
return false;
}
});
}
/***/ }),
/***/ "./app/assets/stylesheets/index.css.scss":
/*!***********************************************!*\
!*** ./app/assets/stylesheets/index.css.scss ***!
\***********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
// extracted by mini-css-extract-plugin
/***/ }),
/***/ "./app/assets/templates/directives/account-menu.pug":
/*!**********************************************************!*\
!*** ./app/assets/templates/directives/account-menu.pug ***!
\**********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
var req = __webpack_require__(/*! !./node_modules/pug-loader!./app/assets/templates/directives/account-menu.pug */ "./node_modules/pug-loader/index.js!./app/assets/templates/directives/account-menu.pug");
module.exports = (req['default'] || req).apply(req, [])
/***/ }),
/***/ "./app/assets/templates/directives/actions-menu.pug":
/*!**********************************************************!*\
!*** ./app/assets/templates/directives/actions-menu.pug ***!
\**********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
var req = __webpack_require__(/*! !./node_modules/pug-loader!./app/assets/templates/directives/actions-menu.pug */ "./node_modules/pug-loader/index.js!./app/assets/templates/directives/actions-menu.pug");
module.exports = (req['default'] || req).apply(req, [])
/***/ }),
/***/ "./app/assets/templates/directives/component-modal.pug":
/*!*************************************************************!*\
!*** ./app/assets/templates/directives/component-modal.pug ***!
\*************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
var req = __webpack_require__(/*! !./node_modules/pug-loader!./app/assets/templates/directives/component-modal.pug */ "./node_modules/pug-loader/index.js!./app/assets/templates/directives/component-modal.pug");
module.exports = (req['default'] || req).apply(req, [])
/***/ }),
/***/ "./app/assets/templates/directives/component-view.pug":
/*!************************************************************!*\
!*** ./app/assets/templates/directives/component-view.pug ***!
\************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
var req = __webpack_require__(/*! !./node_modules/pug-loader!./app/assets/templates/directives/component-view.pug */ "./node_modules/pug-loader/index.js!./app/assets/templates/directives/component-view.pug");
module.exports = (req['default'] || req).apply(req, [])
/***/ }),
/***/ "./app/assets/templates/directives/conflict-resolution-modal.pug":
/*!***********************************************************************!*\
!*** ./app/assets/templates/directives/conflict-resolution-modal.pug ***!
\***********************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
var req = __webpack_require__(/*! !./node_modules/pug-loader!./app/assets/templates/directives/conflict-resolution-modal.pug */ "./node_modules/pug-loader/index.js!./app/assets/templates/directives/conflict-resolution-modal.pug");
module.exports = (req['default'] || req).apply(req, [])
/***/ }),
/***/ "./app/assets/templates/directives/editor-menu.pug":
/*!*********************************************************!*\
!*** ./app/assets/templates/directives/editor-menu.pug ***!
\*********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
var req = __webpack_require__(/*! !./node_modules/pug-loader!./app/assets/templates/directives/editor-menu.pug */ "./node_modules/pug-loader/index.js!./app/assets/templates/directives/editor-menu.pug");
module.exports = (req['default'] || req).apply(req, [])
/***/ }),
/***/ "./app/assets/templates/directives/input-modal.pug":
/*!*********************************************************!*\
!*** ./app/assets/templates/directives/input-modal.pug ***!
\*********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
var req = __webpack_require__(/*! !./node_modules/pug-loader!./app/assets/templates/directives/input-modal.pug */ "./node_modules/pug-loader/index.js!./app/assets/templates/directives/input-modal.pug");
module.exports = (req['default'] || req).apply(req, [])
/***/ }),
/***/ "./app/assets/templates/directives/menu-row.pug":
/*!******************************************************!*\
!*** ./app/assets/templates/directives/menu-row.pug ***!
\******************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
var req = __webpack_require__(/*! !./node_modules/pug-loader!./app/assets/templates/directives/menu-row.pug */ "./node_modules/pug-loader/index.js!./app/assets/templates/directives/menu-row.pug");
module.exports = (req['default'] || req).apply(req, [])
/***/ }),
/***/ "./app/assets/templates/directives/panel-resizer.pug":
/*!***********************************************************!*\
!*** ./app/assets/templates/directives/panel-resizer.pug ***!
\***********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
var req = __webpack_require__(/*! !./node_modules/pug-loader!./app/assets/templates/directives/panel-resizer.pug */ "./node_modules/pug-loader/index.js!./app/assets/templates/directives/panel-resizer.pug");
module.exports = (req['default'] || req).apply(req, [])
/***/ }),
/***/ "./app/assets/templates/directives/password-wizard.pug":
/*!*************************************************************!*\
!*** ./app/assets/templates/directives/password-wizard.pug ***!
\*************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
var req = __webpack_require__(/*! !./node_modules/pug-loader!./app/assets/templates/directives/password-wizard.pug */ "./node_modules/pug-loader/index.js!./app/assets/templates/directives/password-wizard.pug");
module.exports = (req['default'] || req).apply(req, [])
/***/ }),
/***/ "./app/assets/templates/directives/permissions-modal.pug":
/*!***************************************************************!*\
!*** ./app/assets/templates/directives/permissions-modal.pug ***!
\***************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
var req = __webpack_require__(/*! !./node_modules/pug-loader!./app/assets/templates/directives/permissions-modal.pug */ "./node_modules/pug-loader/index.js!./app/assets/templates/directives/permissions-modal.pug");
module.exports = (req['default'] || req).apply(req, [])
/***/ }),
/***/ "./app/assets/templates/directives/privileges-auth-modal.pug":
/*!*******************************************************************!*\
!*** ./app/assets/templates/directives/privileges-auth-modal.pug ***!
\*******************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
var req = __webpack_require__(/*! !./node_modules/pug-loader!./app/assets/templates/directives/privileges-auth-modal.pug */ "./node_modules/pug-loader/index.js!./app/assets/templates/directives/privileges-auth-modal.pug");
module.exports = (req['default'] || req).apply(req, [])
/***/ }),
/***/ "./app/assets/templates/directives/privileges-management-modal.pug":
/*!*************************************************************************!*\
!*** ./app/assets/templates/directives/privileges-management-modal.pug ***!
\*************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
var req = __webpack_require__(/*! !./node_modules/pug-loader!./app/assets/templates/directives/privileges-management-modal.pug */ "./node_modules/pug-loader/index.js!./app/assets/templates/directives/privileges-management-modal.pug");
module.exports = (req['default'] || req).apply(req, [])
/***/ }),
/***/ "./app/assets/templates/directives/revision-preview-modal.pug":
/*!********************************************************************!*\
!*** ./app/assets/templates/directives/revision-preview-modal.pug ***!
\********************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
var req = __webpack_require__(/*! !./node_modules/pug-loader!./app/assets/templates/directives/revision-preview-modal.pug */ "./node_modules/pug-loader/index.js!./app/assets/templates/directives/revision-preview-modal.pug");
module.exports = (req['default'] || req).apply(req, [])
/***/ }),
/***/ "./app/assets/templates/directives/session-history-menu.pug":
/*!******************************************************************!*\
!*** ./app/assets/templates/directives/session-history-menu.pug ***!
\******************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
var req = __webpack_require__(/*! !./node_modules/pug-loader!./app/assets/templates/directives/session-history-menu.pug */ "./node_modules/pug-loader/index.js!./app/assets/templates/directives/session-history-menu.pug");
module.exports = (req['default'] || req).apply(req, [])
/***/ }),
/***/ "./app/assets/templates/directives/sync-resolution-menu.pug":
/*!******************************************************************!*\
!*** ./app/assets/templates/directives/sync-resolution-menu.pug ***!
\******************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
var req = __webpack_require__(/*! !./node_modules/pug-loader!./app/assets/templates/directives/sync-resolution-menu.pug */ "./node_modules/pug-loader/index.js!./app/assets/templates/directives/sync-resolution-menu.pug");
module.exports = (req['default'] || req).apply(req, [])
/***/ }),
/***/ "./app/assets/templates/editor.pug":
/*!*****************************************!*\
!*** ./app/assets/templates/editor.pug ***!
\*****************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
var req = __webpack_require__(/*! !./node_modules/pug-loader!./app/assets/templates/editor.pug */ "./node_modules/pug-loader/index.js!./app/assets/templates/editor.pug");
module.exports = (req['default'] || req).apply(req, [])
/***/ }),
/***/ "./app/assets/templates/lock-screen.pug":
/*!**********************************************!*\
!*** ./app/assets/templates/lock-screen.pug ***!
\**********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
var req = __webpack_require__(/*! !./node_modules/pug-loader!./app/assets/templates/lock-screen.pug */ "./node_modules/pug-loader/index.js!./app/assets/templates/lock-screen.pug");
module.exports = (req['default'] || req).apply(req, [])
/***/ }),
/***/ "./app/assets/templates/notes.pug":
/*!****************************************!*\
!*** ./app/assets/templates/notes.pug ***!
\****************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
var req = __webpack_require__(/*! !./node_modules/pug-loader!./app/assets/templates/notes.pug */ "./node_modules/pug-loader/index.js!./app/assets/templates/notes.pug");
module.exports = (req['default'] || req).apply(req, [])
/***/ }),
/***/ "./app/assets/templates/root.pug":
/*!***************************************!*\
!*** ./app/assets/templates/root.pug ***!
\***************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
var req = __webpack_require__(/*! !./node_modules/pug-loader!./app/assets/templates/root.pug */ "./node_modules/pug-loader/index.js!./app/assets/templates/root.pug");
module.exports = (req['default'] || req).apply(req, [])
/***/ }),
/***/ "./app/assets/templates/tags.pug":
/*!***************************************!*\
!*** ./app/assets/templates/tags.pug ***!
\***************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
var req = __webpack_require__(/*! !./node_modules/pug-loader!./app/assets/templates/tags.pug */ "./node_modules/pug-loader/index.js!./app/assets/templates/tags.pug");
module.exports = (req['default'] || req).apply(req, [])
/***/ }),
/***/ "./node_modules/@babel/runtime/helpers/assertThisInitialized.js":
/*!**********************************************************************!*\
!*** ./node_modules/@babel/runtime/helpers/assertThisInitialized.js ***!
\**********************************************************************/
/*! no static exports found */
/***/ (function(module, exports) {
function _assertThisInitialized(self) {
if (self === void 0) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}
return self;
}
module.exports = _assertThisInitialized;
/***/ }),
/***/ "./node_modules/@babel/runtime/helpers/asyncToGenerator.js":
/*!*****************************************************************!*\
!*** ./node_modules/@babel/runtime/helpers/asyncToGenerator.js ***!
\*****************************************************************/
/*! no static exports found */
/***/ (function(module, exports) {
function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
try {
var info = gen[key](arg);
var value = info.value;
} catch (error) {
reject(error);
return;
}
if (info.done) {
resolve(value);
} else {
Promise.resolve(value).then(_next, _throw);
}
}
function _asyncToGenerator(fn) {
return function () {
var self = this,
args = arguments;
return new Promise(function (resolve, reject) {
var gen = fn.apply(self, args);
function _next(value) {
asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
}
function _throw(err) {
asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
}
_next(undefined);
});
};
}
module.exports = _asyncToGenerator;
/***/ }),
/***/ "./node_modules/@babel/runtime/helpers/classCallCheck.js":
/*!***************************************************************!*\
!*** ./node_modules/@babel/runtime/helpers/classCallCheck.js ***!
\***************************************************************/
/*! no static exports found */
/***/ (function(module, exports) {
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
module.exports = _classCallCheck;
/***/ }),
/***/ "./node_modules/@babel/runtime/helpers/createClass.js":
/*!************************************************************!*\
!*** ./node_modules/@babel/runtime/helpers/createClass.js ***!
\************************************************************/
/*! no static exports found */
/***/ (function(module, exports) {
function _defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
function _createClass(Constructor, protoProps, staticProps) {
if (protoProps) _defineProperties(Constructor.prototype, protoProps);
if (staticProps) _defineProperties(Constructor, staticProps);
return Constructor;
}
module.exports = _createClass;
/***/ }),
/***/ "./node_modules/@babel/runtime/helpers/defineProperty.js":
/*!***************************************************************!*\
!*** ./node_modules/@babel/runtime/helpers/defineProperty.js ***!
\***************************************************************/
/*! no static exports found */
/***/ (function(module, exports) {
function _defineProperty(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
module.exports = _defineProperty;
/***/ }),
/***/ "./node_modules/@babel/runtime/helpers/getPrototypeOf.js":
/*!***************************************************************!*\
!*** ./node_modules/@babel/runtime/helpers/getPrototypeOf.js ***!
\***************************************************************/
/*! no static exports found */
/***/ (function(module, exports) {
function _getPrototypeOf(o) {
module.exports = _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {
return o.__proto__ || Object.getPrototypeOf(o);
};
return _getPrototypeOf(o);
}
module.exports = _getPrototypeOf;
/***/ }),
/***/ "./node_modules/@babel/runtime/helpers/inherits.js":
/*!*********************************************************!*\
!*** ./node_modules/@babel/runtime/helpers/inherits.js ***!
\*********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
var setPrototypeOf = __webpack_require__(/*! ./setPrototypeOf */ "./node_modules/@babel/runtime/helpers/setPrototypeOf.js");
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function");
}
subClass.prototype = Object.create(superClass && superClass.prototype, {
constructor: {
value: subClass,
writable: true,
configurable: true
}
});
if (superClass) setPrototypeOf(subClass, superClass);
}
module.exports = _inherits;
/***/ }),
/***/ "./node_modules/@babel/runtime/helpers/possibleConstructorReturn.js":
/*!**************************************************************************!*\
!*** ./node_modules/@babel/runtime/helpers/possibleConstructorReturn.js ***!
\**************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
var _typeof = __webpack_require__(/*! ../helpers/typeof */ "./node_modules/@babel/runtime/helpers/typeof.js");
var assertThisInitialized = __webpack_require__(/*! ./assertThisInitialized */ "./node_modules/@babel/runtime/helpers/assertThisInitialized.js");
function _possibleConstructorReturn(self, call) {
if (call && (_typeof(call) === "object" || typeof call === "function")) {
return call;
}
return assertThisInitialized(self);
}
module.exports = _possibleConstructorReturn;
/***/ }),
/***/ "./node_modules/@babel/runtime/helpers/setPrototypeOf.js":
/*!***************************************************************!*\
!*** ./node_modules/@babel/runtime/helpers/setPrototypeOf.js ***!
\***************************************************************/
/*! no static exports found */
/***/ (function(module, exports) {
function _setPrototypeOf(o, p) {
module.exports = _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
o.__proto__ = p;
return o;
};
return _setPrototypeOf(o, p);
}
module.exports = _setPrototypeOf;
/***/ }),
/***/ "./node_modules/@babel/runtime/helpers/typeof.js":
/*!*******************************************************!*\
!*** ./node_modules/@babel/runtime/helpers/typeof.js ***!
\*******************************************************/
/*! no static exports found */
/***/ (function(module, exports) {
function _typeof(obj) {
"@babel/helpers - typeof";
if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
module.exports = _typeof = function _typeof(obj) {
return typeof obj;
};
} else {
module.exports = _typeof = function _typeof(obj) {
return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
};
}
return _typeof(obj);
}
module.exports = _typeof;
/***/ }),
/***/ "./node_modules/@babel/runtime/regenerator/index.js":
/*!**********************************************************!*\
!*** ./node_modules/@babel/runtime/regenerator/index.js ***!
\**********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__(/*! regenerator-runtime */ "./node_modules/regenerator-runtime/runtime.js");
/***/ }),
/***/ "./node_modules/angular/angular.js":
/*!*****************************************!*\
!*** ./node_modules/angular/angular.js ***!
\*****************************************/
/*! no static exports found */
/***/ (function(module, exports) {
/**
* @license AngularJS v1.7.9
* (c) 2010-2018 Google, Inc. http://angularjs.org
* License: MIT
*/
(function(window) {'use strict';
/* exported
minErrConfig,
errorHandlingConfig,
isValidObjectMaxDepth
*/
var minErrConfig = {
objectMaxDepth: 5,
urlErrorParamsEnabled: true
};
/**
* @ngdoc function
* @name angular.errorHandlingConfig
* @module ng
* @kind function
*
* @description
* Configure several aspects of error handling in AngularJS if used as a setter or return the
* current configuration if used as a getter. The following options are supported:
*
* - **objectMaxDepth**: The maximum depth to which objects are traversed when stringified for error messages.
*
* Omitted or undefined options will leave the corresponding configuration values unchanged.
*
* @param {Object=} config - The configuration object. May only contain the options that need to be
* updated. Supported keys:
*
* * `objectMaxDepth` **{Number}** - The max depth for stringifying objects. Setting to a
* non-positive or non-numeric value, removes the max depth limit.
* Default: 5
*
* * `urlErrorParamsEnabled` **{Boolean}** - Specifies wether the generated error url will
* contain the parameters of the thrown error. Disabling the parameters can be useful if the
* generated error url is very long.
*
* Default: true. When used without argument, it returns the current value.
*/
function errorHandlingConfig(config) {
if (isObject(config)) {
if (isDefined(config.objectMaxDepth)) {
minErrConfig.objectMaxDepth = isValidObjectMaxDepth(config.objectMaxDepth) ? config.objectMaxDepth : NaN;
}
if (isDefined(config.urlErrorParamsEnabled) && isBoolean(config.urlErrorParamsEnabled)) {
minErrConfig.urlErrorParamsEnabled = config.urlErrorParamsEnabled;
}
} else {
return minErrConfig;
}
}
/**
* @private
* @param {Number} maxDepth
* @return {boolean}
*/
function isValidObjectMaxDepth(maxDepth) {
return isNumber(maxDepth) && maxDepth > 0;
}
/**
* @description
*
* This object provides a utility for producing rich Error messages within
* AngularJS. It can be called as follows:
*
* var exampleMinErr = minErr('example');
* throw exampleMinErr('one', 'This {0} is {1}', foo, bar);
*
* The above creates an instance of minErr in the example namespace. The
* resulting error will have a namespaced error code of example.one. The
* resulting error will replace {0} with the value of foo, and {1} with the
* value of bar. The object is not restricted in the number of arguments it can
* take.
*
* If fewer arguments are specified than necessary for interpolation, the extra
* interpolation markers will be preserved in the final string.
*
* Since data will be parsed statically during a build step, some restrictions
* are applied with respect to how minErr instances are created and called.
* Instances should have names of the form namespaceMinErr for a minErr created
* using minErr('namespace') . Error codes, namespaces and template strings
* should all be static strings, not variables or general expressions.
*
* @param {string} module The namespace to use for the new minErr instance.
* @param {function} ErrorConstructor Custom error constructor to be instantiated when returning
* error from returned function, for cases when a particular type of error is useful.
* @returns {function(code:string, template:string, ...templateArgs): Error} minErr instance
*/
function minErr(module, ErrorConstructor) {
ErrorConstructor = ErrorConstructor || Error;
var url = 'https://errors.angularjs.org/1.7.9/';
var regex = url.replace('.', '\\.') + '[\\s\\S]*';
var errRegExp = new RegExp(regex, 'g');
return function() {
var code = arguments[0],
template = arguments[1],
message = '[' + (module ? module + ':' : '') + code + '] ',
templateArgs = sliceArgs(arguments, 2).map(function(arg) {
return toDebugString(arg, minErrConfig.objectMaxDepth);
}),
paramPrefix, i;
// A minErr message has two parts: the message itself and the url that contains the
// encoded message.
// The message's parameters can contain other error messages which also include error urls.
// To prevent the messages from getting too long, we strip the error urls from the parameters.
message += template.replace(/\{\d+\}/g, function(match) {
var index = +match.slice(1, -1);
if (index < templateArgs.length) {
return templateArgs[index].replace(errRegExp, '');
}
return match;
});
message += '\n' + url + (module ? module + '/' : '') + code;
if (minErrConfig.urlErrorParamsEnabled) {
for (i = 0, paramPrefix = '?'; i < templateArgs.length; i++, paramPrefix = '&') {
message += paramPrefix + 'p' + i + '=' + encodeURIComponent(templateArgs[i]);
}
}
return new ErrorConstructor(message);
};
}
/* We need to tell ESLint what variables are being exported */
/* exported
angular,
msie,
jqLite,
jQuery,
slice,
splice,
push,
toString,
minErrConfig,
errorHandlingConfig,
isValidObjectMaxDepth,
ngMinErr,
angularModule,
uid,
REGEX_STRING_REGEXP,
VALIDITY_STATE_PROPERTY,
lowercase,
uppercase,
nodeName_,
isArrayLike,
forEach,
forEachSorted,
reverseParams,
nextUid,
setHashKey,
extend,
toInt,
inherit,
merge,
noop,
identity,
valueFn,
isUndefined,
isDefined,
isObject,
isBlankObject,
isString,
isNumber,
isNumberNaN,
isDate,
isError,
isArray,
isFunction,
isRegExp,
isWindow,
isScope,
isFile,
isFormData,
isBlob,
isBoolean,
isPromiseLike,
trim,
escapeForRegexp,
isElement,
makeMap,
includes,
arrayRemove,
copy,
simpleCompare,
equals,
csp,
jq,
concat,
sliceArgs,
bind,
toJsonReplacer,
toJson,
fromJson,
convertTimezoneToLocal,
timezoneToOffset,
addDateMinutes,
startingTag,
tryDecodeURIComponent,
parseKeyValue,
toKeyValue,
encodeUriSegment,
encodeUriQuery,
angularInit,
bootstrap,
getTestability,
snake_case,
bindJQuery,
assertArg,
assertArgFn,
assertNotHasOwnProperty,
getter,
getBlockNodes,
hasOwnProperty,
createMap,
stringify,
NODE_TYPE_ELEMENT,
NODE_TYPE_ATTRIBUTE,
NODE_TYPE_TEXT,
NODE_TYPE_COMMENT,
NODE_TYPE_DOCUMENT,
NODE_TYPE_DOCUMENT_FRAGMENT
*/
////////////////////////////////////
/**
* @ngdoc module
* @name ng
* @module ng
* @installation
* @description
*
* The ng module is loaded by default when an AngularJS application is started. The module itself
* contains the essential components for an AngularJS application to function. The table below
* lists a high level breakdown of each of the services/factories, filters, directives and testing
* components available within this core module.
*
*/
var REGEX_STRING_REGEXP = /^\/(.+)\/([a-z]*)$/;
// The name of a form control's ValidityState property.
// This is used so that it's possible for internal tests to create mock ValidityStates.
var VALIDITY_STATE_PROPERTY = 'validity';
var hasOwnProperty = Object.prototype.hasOwnProperty;
/**
* @private
*
* @description Converts the specified string to lowercase.
* @param {string} string String to be converted to lowercase.
* @returns {string} Lowercased string.
*/
var lowercase = function(string) {return isString(string) ? string.toLowerCase() : string;};
/**
* @private
*
* @description Converts the specified string to uppercase.
* @param {string} string String to be converted to uppercase.
* @returns {string} Uppercased string.
*/
var uppercase = function(string) {return isString(string) ? string.toUpperCase() : string;};
var
msie, // holds major version number for IE, or NaN if UA is not IE.
jqLite, // delay binding since jQuery could be loaded after us.
jQuery, // delay binding
slice = [].slice,
splice = [].splice,
push = [].push,
toString = Object.prototype.toString,
getPrototypeOf = Object.getPrototypeOf,
ngMinErr = minErr('ng'),
/** @name angular */
angular = window.angular || (window.angular = {}),
angularModule,
uid = 0;
// Support: IE 9-11 only
/**
* documentMode is an IE-only property
* http://msdn.microsoft.com/en-us/library/ie/cc196988(v=vs.85).aspx
*/
msie = window.document.documentMode;
/**
* @private
* @param {*} obj
* @return {boolean} Returns true if `obj` is an array or array-like object (NodeList, Arguments,
* String ...)
*/
function isArrayLike(obj) {
// `null`, `undefined` and `window` are not array-like
if (obj == null || isWindow(obj)) return false;
// arrays, strings and jQuery/jqLite objects are array like
// * jqLite is either the jQuery or jqLite constructor function
// * we have to check the existence of jqLite first as this method is called
// via the forEach method when constructing the jqLite object in the first place
if (isArray(obj) || isString(obj) || (jqLite && obj instanceof jqLite)) return true;
// Support: iOS 8.2 (not reproducible in simulator)
// "length" in obj used to prevent JIT error (gh-11508)
var length = 'length' in Object(obj) && obj.length;
// NodeList objects (with `item` method) and
// other objects with suitable length characteristics are array-like
return isNumber(length) && (length >= 0 && (length - 1) in obj || typeof obj.item === 'function');
}
/**
* @ngdoc function
* @name angular.forEach
* @module ng
* @kind function
*
* @description
* Invokes the `iterator` function once for each item in `obj` collection, which can be either an
* object or an array. The `iterator` function is invoked with `iterator(value, key, obj)`, where `value`
* is the value of an object property or an array element, `key` is the object property key or
* array element index and obj is the `obj` itself. Specifying a `context` for the function is optional.
*
* It is worth noting that `.forEach` does not iterate over inherited properties because it filters
* using the `hasOwnProperty` method.
*
* Unlike ES262's
* [Array.prototype.forEach](http://www.ecma-international.org/ecma-262/5.1/#sec-15.4.4.18),
* providing 'undefined' or 'null' values for `obj` will not throw a TypeError, but rather just
* return the value provided.
*
```js
var values = {name: 'misko', gender: 'male'};
var log = [];
angular.forEach(values, function(value, key) {
this.push(key + ': ' + value);
}, log);
expect(log).toEqual(['name: misko', 'gender: male']);
```
*
* @param {Object|Array} obj Object to iterate over.
* @param {Function} iterator Iterator function.
* @param {Object=} context Object to become context (`this`) for the iterator function.
* @returns {Object|Array} Reference to `obj`.
*/
function forEach(obj, iterator, context) {
var key, length;
if (obj) {
if (isFunction(obj)) {
for (key in obj) {
if (key !== 'prototype' && key !== 'length' && key !== 'name' && obj.hasOwnProperty(key)) {
iterator.call(context, obj[key], key, obj);
}
}
} else if (isArray(obj) || isArrayLike(obj)) {
var isPrimitive = typeof obj !== 'object';
for (key = 0, length = obj.length; key < length; key++) {
if (isPrimitive || key in obj) {
iterator.call(context, obj[key], key, obj);
}
}
} else if (obj.forEach && obj.forEach !== forEach) {
obj.forEach(iterator, context, obj);
} else if (isBlankObject(obj)) {
// createMap() fast path --- Safe to avoid hasOwnProperty check because prototype chain is empty
for (key in obj) {
iterator.call(context, obj[key], key, obj);
}
} else if (typeof obj.hasOwnProperty === 'function') {
// Slow path for objects inheriting Object.prototype, hasOwnProperty check needed
for (key in obj) {
if (obj.hasOwnProperty(key)) {
iterator.call(context, obj[key], key, obj);
}
}
} else {
// Slow path for objects which do not have a method `hasOwnProperty`
for (key in obj) {
if (hasOwnProperty.call(obj, key)) {
iterator.call(context, obj[key], key, obj);
}
}
}
}
return obj;
}
function forEachSorted(obj, iterator, context) {
var keys = Object.keys(obj).sort();
for (var i = 0; i < keys.length; i++) {
iterator.call(context, obj[keys[i]], keys[i]);
}
return keys;
}
/**
* when using forEach the params are value, key, but it is often useful to have key, value.
* @param {function(string, *)} iteratorFn
* @returns {function(*, string)}
*/
function reverseParams(iteratorFn) {
return function(value, key) {iteratorFn(key, value);};
}
/**
* A consistent way of creating unique IDs in angular.
*
* Using simple numbers allows us to generate 28.6 million unique ids per second for 10 years before
* we hit number precision issues in JavaScript.
*
* Math.pow(2,53) / 60 / 60 / 24 / 365 / 10 = 28.6M
*
* @returns {number} an unique alpha-numeric string
*/
function nextUid() {
return ++uid;
}
/**
* Set or clear the hashkey for an object.
* @param obj object
* @param h the hashkey (!truthy to delete the hashkey)
*/
function setHashKey(obj, h) {
if (h) {
obj.$$hashKey = h;
} else {
delete obj.$$hashKey;
}
}
function baseExtend(dst, objs, deep) {
var h = dst.$$hashKey;
for (var i = 0, ii = objs.length; i < ii; ++i) {
var obj = objs[i];
if (!isObject(obj) && !isFunction(obj)) continue;
var keys = Object.keys(obj);
for (var j = 0, jj = keys.length; j < jj; j++) {
var key = keys[j];
var src = obj[key];
if (deep && isObject(src)) {
if (isDate(src)) {
dst[key] = new Date(src.valueOf());
} else if (isRegExp(src)) {
dst[key] = new RegExp(src);
} else if (src.nodeName) {
dst[key] = src.cloneNode(true);
} else if (isElement(src)) {
dst[key] = src.clone();
} else {
if (key !== '__proto__') {
if (!isObject(dst[key])) dst[key] = isArray(src) ? [] : {};
baseExtend(dst[key], [src], true);
}
}
} else {
dst[key] = src;
}
}
}
setHashKey(dst, h);
return dst;
}
/**
* @ngdoc function
* @name angular.extend
* @module ng
* @kind function
*
* @description
* Extends the destination object `dst` by copying own enumerable properties from the `src` object(s)
* to `dst`. You can specify multiple `src` objects. If you want to preserve original objects, you can do so
* by passing an empty object as the target: `var object = angular.extend({}, object1, object2)`.
*
* **Note:** Keep in mind that `angular.extend` does not support recursive merge (deep copy). Use
* {@link angular.merge} for this.
*
* @param {Object} dst Destination object.
* @param {...Object} src Source object(s).
* @returns {Object} Reference to `dst`.
*/
function extend(dst) {
return baseExtend(dst, slice.call(arguments, 1), false);
}
/**
* @ngdoc function
* @name angular.merge
* @module ng
* @kind function
*
* @description
* Deeply extends the destination object `dst` by copying own enumerable properties from the `src` object(s)
* to `dst`. You can specify multiple `src` objects. If you want to preserve original objects, you can do so
* by passing an empty object as the target: `var object = angular.merge({}, object1, object2)`.
*
* Unlike {@link angular.extend extend()}, `merge()` recursively descends into object properties of source
* objects, performing a deep copy.
*
* @deprecated
* sinceVersion="1.6.5"
* This function is deprecated, but will not be removed in the 1.x lifecycle.
* There are edge cases (see {@link angular.merge#known-issues known issues}) that are not
* supported by this function. We suggest using another, similar library for all-purpose merging,
* such as [lodash's merge()](https://lodash.com/docs/4.17.4#merge).
*
* @knownIssue
* This is a list of (known) object types that are not handled correctly by this function:
* - [`Blob`](https://developer.mozilla.org/docs/Web/API/Blob)
* - [`MediaStream`](https://developer.mozilla.org/docs/Web/API/MediaStream)
* - [`CanvasGradient`](https://developer.mozilla.org/docs/Web/API/CanvasGradient)
* - AngularJS {@link $rootScope.Scope scopes};
*
* `angular.merge` also does not support merging objects with circular references.
*
* @param {Object} dst Destination object.
* @param {...Object} src Source object(s).
* @returns {Object} Reference to `dst`.
*/
function merge(dst) {
return baseExtend(dst, slice.call(arguments, 1), true);
}
function toInt(str) {
return parseInt(str, 10);
}
var isNumberNaN = Number.isNaN || function isNumberNaN(num) {
// eslint-disable-next-line no-self-compare
return num !== num;
};
function inherit(parent, extra) {
return extend(Object.create(parent), extra);
}
/**
* @ngdoc function
* @name angular.noop
* @module ng
* @kind function
*
* @description
* A function that performs no operations. This function can be useful when writing code in the
* functional style.
```js
function foo(callback) {
var result = calculateResult();
(callback || angular.noop)(result);
}
```
*/
function noop() {}
noop.$inject = [];
/**
* @ngdoc function
* @name angular.identity
* @module ng
* @kind function
*
* @description
* A function that returns its first argument. This function is useful when writing code in the
* functional style.
*
```js
function transformer(transformationFn, value) {
return (transformationFn || angular.identity)(value);
};
// E.g.
function getResult(fn, input) {
return (fn || angular.identity)(input);
};
getResult(function(n) { return n * 2; }, 21); // returns 42
getResult(null, 21); // returns 21
getResult(undefined, 21); // returns 21
```
*
* @param {*} value to be returned.
* @returns {*} the value passed in.
*/
function identity($) {return $;}
identity.$inject = [];
function valueFn(value) {return function valueRef() {return value;};}
function hasCustomToString(obj) {
return isFunction(obj.toString) && obj.toString !== toString;
}
/**
* @ngdoc function
* @name angular.isUndefined
* @module ng
* @kind function
*
* @description
* Determines if a reference is undefined.
*
* @param {*} value Reference to check.
* @returns {boolean} True if `value` is undefined.
*/
function isUndefined(value) {return typeof value === 'undefined';}
/**
* @ngdoc function
* @name angular.isDefined
* @module ng
* @kind function
*
* @description
* Determines if a reference is defined.
*
* @param {*} value Reference to check.
* @returns {boolean} True if `value` is defined.
*/
function isDefined(value) {return typeof value !== 'undefined';}
/**
* @ngdoc function
* @name angular.isObject
* @module ng
* @kind function
*
* @description
* Determines if a reference is an `Object`. Unlike `typeof` in JavaScript, `null`s are not
* considered to be objects. Note that JavaScript arrays are objects.
*
* @param {*} value Reference to check.
* @returns {boolean} True if `value` is an `Object` but not `null`.
*/
function isObject(value) {
// http://jsperf.com/isobject4
return value !== null && typeof value === 'object';
}
/**
* Determine if a value is an object with a null prototype
*
* @returns {boolean} True if `value` is an `Object` with a null prototype
*/
function isBlankObject(value) {
return value !== null && typeof value === 'object' && !getPrototypeOf(value);
}
/**
* @ngdoc function
* @name angular.isString
* @module ng
* @kind function
*
* @description
* Determines if a reference is a `String`.
*
* @param {*} value Reference to check.
* @returns {boolean} True if `value` is a `String`.
*/
function isString(value) {return typeof value === 'string';}
/**
* @ngdoc function
* @name angular.isNumber
* @module ng
* @kind function
*
* @description
* Determines if a reference is a `Number`.
*
* This includes the "special" numbers `NaN`, `+Infinity` and `-Infinity`.
*
* If you wish to exclude these then you can use the native
* [`isFinite'](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/isFinite)
* method.
*
* @param {*} value Reference to check.
* @returns {boolean} True if `value` is a `Number`.
*/
function isNumber(value) {return typeof value === 'number';}
/**
* @ngdoc function
* @name angular.isDate
* @module ng
* @kind function
*
* @description
* Determines if a value is a date.
*
* @param {*} value Reference to check.
* @returns {boolean} True if `value` is a `Date`.
*/
function isDate(value) {
return toString.call(value) === '[object Date]';
}
/**
* @ngdoc function
* @name angular.isArray
* @module ng
* @kind function
*
* @description
* Determines if a reference is an `Array`.
*
* @param {*} value Reference to check.
* @returns {boolean} True if `value` is an `Array`.
*/
function isArray(arr) {
return Array.isArray(arr) || arr instanceof Array;
}
/**
* @description
* Determines if a reference is an `Error`.
* Loosely based on https://www.npmjs.com/package/iserror
*
* @param {*} value Reference to check.
* @returns {boolean} True if `value` is an `Error`.
*/
function isError(value) {
var tag = toString.call(value);
switch (tag) {
case '[object Error]': return true;
case '[object Exception]': return true;
case '[object DOMException]': return true;
default: return value instanceof Error;
}
}
/**
* @ngdoc function
* @name angular.isFunction
* @module ng
* @kind function
*
* @description
* Determines if a reference is a `Function`.
*
* @param {*} value Reference to check.
* @returns {boolean} True if `value` is a `Function`.
*/
function isFunction(value) {return typeof value === 'function';}
/**
* Determines if a value is a regular expression object.
*
* @private
* @param {*} value Reference to check.
* @returns {boolean} True if `value` is a `RegExp`.
*/
function isRegExp(value) {
return toString.call(value) === '[object RegExp]';
}
/**
* Checks if `obj` is a window object.
*
* @private
* @param {*} obj Object to check
* @returns {boolean} True if `obj` is a window obj.
*/
function isWindow(obj) {
return obj && obj.window === obj;
}
function isScope(obj) {
return obj && obj.$evalAsync && obj.$watch;
}
function isFile(obj) {
return toString.call(obj) === '[object File]';
}
function isFormData(obj) {
return toString.call(obj) === '[object FormData]';
}
function isBlob(obj) {
return toString.call(obj) === '[object Blob]';
}
function isBoolean(value) {
return typeof value === 'boolean';
}
function isPromiseLike(obj) {
return obj && isFunction(obj.then);
}
var TYPED_ARRAY_REGEXP = /^\[object (?:Uint8|Uint8Clamped|Uint16|Uint32|Int8|Int16|Int32|Float32|Float64)Array]$/;
function isTypedArray(value) {
return value && isNumber(value.length) && TYPED_ARRAY_REGEXP.test(toString.call(value));
}
function isArrayBuffer(obj) {
return toString.call(obj) === '[object ArrayBuffer]';
}
var trim = function(value) {
return isString(value) ? value.trim() : value;
};
// Copied from:
// http://docs.closure-library.googlecode.com/git/local_closure_goog_string_string.js.source.html#line1021
// Prereq: s is a string.
var escapeForRegexp = function(s) {
return s
.replace(/([-()[\]{}+?*.$^|,:#= 0) {
array.splice(index, 1);
}
return index;
}
/**
* @ngdoc function
* @name angular.copy
* @module ng
* @kind function
*
* @description
* Creates a deep copy of `source`, which should be an object or an array. This functions is used
* internally, mostly in the change-detection code. It is not intended as an all-purpose copy
* function, and has several limitations (see below).
*
* * If no destination is supplied, a copy of the object or array is created.
* * If a destination is provided, all of its elements (for arrays) or properties (for objects)
* are deleted and then all elements/properties from the source are copied to it.
* * If `source` is not an object or array (inc. `null` and `undefined`), `source` is returned.
* * If `source` is identical to `destination` an exception will be thrown.
*
*
*
*
* Only enumerable properties are taken into account. Non-enumerable properties (both on `source`
* and on `destination`) will be ignored.
*
*
*
* `angular.copy` does not check if destination and source are of the same type. It's the
* developer's responsibility to make sure they are compatible.
*
*
* @knownIssue
* This is a non-exhaustive list of object types / features that are not handled correctly by
* `angular.copy`. Note that since this functions is used by the change detection code, this
* means binding or watching objects of these types (or that include these types) might not work
* correctly.
* - [`File`](https://developer.mozilla.org/docs/Web/API/File)
* - [`Map`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Map)
* - [`ImageData`](https://developer.mozilla.org/docs/Web/API/ImageData)
* - [`MediaStream`](https://developer.mozilla.org/docs/Web/API/MediaStream)
* - [`Set`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Set)
* - [`WeakMap`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/WeakMap)
* - ['getter'](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/get)/
* [`setter`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/set)`
*
* @param {*} source The source that will be used to make a copy. Can be any type, including
* primitives, `null`, and `undefined`.
* @param {(Object|Array)=} destination Destination into which the source is copied. If provided,
* must be of the same type as `source`.
* @returns {*} The copy or updated `destination`, if `destination` was specified.
*
* @example
form = {{user | json}}
leader = {{leader | json}}
// Module: copyExample
angular.
module('copyExample', []).
controller('ExampleController', ['$scope', function($scope) {
$scope.leader = {};
$scope.reset = function() {
// Example with 1 argument
$scope.user = angular.copy($scope.leader);
};
$scope.update = function(user) {
// Example with 2 arguments
angular.copy(user, $scope.leader);
};
$scope.reset();
}]);
*/
function copy(source, destination, maxDepth) {
var stackSource = [];
var stackDest = [];
maxDepth = isValidObjectMaxDepth(maxDepth) ? maxDepth : NaN;
if (destination) {
if (isTypedArray(destination) || isArrayBuffer(destination)) {
throw ngMinErr('cpta', 'Can\'t copy! TypedArray destination cannot be mutated.');
}
if (source === destination) {
throw ngMinErr('cpi', 'Can\'t copy! Source and destination are identical.');
}
// Empty the destination object
if (isArray(destination)) {
destination.length = 0;
} else {
forEach(destination, function(value, key) {
if (key !== '$$hashKey') {
delete destination[key];
}
});
}
stackSource.push(source);
stackDest.push(destination);
return copyRecurse(source, destination, maxDepth);
}
return copyElement(source, maxDepth);
function copyRecurse(source, destination, maxDepth) {
maxDepth--;
if (maxDepth < 0) {
return '...';
}
var h = destination.$$hashKey;
var key;
if (isArray(source)) {
for (var i = 0, ii = source.length; i < ii; i++) {
destination.push(copyElement(source[i], maxDepth));
}
} else if (isBlankObject(source)) {
// createMap() fast path --- Safe to avoid hasOwnProperty check because prototype chain is empty
for (key in source) {
destination[key] = copyElement(source[key], maxDepth);
}
} else if (source && typeof source.hasOwnProperty === 'function') {
// Slow path, which must rely on hasOwnProperty
for (key in source) {
if (source.hasOwnProperty(key)) {
destination[key] = copyElement(source[key], maxDepth);
}
}
} else {
// Slowest path --- hasOwnProperty can't be called as a method
for (key in source) {
if (hasOwnProperty.call(source, key)) {
destination[key] = copyElement(source[key], maxDepth);
}
}
}
setHashKey(destination, h);
return destination;
}
function copyElement(source, maxDepth) {
// Simple values
if (!isObject(source)) {
return source;
}
// Already copied values
var index = stackSource.indexOf(source);
if (index !== -1) {
return stackDest[index];
}
if (isWindow(source) || isScope(source)) {
throw ngMinErr('cpws',
'Can\'t copy! Making copies of Window or Scope instances is not supported.');
}
var needsRecurse = false;
var destination = copyType(source);
if (destination === undefined) {
destination = isArray(source) ? [] : Object.create(getPrototypeOf(source));
needsRecurse = true;
}
stackSource.push(source);
stackDest.push(destination);
return needsRecurse
? copyRecurse(source, destination, maxDepth)
: destination;
}
function copyType(source) {
switch (toString.call(source)) {
case '[object Int8Array]':
case '[object Int16Array]':
case '[object Int32Array]':
case '[object Float32Array]':
case '[object Float64Array]':
case '[object Uint8Array]':
case '[object Uint8ClampedArray]':
case '[object Uint16Array]':
case '[object Uint32Array]':
return new source.constructor(copyElement(source.buffer), source.byteOffset, source.length);
case '[object ArrayBuffer]':
// Support: IE10
if (!source.slice) {
// If we're in this case we know the environment supports ArrayBuffer
/* eslint-disable no-undef */
var copied = new ArrayBuffer(source.byteLength);
new Uint8Array(copied).set(new Uint8Array(source));
/* eslint-enable */
return copied;
}
return source.slice(0);
case '[object Boolean]':
case '[object Number]':
case '[object String]':
case '[object Date]':
return new source.constructor(source.valueOf());
case '[object RegExp]':
var re = new RegExp(source.source, source.toString().match(/[^/]*$/)[0]);
re.lastIndex = source.lastIndex;
return re;
case '[object Blob]':
return new source.constructor([source], {type: source.type});
}
if (isFunction(source.cloneNode)) {
return source.cloneNode(true);
}
}
}
// eslint-disable-next-line no-self-compare
function simpleCompare(a, b) { return a === b || (a !== a && b !== b); }
/**
* @ngdoc function
* @name angular.equals
* @module ng
* @kind function
*
* @description
* Determines if two objects or two values are equivalent. Supports value types, regular
* expressions, arrays and objects.
*
* Two objects or values are considered equivalent if at least one of the following is true:
*
* * Both objects or values pass `===` comparison.
* * Both objects or values are of the same type and all of their properties are equal by
* comparing them with `angular.equals`.
* * Both values are NaN. (In JavaScript, NaN == NaN => false. But we consider two NaN as equal)
* * Both values represent the same regular expression (In JavaScript,
* /abc/ == /abc/ => false. But we consider two regular expressions as equal when their textual
* representation matches).
*
* During a property comparison, properties of `function` type and properties with names
* that begin with `$` are ignored.
*
* Scope and DOMWindow objects are being compared only by identify (`===`).
*
* @param {*} o1 Object or value to compare.
* @param {*} o2 Object or value to compare.
* @returns {boolean} True if arguments are equal.
*
* @example
angular.module('equalsExample', []).controller('ExampleController', ['$scope', function($scope) {
$scope.user1 = {};
$scope.user2 = {};
$scope.compare = function() {
$scope.result = angular.equals($scope.user1, $scope.user2);
};
}]);
*/
function equals(o1, o2) {
if (o1 === o2) return true;
if (o1 === null || o2 === null) return false;
// eslint-disable-next-line no-self-compare
if (o1 !== o1 && o2 !== o2) return true; // NaN === NaN
var t1 = typeof o1, t2 = typeof o2, length, key, keySet;
if (t1 === t2 && t1 === 'object') {
if (isArray(o1)) {
if (!isArray(o2)) return false;
if ((length = o1.length) === o2.length) {
for (key = 0; key < length; key++) {
if (!equals(o1[key], o2[key])) return false;
}
return true;
}
} else if (isDate(o1)) {
if (!isDate(o2)) return false;
return simpleCompare(o1.getTime(), o2.getTime());
} else if (isRegExp(o1)) {
if (!isRegExp(o2)) return false;
return o1.toString() === o2.toString();
} else {
if (isScope(o1) || isScope(o2) || isWindow(o1) || isWindow(o2) ||
isArray(o2) || isDate(o2) || isRegExp(o2)) return false;
keySet = createMap();
for (key in o1) {
if (key.charAt(0) === '$' || isFunction(o1[key])) continue;
if (!equals(o1[key], o2[key])) return false;
keySet[key] = true;
}
for (key in o2) {
if (!(key in keySet) &&
key.charAt(0) !== '$' &&
isDefined(o2[key]) &&
!isFunction(o2[key])) return false;
}
return true;
}
}
return false;
}
var csp = function() {
if (!isDefined(csp.rules)) {
var ngCspElement = (window.document.querySelector('[ng-csp]') ||
window.document.querySelector('[data-ng-csp]'));
if (ngCspElement) {
var ngCspAttribute = ngCspElement.getAttribute('ng-csp') ||
ngCspElement.getAttribute('data-ng-csp');
csp.rules = {
noUnsafeEval: !ngCspAttribute || (ngCspAttribute.indexOf('no-unsafe-eval') !== -1),
noInlineStyle: !ngCspAttribute || (ngCspAttribute.indexOf('no-inline-style') !== -1)
};
} else {
csp.rules = {
noUnsafeEval: noUnsafeEval(),
noInlineStyle: false
};
}
}
return csp.rules;
function noUnsafeEval() {
try {
// eslint-disable-next-line no-new, no-new-func
new Function('');
return false;
} catch (e) {
return true;
}
}
};
/**
* @ngdoc directive
* @module ng
* @name ngJq
*
* @element ANY
* @param {string=} ngJq the name of the library available under `window`
* to be used for angular.element
* @description
* Use this directive to force the angular.element library. This should be
* used to force either jqLite by leaving ng-jq blank or setting the name of
* the jquery variable under window (eg. jQuery).
*
* Since AngularJS looks for this directive when it is loaded (doesn't wait for the
* DOMContentLoaded event), it must be placed on an element that comes before the script
* which loads angular. Also, only the first instance of `ng-jq` will be used and all
* others ignored.
*
* @example
* This example shows how to force jqLite using the `ngJq` directive to the `html` tag.
```html
...
...
```
* @example
* This example shows how to use a jQuery based library of a different name.
* The library name must be available at the top most 'window'.
```html
...
...
```
*/
var jq = function() {
if (isDefined(jq.name_)) return jq.name_;
var el;
var i, ii = ngAttrPrefixes.length, prefix, name;
for (i = 0; i < ii; ++i) {
prefix = ngAttrPrefixes[i];
el = window.document.querySelector('[' + prefix.replace(':', '\\:') + 'jq]');
if (el) {
name = el.getAttribute(prefix + 'jq');
break;
}
}
return (jq.name_ = name);
};
function concat(array1, array2, index) {
return array1.concat(slice.call(array2, index));
}
function sliceArgs(args, startIndex) {
return slice.call(args, startIndex || 0);
}
/**
* @ngdoc function
* @name angular.bind
* @module ng
* @kind function
*
* @description
* Returns a function which calls function `fn` bound to `self` (`self` becomes the `this` for
* `fn`). You can supply optional `args` that are prebound to the function. This feature is also
* known as [partial application](http://en.wikipedia.org/wiki/Partial_application), as
* distinguished from [function currying](http://en.wikipedia.org/wiki/Currying#Contrast_with_partial_function_application).
*
* @param {Object} self Context which `fn` should be evaluated in.
* @param {function()} fn Function to be bound.
* @param {...*} args Optional arguments to be prebound to the `fn` function call.
* @returns {function()} Function that wraps the `fn` with all the specified bindings.
*/
function bind(self, fn) {
var curryArgs = arguments.length > 2 ? sliceArgs(arguments, 2) : [];
if (isFunction(fn) && !(fn instanceof RegExp)) {
return curryArgs.length
? function() {
return arguments.length
? fn.apply(self, concat(curryArgs, arguments, 0))
: fn.apply(self, curryArgs);
}
: function() {
return arguments.length
? fn.apply(self, arguments)
: fn.call(self);
};
} else {
// In IE, native methods are not functions so they cannot be bound (note: they don't need to be).
return fn;
}
}
function toJsonReplacer(key, value) {
var val = value;
if (typeof key === 'string' && key.charAt(0) === '$' && key.charAt(1) === '$') {
val = undefined;
} else if (isWindow(value)) {
val = '$WINDOW';
} else if (value && window.document === value) {
val = '$DOCUMENT';
} else if (isScope(value)) {
val = '$SCOPE';
}
return val;
}
/**
* @ngdoc function
* @name angular.toJson
* @module ng
* @kind function
*
* @description
* Serializes input into a JSON-formatted string. Properties with leading $$ characters will be
* stripped since AngularJS uses this notation internally.
*
* @param {Object|Array|Date|string|number|boolean} obj Input to be serialized into JSON.
* @param {boolean|number} [pretty=2] If set to true, the JSON output will contain newlines and whitespace.
* If set to an integer, the JSON output will contain that many spaces per indentation.
* @returns {string|undefined} JSON-ified string representing `obj`.
* @knownIssue
*
* The Safari browser throws a `RangeError` instead of returning `null` when it tries to stringify a `Date`
* object with an invalid date value. The only reliable way to prevent this is to monkeypatch the
* `Date.prototype.toJSON` method as follows:
*
* ```
* var _DatetoJSON = Date.prototype.toJSON;
* Date.prototype.toJSON = function() {
* try {
* return _DatetoJSON.call(this);
* } catch(e) {
* if (e instanceof RangeError) {
* return null;
* }
* throw e;
* }
* };
* ```
*
* See https://github.com/angular/angular.js/pull/14221 for more information.
*/
function toJson(obj, pretty) {
if (isUndefined(obj)) return undefined;
if (!isNumber(pretty)) {
pretty = pretty ? 2 : null;
}
return JSON.stringify(obj, toJsonReplacer, pretty);
}
/**
* @ngdoc function
* @name angular.fromJson
* @module ng
* @kind function
*
* @description
* Deserializes a JSON string.
*
* @param {string} json JSON string to deserialize.
* @returns {Object|Array|string|number} Deserialized JSON string.
*/
function fromJson(json) {
return isString(json)
? JSON.parse(json)
: json;
}
var ALL_COLONS = /:/g;
function timezoneToOffset(timezone, fallback) {
// Support: IE 9-11 only, Edge 13-15+
// IE/Edge do not "understand" colon (`:`) in timezone
timezone = timezone.replace(ALL_COLONS, '');
var requestedTimezoneOffset = Date.parse('Jan 01, 1970 00:00:00 ' + timezone) / 60000;
return isNumberNaN(requestedTimezoneOffset) ? fallback : requestedTimezoneOffset;
}
function addDateMinutes(date, minutes) {
date = new Date(date.getTime());
date.setMinutes(date.getMinutes() + minutes);
return date;
}
function convertTimezoneToLocal(date, timezone, reverse) {
reverse = reverse ? -1 : 1;
var dateTimezoneOffset = date.getTimezoneOffset();
var timezoneOffset = timezoneToOffset(timezone, dateTimezoneOffset);
return addDateMinutes(date, reverse * (timezoneOffset - dateTimezoneOffset));
}
/**
* @returns {string} Returns the string representation of the element.
*/
function startingTag(element) {
element = jqLite(element).clone().empty();
var elemHtml = jqLite('').append(element).html();
try {
return element[0].nodeType === NODE_TYPE_TEXT ? lowercase(elemHtml) :
elemHtml.
match(/^(<[^>]+>)/)[1].
replace(/^<([\w-]+)/, function(match, nodeName) {return '<' + lowercase(nodeName);});
} catch (e) {
return lowercase(elemHtml);
}
}
/////////////////////////////////////////////////
/**
* Tries to decode the URI component without throwing an exception.
*
* @private
* @param str value potential URI component to check.
* @returns {boolean} True if `value` can be decoded
* with the decodeURIComponent function.
*/
function tryDecodeURIComponent(value) {
try {
return decodeURIComponent(value);
} catch (e) {
// Ignore any invalid uri component.
}
}
/**
* Parses an escaped url query string into key-value pairs.
* @returns {Object.}
*/
function parseKeyValue(/**string*/keyValue) {
var obj = {};
forEach((keyValue || '').split('&'), function(keyValue) {
var splitPoint, key, val;
if (keyValue) {
key = keyValue = keyValue.replace(/\+/g,'%20');
splitPoint = keyValue.indexOf('=');
if (splitPoint !== -1) {
key = keyValue.substring(0, splitPoint);
val = keyValue.substring(splitPoint + 1);
}
key = tryDecodeURIComponent(key);
if (isDefined(key)) {
val = isDefined(val) ? tryDecodeURIComponent(val) : true;
if (!hasOwnProperty.call(obj, key)) {
obj[key] = val;
} else if (isArray(obj[key])) {
obj[key].push(val);
} else {
obj[key] = [obj[key],val];
}
}
}
});
return obj;
}
function toKeyValue(obj) {
var parts = [];
forEach(obj, function(value, key) {
if (isArray(value)) {
forEach(value, function(arrayValue) {
parts.push(encodeUriQuery(key, true) +
(arrayValue === true ? '' : '=' + encodeUriQuery(arrayValue, true)));
});
} else {
parts.push(encodeUriQuery(key, true) +
(value === true ? '' : '=' + encodeUriQuery(value, true)));
}
});
return parts.length ? parts.join('&') : '';
}
/**
* We need our custom method because encodeURIComponent is too aggressive and doesn't follow
* http://www.ietf.org/rfc/rfc3986.txt with regards to the character set (pchar) allowed in path
* segments:
* segment = *pchar
* pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
* pct-encoded = "%" HEXDIG HEXDIG
* unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
* sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
* / "*" / "+" / "," / ";" / "="
*/
function encodeUriSegment(val) {
return encodeUriQuery(val, true).
replace(/%26/gi, '&').
replace(/%3D/gi, '=').
replace(/%2B/gi, '+');
}
/**
* This method is intended for encoding *key* or *value* parts of query component. We need a custom
* method because encodeURIComponent is too aggressive and encodes stuff that doesn't have to be
* encoded per http://tools.ietf.org/html/rfc3986:
* query = *( pchar / "/" / "?" )
* pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
* unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
* pct-encoded = "%" HEXDIG HEXDIG
* sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
* / "*" / "+" / "," / ";" / "="
*/
function encodeUriQuery(val, pctEncodeSpaces) {
return encodeURIComponent(val).
replace(/%40/gi, '@').
replace(/%3A/gi, ':').
replace(/%24/g, '$').
replace(/%2C/gi, ',').
replace(/%3B/gi, ';').
replace(/%20/g, (pctEncodeSpaces ? '%20' : '+'));
}
var ngAttrPrefixes = ['ng-', 'data-ng-', 'ng:', 'x-ng-'];
function getNgAttribute(element, ngAttr) {
var attr, i, ii = ngAttrPrefixes.length;
for (i = 0; i < ii; ++i) {
attr = ngAttrPrefixes[i] + ngAttr;
if (isString(attr = element.getAttribute(attr))) {
return attr;
}
}
return null;
}
function allowAutoBootstrap(document) {
var script = document.currentScript;
if (!script) {
// Support: IE 9-11 only
// IE does not have `document.currentScript`
return true;
}
// If the `currentScript` property has been clobbered just return false, since this indicates a probable attack
if (!(script instanceof window.HTMLScriptElement || script instanceof window.SVGScriptElement)) {
return false;
}
var attributes = script.attributes;
var srcs = [attributes.getNamedItem('src'), attributes.getNamedItem('href'), attributes.getNamedItem('xlink:href')];
return srcs.every(function(src) {
if (!src) {
return true;
}
if (!src.value) {
return false;
}
var link = document.createElement('a');
link.href = src.value;
if (document.location.origin === link.origin) {
// Same-origin resources are always allowed, even for non-whitelisted schemes.
return true;
}
// Disabled bootstrapping unless angular.js was loaded from a known scheme used on the web.
// This is to prevent angular.js bundled with browser extensions from being used to bypass the
// content security policy in web pages and other browser extensions.
switch (link.protocol) {
case 'http:':
case 'https:':
case 'ftp:':
case 'blob:':
case 'file:':
case 'data:':
return true;
default:
return false;
}
});
}
// Cached as it has to run during loading so that document.currentScript is available.
var isAutoBootstrapAllowed = allowAutoBootstrap(window.document);
/**
* @ngdoc directive
* @name ngApp
* @module ng
*
* @element ANY
* @param {angular.Module} ngApp an optional application
* {@link angular.module module} name to load.
* @param {boolean=} ngStrictDi if this attribute is present on the app element, the injector will be
* created in "strict-di" mode. This means that the application will fail to invoke functions which
* do not use explicit function annotation (and are thus unsuitable for minification), as described
* in {@link guide/di the Dependency Injection guide}, and useful debugging info will assist in
* tracking down the root of these bugs.
*
* @description
*
* Use this directive to **auto-bootstrap** an AngularJS application. The `ngApp` directive
* designates the **root element** of the application and is typically placed near the root element
* of the page - e.g. on the `` or `` tags.
*
* There are a few things to keep in mind when using `ngApp`:
* - only one AngularJS application can be auto-bootstrapped per HTML document. The first `ngApp`
* found in the document will be used to define the root element to auto-bootstrap as an
* application. To run multiple applications in an HTML document you must manually bootstrap them using
* {@link angular.bootstrap} instead.
* - AngularJS applications cannot be nested within each other.
* - Do not use a directive that uses {@link ng.$compile#transclusion transclusion} on the same element as `ngApp`.
* This includes directives such as {@link ng.ngIf `ngIf`}, {@link ng.ngInclude `ngInclude`} and
* {@link ngRoute.ngView `ngView`}.
* Doing this misplaces the app {@link ng.$rootElement `$rootElement`} and the app's {@link auto.$injector injector},
* causing animations to stop working and making the injector inaccessible from outside the app.
*
* You can specify an **AngularJS module** to be used as the root module for the application. This
* module will be loaded into the {@link auto.$injector} when the application is bootstrapped. It
* should contain the application code needed or have dependencies on other modules that will
* contain the code. See {@link angular.module} for more information.
*
* In the example below if the `ngApp` directive were not placed on the `html` element then the
* document would not be compiled, the `AppController` would not be instantiated and the `{{ a+b }}`
* would not be resolved to `3`.
*
* @example
*
* ### Simple Usage
*
* `ngApp` is the easiest, and most common way to bootstrap an application.
*
I can add: {{a}} + {{b}} = {{ a+b }}
angular.module('ngAppDemo', []).controller('ngAppDemoController', function($scope) {
$scope.a = 1;
$scope.b = 2;
});
*
* @example
*
* ### With `ngStrictDi`
*
* Using `ngStrictDi`, you would see something like this:
*
I can add: {{a}} + {{b}} = {{ a+b }}
This renders because the controller does not fail to
instantiate, by using explicit annotation style (see
script.js for details)
Name:
Hello, {{name}}!
This renders because the controller does not fail to
instantiate, by using explicit annotation style
(see script.js for details)
I can add: {{a}} + {{b}} = {{ a+b }}
The controller could not be instantiated, due to relying
on automatic function annotations (which are disabled in
strict mode). As such, the content of this section is not
interpolated, and there should be an error in your web console.
angular.module('ngAppStrictDemo', [])
// BadController will fail to instantiate, due to relying on automatic function annotation,
// rather than an explicit annotation
.controller('BadController', function($scope) {
$scope.a = 1;
$scope.b = 2;
})
// Unlike BadController, GoodController1 and GoodController2 will not fail to be instantiated,
// due to using explicit annotations using the array style and $inject property, respectively.
.controller('GoodController1', ['$scope', function($scope) {
$scope.a = 1;
$scope.b = 2;
}])
.controller('GoodController2', GoodController2);
function GoodController2($scope) {
$scope.name = 'World';
}
GoodController2.$inject = ['$scope'];
div[ng-controller] {
margin-bottom: 1em;
-webkit-border-radius: 4px;
border-radius: 4px;
border: 1px solid;
padding: .5em;
}
div[ng-controller^=Good] {
border-color: #d6e9c6;
background-color: #dff0d8;
color: #3c763d;
}
div[ng-controller^=Bad] {
border-color: #ebccd1;
background-color: #f2dede;
color: #a94442;
margin-bottom: 0;
}
*/
function angularInit(element, bootstrap) {
var appElement,
module,
config = {};
// The element `element` has priority over any other element.
forEach(ngAttrPrefixes, function(prefix) {
var name = prefix + 'app';
if (!appElement && element.hasAttribute && element.hasAttribute(name)) {
appElement = element;
module = element.getAttribute(name);
}
});
forEach(ngAttrPrefixes, function(prefix) {
var name = prefix + 'app';
var candidate;
if (!appElement && (candidate = element.querySelector('[' + name.replace(':', '\\:') + ']'))) {
appElement = candidate;
module = candidate.getAttribute(name);
}
});
if (appElement) {
if (!isAutoBootstrapAllowed) {
window.console.error('AngularJS: disabling automatic bootstrap.
*
*
*
* ```
*
* @param {DOMElement} element DOM element which is the root of AngularJS application.
* @param {Array=} modules an array of modules to load into the application.
* Each item in the array should be the name of a predefined module or a (DI annotated)
* function that will be invoked by the injector as a `config` block.
* See: {@link angular.module modules}
* @param {Object=} config an object for defining configuration options for the application. The
* following keys are supported:
*
* * `strictDi` - disable automatic function annotation for the application. This is meant to
* assist in finding bugs which break minified code. Defaults to `false`.
*
* @returns {auto.$injector} Returns the newly created injector for this app.
*/
function bootstrap(element, modules, config) {
if (!isObject(config)) config = {};
var defaultConfig = {
strictDi: false
};
config = extend(defaultConfig, config);
var doBootstrap = function() {
element = jqLite(element);
if (element.injector()) {
var tag = (element[0] === window.document) ? 'document' : startingTag(element);
// Encode angle brackets to prevent input from being sanitized to empty string #8683.
throw ngMinErr(
'btstrpd',
'App already bootstrapped with this element \'{0}\'',
tag.replace(/,'<').replace(/>/,'>'));
}
modules = modules || [];
modules.unshift(['$provide', function($provide) {
$provide.value('$rootElement', element);
}]);
if (config.debugInfoEnabled) {
// Pushing so that this overrides `debugInfoEnabled` setting defined in user's `modules`.
modules.push(['$compileProvider', function($compileProvider) {
$compileProvider.debugInfoEnabled(true);
}]);
}
modules.unshift('ng');
var injector = createInjector(modules, config.strictDi);
injector.invoke(['$rootScope', '$rootElement', '$compile', '$injector',
function bootstrapApply(scope, element, compile, injector) {
scope.$apply(function() {
element.data('$injector', injector);
compile(element)(scope);
});
}]
);
return injector;
};
var NG_ENABLE_DEBUG_INFO = /^NG_ENABLE_DEBUG_INFO!/;
var NG_DEFER_BOOTSTRAP = /^NG_DEFER_BOOTSTRAP!/;
if (window && NG_ENABLE_DEBUG_INFO.test(window.name)) {
config.debugInfoEnabled = true;
window.name = window.name.replace(NG_ENABLE_DEBUG_INFO, '');
}
if (window && !NG_DEFER_BOOTSTRAP.test(window.name)) {
return doBootstrap();
}
window.name = window.name.replace(NG_DEFER_BOOTSTRAP, '');
angular.resumeBootstrap = function(extraModules) {
forEach(extraModules, function(module) {
modules.push(module);
});
return doBootstrap();
};
if (isFunction(angular.resumeDeferredBootstrap)) {
angular.resumeDeferredBootstrap();
}
}
/**
* @ngdoc function
* @name angular.reloadWithDebugInfo
* @module ng
* @description
* Use this function to reload the current application with debug information turned on.
* This takes precedence over a call to `$compileProvider.debugInfoEnabled(false)`.
*
* See {@link ng.$compileProvider#debugInfoEnabled} for more.
*/
function reloadWithDebugInfo() {
window.name = 'NG_ENABLE_DEBUG_INFO!' + window.name;
window.location.reload();
}
/**
* @name angular.getTestability
* @module ng
* @description
* Get the testability service for the instance of AngularJS on the given
* element.
* @param {DOMElement} element DOM element which is the root of AngularJS application.
*/
function getTestability(rootElement) {
var injector = angular.element(rootElement).injector();
if (!injector) {
throw ngMinErr('test',
'no injector found for element argument to getTestability');
}
return injector.get('$$testability');
}
var SNAKE_CASE_REGEXP = /[A-Z]/g;
function snake_case(name, separator) {
separator = separator || '_';
return name.replace(SNAKE_CASE_REGEXP, function(letter, pos) {
return (pos ? separator : '') + letter.toLowerCase();
});
}
var bindJQueryFired = false;
function bindJQuery() {
var originalCleanData;
if (bindJQueryFired) {
return;
}
// bind to jQuery if present;
var jqName = jq();
jQuery = isUndefined(jqName) ? window.jQuery : // use jQuery (if present)
!jqName ? undefined : // use jqLite
window[jqName]; // use jQuery specified by `ngJq`
// Use jQuery if it exists with proper functionality, otherwise default to us.
// AngularJS 1.2+ requires jQuery 1.7+ for on()/off() support.
// AngularJS 1.3+ technically requires at least jQuery 2.1+ but it may work with older
// versions. It will not work for sure with jQuery <1.7, though.
if (jQuery && jQuery.fn.on) {
jqLite = jQuery;
extend(jQuery.fn, {
scope: JQLitePrototype.scope,
isolateScope: JQLitePrototype.isolateScope,
controller: /** @type {?} */ (JQLitePrototype).controller,
injector: JQLitePrototype.injector,
inheritedData: JQLitePrototype.inheritedData
});
} else {
jqLite = JQLite;
}
// All nodes removed from the DOM via various jqLite/jQuery APIs like .remove()
// are passed through jqLite/jQuery.cleanData. Monkey-patch this method to fire
// the $destroy event on all removed nodes.
originalCleanData = jqLite.cleanData;
jqLite.cleanData = function(elems) {
var events;
for (var i = 0, elem; (elem = elems[i]) != null; i++) {
events = (jqLite._data(elem) || {}).events;
if (events && events.$destroy) {
jqLite(elem).triggerHandler('$destroy');
}
}
originalCleanData(elems);
};
angular.element = jqLite;
// Prevent double-proxying.
bindJQueryFired = true;
}
/**
* throw error if the argument is falsy.
*/
function assertArg(arg, name, reason) {
if (!arg) {
throw ngMinErr('areq', 'Argument \'{0}\' is {1}', (name || '?'), (reason || 'required'));
}
return arg;
}
function assertArgFn(arg, name, acceptArrayAnnotation) {
if (acceptArrayAnnotation && isArray(arg)) {
arg = arg[arg.length - 1];
}
assertArg(isFunction(arg), name, 'not a function, got ' +
(arg && typeof arg === 'object' ? arg.constructor.name || 'Object' : typeof arg));
return arg;
}
/**
* throw error if the name given is hasOwnProperty
* @param {String} name the name to test
* @param {String} context the context in which the name is used, such as module or directive
*/
function assertNotHasOwnProperty(name, context) {
if (name === 'hasOwnProperty') {
throw ngMinErr('badname', 'hasOwnProperty is not a valid {0} name', context);
}
}
/**
* Return the value accessible from the object by path. Any undefined traversals are ignored
* @param {Object} obj starting object
* @param {String} path path to traverse
* @param {boolean} [bindFnToScope=true]
* @returns {Object} value as accessible by path
*/
//TODO(misko): this function needs to be removed
function getter(obj, path, bindFnToScope) {
if (!path) return obj;
var keys = path.split('.');
var key;
var lastInstance = obj;
var len = keys.length;
for (var i = 0; i < len; i++) {
key = keys[i];
if (obj) {
obj = (lastInstance = obj)[key];
}
}
if (!bindFnToScope && isFunction(obj)) {
return bind(lastInstance, obj);
}
return obj;
}
/**
* Return the DOM siblings between the first and last node in the given array.
* @param {Array} array like object
* @returns {Array} the inputted object or a jqLite collection containing the nodes
*/
function getBlockNodes(nodes) {
// TODO(perf): update `nodes` instead of creating a new object?
var node = nodes[0];
var endNode = nodes[nodes.length - 1];
var blockNodes;
for (var i = 1; node !== endNode && (node = node.nextSibling); i++) {
if (blockNodes || nodes[i] !== node) {
if (!blockNodes) {
blockNodes = jqLite(slice.call(nodes, 0, i));
}
blockNodes.push(node);
}
}
return blockNodes || nodes;
}
/**
* Creates a new object without a prototype. This object is useful for lookup without having to
* guard against prototypically inherited properties via hasOwnProperty.
*
* Related micro-benchmarks:
* - http://jsperf.com/object-create2
* - http://jsperf.com/proto-map-lookup/2
* - http://jsperf.com/for-in-vs-object-keys2
*
* @returns {Object}
*/
function createMap() {
return Object.create(null);
}
function stringify(value) {
if (value == null) { // null || undefined
return '';
}
switch (typeof value) {
case 'string':
break;
case 'number':
value = '' + value;
break;
default:
if (hasCustomToString(value) && !isArray(value) && !isDate(value)) {
value = value.toString();
} else {
value = toJson(value);
}
}
return value;
}
var NODE_TYPE_ELEMENT = 1;
var NODE_TYPE_ATTRIBUTE = 2;
var NODE_TYPE_TEXT = 3;
var NODE_TYPE_COMMENT = 8;
var NODE_TYPE_DOCUMENT = 9;
var NODE_TYPE_DOCUMENT_FRAGMENT = 11;
/**
* @ngdoc type
* @name angular.Module
* @module ng
* @description
*
* Interface for configuring AngularJS {@link angular.module modules}.
*/
function setupModuleLoader(window) {
var $injectorMinErr = minErr('$injector');
var ngMinErr = minErr('ng');
function ensure(obj, name, factory) {
return obj[name] || (obj[name] = factory());
}
var angular = ensure(window, 'angular', Object);
// We need to expose `angular.$$minErr` to modules such as `ngResource` that reference it during bootstrap
angular.$$minErr = angular.$$minErr || minErr;
return ensure(angular, 'module', function() {
/** @type {Object.} */
var modules = {};
/**
* @ngdoc function
* @name angular.module
* @module ng
* @description
*
* The `angular.module` is a global place for creating, registering and retrieving AngularJS
* modules.
* All modules (AngularJS core or 3rd party) that should be available to an application must be
* registered using this mechanism.
*
* Passing one argument retrieves an existing {@link angular.Module},
* whereas passing more than one argument creates a new {@link angular.Module}
*
*
* # Module
*
* A module is a collection of services, directives, controllers, filters, and configuration information.
* `angular.module` is used to configure the {@link auto.$injector $injector}.
*
* ```js
* // Create a new module
* var myModule = angular.module('myModule', []);
*
* // register a new service
* myModule.value('appName', 'MyCoolApp');
*
* // configure existing services inside initialization blocks.
* myModule.config(['$locationProvider', function($locationProvider) {
* // Configure existing providers
* $locationProvider.hashPrefix('!');
* }]);
* ```
*
* Then you can create an injector and load your modules like this:
*
* ```js
* var injector = angular.injector(['ng', 'myModule'])
* ```
*
* However it's more likely that you'll just use
* {@link ng.directive:ngApp ngApp} or
* {@link angular.bootstrap} to simplify this process for you.
*
* @param {!string} name The name of the module to create or retrieve.
* @param {!Array.=} requires If specified then new module is being created. If
* unspecified then the module is being retrieved for further configuration.
* @param {Function=} configFn Optional configuration function for the module. Same as
* {@link angular.Module#config Module#config()}.
* @returns {angular.Module} new module with the {@link angular.Module} api.
*/
return function module(name, requires, configFn) {
var info = {};
var assertNotHasOwnProperty = function(name, context) {
if (name === 'hasOwnProperty') {
throw ngMinErr('badname', 'hasOwnProperty is not a valid {0} name', context);
}
};
assertNotHasOwnProperty(name, 'module');
if (requires && modules.hasOwnProperty(name)) {
modules[name] = null;
}
return ensure(modules, name, function() {
if (!requires) {
throw $injectorMinErr('nomod', 'Module \'{0}\' is not available! You either misspelled ' +
'the module name or forgot to load it. If registering a module ensure that you ' +
'specify the dependencies as the second argument.', name);
}
/** @type {!Array.>} */
var invokeQueue = [];
/** @type {!Array.} */
var configBlocks = [];
/** @type {!Array.} */
var runBlocks = [];
var config = invokeLater('$injector', 'invoke', 'push', configBlocks);
/** @type {angular.Module} */
var moduleInstance = {
// Private state
_invokeQueue: invokeQueue,
_configBlocks: configBlocks,
_runBlocks: runBlocks,
/**
* @ngdoc method
* @name angular.Module#info
* @module ng
*
* @param {Object=} info Information about the module
* @returns {Object|Module} The current info object for this module if called as a getter,
* or `this` if called as a setter.
*
* @description
* Read and write custom information about this module.
* For example you could put the version of the module in here.
*
* ```js
* angular.module('myModule', []).info({ version: '1.0.0' });
* ```
*
* The version could then be read back out by accessing the module elsewhere:
*
* ```
* var version = angular.module('myModule').info().version;
* ```
*
* You can also retrieve this information during runtime via the
* {@link $injector#modules `$injector.modules`} property:
*
* ```js
* var version = $injector.modules['myModule'].info().version;
* ```
*/
info: function(value) {
if (isDefined(value)) {
if (!isObject(value)) throw ngMinErr('aobj', 'Argument \'{0}\' must be an object', 'value');
info = value;
return this;
}
return info;
},
/**
* @ngdoc property
* @name angular.Module#requires
* @module ng
*
* @description
* Holds the list of modules which the injector will load before the current module is
* loaded.
*/
requires: requires,
/**
* @ngdoc property
* @name angular.Module#name
* @module ng
*
* @description
* Name of the module.
*/
name: name,
/**
* @ngdoc method
* @name angular.Module#provider
* @module ng
* @param {string} name service name
* @param {Function} providerType Construction function for creating new instance of the
* service.
* @description
* See {@link auto.$provide#provider $provide.provider()}.
*/
provider: invokeLaterAndSetModuleName('$provide', 'provider'),
/**
* @ngdoc method
* @name angular.Module#factory
* @module ng
* @param {string} name service name
* @param {Function} providerFunction Function for creating new instance of the service.
* @description
* See {@link auto.$provide#factory $provide.factory()}.
*/
factory: invokeLaterAndSetModuleName('$provide', 'factory'),
/**
* @ngdoc method
* @name angular.Module#service
* @module ng
* @param {string} name service name
* @param {Function} constructor A constructor function that will be instantiated.
* @description
* See {@link auto.$provide#service $provide.service()}.
*/
service: invokeLaterAndSetModuleName('$provide', 'service'),
/**
* @ngdoc method
* @name angular.Module#value
* @module ng
* @param {string} name service name
* @param {*} object Service instance object.
* @description
* See {@link auto.$provide#value $provide.value()}.
*/
value: invokeLater('$provide', 'value'),
/**
* @ngdoc method
* @name angular.Module#constant
* @module ng
* @param {string} name constant name
* @param {*} object Constant value.
* @description
* Because the constants are fixed, they get applied before other provide methods.
* See {@link auto.$provide#constant $provide.constant()}.
*/
constant: invokeLater('$provide', 'constant', 'unshift'),
/**
* @ngdoc method
* @name angular.Module#decorator
* @module ng
* @param {string} name The name of the service to decorate.
* @param {Function} decorFn This function will be invoked when the service needs to be
* instantiated and should return the decorated service instance.
* @description
* See {@link auto.$provide#decorator $provide.decorator()}.
*/
decorator: invokeLaterAndSetModuleName('$provide', 'decorator', configBlocks),
/**
* @ngdoc method
* @name angular.Module#animation
* @module ng
* @param {string} name animation name
* @param {Function} animationFactory Factory function for creating new instance of an
* animation.
* @description
*
* **NOTE**: animations take effect only if the **ngAnimate** module is loaded.
*
*
* Defines an animation hook that can be later used with
* {@link $animate $animate} service and directives that use this service.
*
* ```js
* module.animation('.animation-name', function($inject1, $inject2) {
* return {
* eventName : function(element, done) {
* //code to run the animation
* //once complete, then run done()
* return function cancellationFunction(element) {
* //code to cancel the animation
* }
* }
* }
* })
* ```
*
* See {@link ng.$animateProvider#register $animateProvider.register()} and
* {@link ngAnimate ngAnimate module} for more information.
*/
animation: invokeLaterAndSetModuleName('$animateProvider', 'register'),
/**
* @ngdoc method
* @name angular.Module#filter
* @module ng
* @param {string} name Filter name - this must be a valid AngularJS expression identifier
* @param {Function} filterFactory Factory function for creating new instance of filter.
* @description
* See {@link ng.$filterProvider#register $filterProvider.register()}.
*
*
* **Note:** Filter names must be valid AngularJS {@link expression} identifiers, such as `uppercase` or `orderBy`.
* Names with special characters, such as hyphens and dots, are not allowed. If you wish to namespace
* your filters, then you can use capitalization (`myappSubsectionFilterx`) or underscores
* (`myapp_subsection_filterx`).
*
*/
filter: invokeLaterAndSetModuleName('$filterProvider', 'register'),
/**
* @ngdoc method
* @name angular.Module#controller
* @module ng
* @param {string|Object} name Controller name, or an object map of controllers where the
* keys are the names and the values are the constructors.
* @param {Function} constructor Controller constructor function.
* @description
* See {@link ng.$controllerProvider#register $controllerProvider.register()}.
*/
controller: invokeLaterAndSetModuleName('$controllerProvider', 'register'),
/**
* @ngdoc method
* @name angular.Module#directive
* @module ng
* @param {string|Object} name Directive name, or an object map of directives where the
* keys are the names and the values are the factories.
* @param {Function} directiveFactory Factory function for creating new instance of
* directives.
* @description
* See {@link ng.$compileProvider#directive $compileProvider.directive()}.
*/
directive: invokeLaterAndSetModuleName('$compileProvider', 'directive'),
/**
* @ngdoc method
* @name angular.Module#component
* @module ng
* @param {string|Object} name Name of the component in camelCase (i.e. `myComp` which will match ``),
* or an object map of components where the keys are the names and the values are the component definition objects.
* @param {Object} options Component definition object (a simplified
* {@link ng.$compile#directive-definition-object directive definition object})
*
* @description
* See {@link ng.$compileProvider#component $compileProvider.component()}.
*/
component: invokeLaterAndSetModuleName('$compileProvider', 'component'),
/**
* @ngdoc method
* @name angular.Module#config
* @module ng
* @param {Function} configFn Execute this function on module load. Useful for service
* configuration.
* @description
* Use this method to configure services by injecting their
* {@link angular.Module#provider `providers`}, e.g. for adding routes to the
* {@link ngRoute.$routeProvider $routeProvider}.
*
* Note that you can only inject {@link angular.Module#provider `providers`} and
* {@link angular.Module#constant `constants`} into this function.
*
* For more about how to configure services, see
* {@link providers#provider-recipe Provider Recipe}.
*/
config: config,
/**
* @ngdoc method
* @name angular.Module#run
* @module ng
* @param {Function} initializationFn Execute this function after injector creation.
* Useful for application initialization.
* @description
* Use this method to register work which should be performed when the injector is done
* loading all modules.
*/
run: function(block) {
runBlocks.push(block);
return this;
}
};
if (configFn) {
config(configFn);
}
return moduleInstance;
/**
* @param {string} provider
* @param {string} method
* @param {String=} insertMethod
* @returns {angular.Module}
*/
function invokeLater(provider, method, insertMethod, queue) {
if (!queue) queue = invokeQueue;
return function() {
queue[insertMethod || 'push']([provider, method, arguments]);
return moduleInstance;
};
}
/**
* @param {string} provider
* @param {string} method
* @returns {angular.Module}
*/
function invokeLaterAndSetModuleName(provider, method, queue) {
if (!queue) queue = invokeQueue;
return function(recipeName, factoryFunction) {
if (factoryFunction && isFunction(factoryFunction)) factoryFunction.$$moduleName = name;
queue.push([provider, method, arguments]);
return moduleInstance;
};
}
});
};
});
}
/* global shallowCopy: true */
/**
* Creates a shallow copy of an object, an array or a primitive.
*
* Assumes that there are no proto properties for objects.
*/
function shallowCopy(src, dst) {
if (isArray(src)) {
dst = dst || [];
for (var i = 0, ii = src.length; i < ii; i++) {
dst[i] = src[i];
}
} else if (isObject(src)) {
dst = dst || {};
for (var key in src) {
if (!(key.charAt(0) === '$' && key.charAt(1) === '$')) {
dst[key] = src[key];
}
}
}
return dst || src;
}
/* exported toDebugString */
function serializeObject(obj, maxDepth) {
var seen = [];
// There is no direct way to stringify object until reaching a specific depth
// and a very deep object can cause a performance issue, so we copy the object
// based on this specific depth and then stringify it.
if (isValidObjectMaxDepth(maxDepth)) {
// This file is also included in `angular-loader`, so `copy()` might not always be available in
// the closure. Therefore, it is lazily retrieved as `angular.copy()` when needed.
obj = angular.copy(obj, null, maxDepth);
}
return JSON.stringify(obj, function(key, val) {
val = toJsonReplacer(key, val);
if (isObject(val)) {
if (seen.indexOf(val) >= 0) return '...';
seen.push(val);
}
return val;
});
}
function toDebugString(obj, maxDepth) {
if (typeof obj === 'function') {
return obj.toString().replace(/ \{[\s\S]*$/, '');
} else if (isUndefined(obj)) {
return 'undefined';
} else if (typeof obj !== 'string') {
return serializeObject(obj, maxDepth);
}
return obj;
}
/* global angularModule: true,
version: true,
$CompileProvider,
htmlAnchorDirective,
inputDirective,
hiddenInputBrowserCacheDirective,
formDirective,
scriptDirective,
selectDirective,
optionDirective,
ngBindDirective,
ngBindHtmlDirective,
ngBindTemplateDirective,
ngClassDirective,
ngClassEvenDirective,
ngClassOddDirective,
ngCloakDirective,
ngControllerDirective,
ngFormDirective,
ngHideDirective,
ngIfDirective,
ngIncludeDirective,
ngIncludeFillContentDirective,
ngInitDirective,
ngNonBindableDirective,
ngPluralizeDirective,
ngRefDirective,
ngRepeatDirective,
ngShowDirective,
ngStyleDirective,
ngSwitchDirective,
ngSwitchWhenDirective,
ngSwitchDefaultDirective,
ngOptionsDirective,
ngTranscludeDirective,
ngModelDirective,
ngListDirective,
ngChangeDirective,
patternDirective,
patternDirective,
requiredDirective,
requiredDirective,
minlengthDirective,
minlengthDirective,
maxlengthDirective,
maxlengthDirective,
ngValueDirective,
ngModelOptionsDirective,
ngAttributeAliasDirectives,
ngEventDirectives,
$AnchorScrollProvider,
$AnimateProvider,
$CoreAnimateCssProvider,
$$CoreAnimateJsProvider,
$$CoreAnimateQueueProvider,
$$AnimateRunnerFactoryProvider,
$$AnimateAsyncRunFactoryProvider,
$BrowserProvider,
$CacheFactoryProvider,
$ControllerProvider,
$DateProvider,
$DocumentProvider,
$$IsDocumentHiddenProvider,
$ExceptionHandlerProvider,
$FilterProvider,
$$ForceReflowProvider,
$InterpolateProvider,
$$IntervalFactoryProvider,
$IntervalProvider,
$HttpProvider,
$HttpParamSerializerProvider,
$HttpParamSerializerJQLikeProvider,
$HttpBackendProvider,
$xhrFactoryProvider,
$jsonpCallbacksProvider,
$LocationProvider,
$LogProvider,
$$MapProvider,
$ParseProvider,
$RootScopeProvider,
$QProvider,
$$QProvider,
$$SanitizeUriProvider,
$SceProvider,
$SceDelegateProvider,
$SnifferProvider,
$$TaskTrackerFactoryProvider,
$TemplateCacheProvider,
$TemplateRequestProvider,
$$TestabilityProvider,
$TimeoutProvider,
$$RAFProvider,
$WindowProvider,
$$jqLiteProvider,
$$CookieReaderProvider
*/
/**
* @ngdoc object
* @name angular.version
* @module ng
* @description
* An object that contains information about the current AngularJS version.
*
* This object has the following properties:
*
* - `full` – `{string}` – Full version string, such as "0.9.18".
* - `major` – `{number}` – Major version number, such as "0".
* - `minor` – `{number}` – Minor version number, such as "9".
* - `dot` – `{number}` – Dot version number, such as "18".
* - `codeName` – `{string}` – Code name of the release, such as "jiggling-armfat".
*/
var version = {
// These placeholder strings will be replaced by grunt's `build` task.
// They need to be double- or single-quoted.
full: '1.7.9',
major: 1,
minor: 7,
dot: 9,
codeName: 'pollution-eradication'
};
function publishExternalAPI(angular) {
extend(angular, {
'errorHandlingConfig': errorHandlingConfig,
'bootstrap': bootstrap,
'copy': copy,
'extend': extend,
'merge': merge,
'equals': equals,
'element': jqLite,
'forEach': forEach,
'injector': createInjector,
'noop': noop,
'bind': bind,
'toJson': toJson,
'fromJson': fromJson,
'identity': identity,
'isUndefined': isUndefined,
'isDefined': isDefined,
'isString': isString,
'isFunction': isFunction,
'isObject': isObject,
'isNumber': isNumber,
'isElement': isElement,
'isArray': isArray,
'version': version,
'isDate': isDate,
'callbacks': {$$counter: 0},
'getTestability': getTestability,
'reloadWithDebugInfo': reloadWithDebugInfo,
'$$minErr': minErr,
'$$csp': csp,
'$$encodeUriSegment': encodeUriSegment,
'$$encodeUriQuery': encodeUriQuery,
'$$lowercase': lowercase,
'$$stringify': stringify,
'$$uppercase': uppercase
});
angularModule = setupModuleLoader(window);
angularModule('ng', ['ngLocale'], ['$provide',
function ngModule($provide) {
// $$sanitizeUriProvider needs to be before $compileProvider as it is used by it.
$provide.provider({
$$sanitizeUri: $$SanitizeUriProvider
});
$provide.provider('$compile', $CompileProvider).
directive({
a: htmlAnchorDirective,
input: inputDirective,
textarea: inputDirective,
form: formDirective,
script: scriptDirective,
select: selectDirective,
option: optionDirective,
ngBind: ngBindDirective,
ngBindHtml: ngBindHtmlDirective,
ngBindTemplate: ngBindTemplateDirective,
ngClass: ngClassDirective,
ngClassEven: ngClassEvenDirective,
ngClassOdd: ngClassOddDirective,
ngCloak: ngCloakDirective,
ngController: ngControllerDirective,
ngForm: ngFormDirective,
ngHide: ngHideDirective,
ngIf: ngIfDirective,
ngInclude: ngIncludeDirective,
ngInit: ngInitDirective,
ngNonBindable: ngNonBindableDirective,
ngPluralize: ngPluralizeDirective,
ngRef: ngRefDirective,
ngRepeat: ngRepeatDirective,
ngShow: ngShowDirective,
ngStyle: ngStyleDirective,
ngSwitch: ngSwitchDirective,
ngSwitchWhen: ngSwitchWhenDirective,
ngSwitchDefault: ngSwitchDefaultDirective,
ngOptions: ngOptionsDirective,
ngTransclude: ngTranscludeDirective,
ngModel: ngModelDirective,
ngList: ngListDirective,
ngChange: ngChangeDirective,
pattern: patternDirective,
ngPattern: patternDirective,
required: requiredDirective,
ngRequired: requiredDirective,
minlength: minlengthDirective,
ngMinlength: minlengthDirective,
maxlength: maxlengthDirective,
ngMaxlength: maxlengthDirective,
ngValue: ngValueDirective,
ngModelOptions: ngModelOptionsDirective
}).
directive({
ngInclude: ngIncludeFillContentDirective,
input: hiddenInputBrowserCacheDirective
}).
directive(ngAttributeAliasDirectives).
directive(ngEventDirectives);
$provide.provider({
$anchorScroll: $AnchorScrollProvider,
$animate: $AnimateProvider,
$animateCss: $CoreAnimateCssProvider,
$$animateJs: $$CoreAnimateJsProvider,
$$animateQueue: $$CoreAnimateQueueProvider,
$$AnimateRunner: $$AnimateRunnerFactoryProvider,
$$animateAsyncRun: $$AnimateAsyncRunFactoryProvider,
$browser: $BrowserProvider,
$cacheFactory: $CacheFactoryProvider,
$controller: $ControllerProvider,
$document: $DocumentProvider,
$$isDocumentHidden: $$IsDocumentHiddenProvider,
$exceptionHandler: $ExceptionHandlerProvider,
$filter: $FilterProvider,
$$forceReflow: $$ForceReflowProvider,
$interpolate: $InterpolateProvider,
$interval: $IntervalProvider,
$$intervalFactory: $$IntervalFactoryProvider,
$http: $HttpProvider,
$httpParamSerializer: $HttpParamSerializerProvider,
$httpParamSerializerJQLike: $HttpParamSerializerJQLikeProvider,
$httpBackend: $HttpBackendProvider,
$xhrFactory: $xhrFactoryProvider,
$jsonpCallbacks: $jsonpCallbacksProvider,
$location: $LocationProvider,
$log: $LogProvider,
$parse: $ParseProvider,
$rootScope: $RootScopeProvider,
$q: $QProvider,
$$q: $$QProvider,
$sce: $SceProvider,
$sceDelegate: $SceDelegateProvider,
$sniffer: $SnifferProvider,
$$taskTrackerFactory: $$TaskTrackerFactoryProvider,
$templateCache: $TemplateCacheProvider,
$templateRequest: $TemplateRequestProvider,
$$testability: $$TestabilityProvider,
$timeout: $TimeoutProvider,
$window: $WindowProvider,
$$rAF: $$RAFProvider,
$$jqLite: $$jqLiteProvider,
$$Map: $$MapProvider,
$$cookieReader: $$CookieReaderProvider
});
}
])
.info({ angularVersion: '1.7.9' });
}
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Any commits to this file should be reviewed with security in mind. *
* Changes to this file can potentially create security vulnerabilities. *
* An approval from 2 Core members with history of modifying *
* this file is required. *
* *
* Does the change somehow allow for arbitrary javascript to be executed? *
* Or allows for someone to change the prototype of built-in objects? *
* Or gives undesired access to variables likes document or window? *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/* global
JQLitePrototype: true,
BOOLEAN_ATTR: true,
ALIASED_ATTR: true
*/
//////////////////////////////////
//JQLite
//////////////////////////////////
/**
* @ngdoc function
* @name angular.element
* @module ng
* @kind function
*
* @description
* Wraps a raw DOM element or HTML string as a [jQuery](http://jquery.com) element.
*
* If jQuery is available, `angular.element` is an alias for the
* [jQuery](http://api.jquery.com/jQuery/) function. If jQuery is not available, `angular.element`
* delegates to AngularJS's built-in subset of jQuery, called "jQuery lite" or **jqLite**.
*
* jqLite is a tiny, API-compatible subset of jQuery that allows
* AngularJS to manipulate the DOM in a cross-browser compatible way. jqLite implements only the most
* commonly needed functionality with the goal of having a very small footprint.
*
* To use `jQuery`, simply ensure it is loaded before the `angular.js` file. You can also use the
* {@link ngJq `ngJq`} directive to specify that jqlite should be used over jQuery, or to use a
* specific version of jQuery if multiple versions exist on the page.
*
*
**Note:** All element references in AngularJS are always wrapped with jQuery or
* jqLite (such as the element argument in a directive's compile / link function). They are never raw DOM references.
*
*
**Note:** Keep in mind that this function will not find elements
* by tag name / CSS selector. For lookups by tag name, try instead `angular.element(document).find(...)`
* or `$document.find()`, or use the standard DOM APIs, e.g. `document.querySelectorAll()`.
*
* ## AngularJS's jqLite
* jqLite provides only the following jQuery methods:
*
* - [`addClass()`](http://api.jquery.com/addClass/) - Does not support a function as first argument
* - [`after()`](http://api.jquery.com/after/)
* - [`append()`](http://api.jquery.com/append/) - Contrary to jQuery, this doesn't clone elements
* so will not work correctly when invoked on a jqLite object containing more than one DOM node
* - [`attr()`](http://api.jquery.com/attr/) - Does not support functions as parameters
* - [`bind()`](http://api.jquery.com/bind/) (_deprecated_, use [`on()`](http://api.jquery.com/on/)) - Does not support namespaces, selectors or eventData
* - [`children()`](http://api.jquery.com/children/) - Does not support selectors
* - [`clone()`](http://api.jquery.com/clone/)
* - [`contents()`](http://api.jquery.com/contents/)
* - [`css()`](http://api.jquery.com/css/) - Only retrieves inline-styles, does not call `getComputedStyle()`.
* As a setter, does not convert numbers to strings or append 'px', and also does not have automatic property prefixing.
* - [`data()`](http://api.jquery.com/data/)
* - [`detach()`](http://api.jquery.com/detach/)
* - [`empty()`](http://api.jquery.com/empty/)
* - [`eq()`](http://api.jquery.com/eq/)
* - [`find()`](http://api.jquery.com/find/) - Limited to lookups by tag name
* - [`hasClass()`](http://api.jquery.com/hasClass/)
* - [`html()`](http://api.jquery.com/html/)
* - [`next()`](http://api.jquery.com/next/) - Does not support selectors
* - [`on()`](http://api.jquery.com/on/) - Does not support namespaces, selectors or eventData
* - [`off()`](http://api.jquery.com/off/) - Does not support namespaces, selectors or event object as parameter
* - [`one()`](http://api.jquery.com/one/) - Does not support namespaces or selectors
* - [`parent()`](http://api.jquery.com/parent/) - Does not support selectors
* - [`prepend()`](http://api.jquery.com/prepend/)
* - [`prop()`](http://api.jquery.com/prop/)
* - [`ready()`](http://api.jquery.com/ready/) (_deprecated_, use `angular.element(callback)` instead of `angular.element(document).ready(callback)`)
* - [`remove()`](http://api.jquery.com/remove/)
* - [`removeAttr()`](http://api.jquery.com/removeAttr/) - Does not support multiple attributes
* - [`removeClass()`](http://api.jquery.com/removeClass/) - Does not support a function as first argument
* - [`removeData()`](http://api.jquery.com/removeData/)
* - [`replaceWith()`](http://api.jquery.com/replaceWith/)
* - [`text()`](http://api.jquery.com/text/)
* - [`toggleClass()`](http://api.jquery.com/toggleClass/) - Does not support a function as first argument
* - [`triggerHandler()`](http://api.jquery.com/triggerHandler/) - Passes a dummy event object to handlers
* - [`unbind()`](http://api.jquery.com/unbind/) (_deprecated_, use [`off()`](http://api.jquery.com/off/)) - Does not support namespaces or event object as parameter
* - [`val()`](http://api.jquery.com/val/)
* - [`wrap()`](http://api.jquery.com/wrap/)
*
* ## jQuery/jqLite Extras
* AngularJS also provides the following additional methods and events to both jQuery and jqLite:
*
* ### Events
* - `$destroy` - AngularJS intercepts all jqLite/jQuery's DOM destruction apis and fires this event
* on all DOM nodes being removed. This can be used to clean up any 3rd party bindings to the DOM
* element before it is removed.
*
* ### Methods
* - `controller(name)` - retrieves the controller of the current element or its parent. By default
* retrieves controller associated with the `ngController` directive. If `name` is provided as
* camelCase directive name, then the controller for this directive will be retrieved (e.g.
* `'ngModel'`).
* - `injector()` - retrieves the injector of the current element or its parent.
* - `scope()` - retrieves the {@link ng.$rootScope.Scope scope} of the current
* element or its parent. Requires {@link guide/production#disabling-debug-data Debug Data} to
* be enabled.
* - `isolateScope()` - retrieves an isolate {@link ng.$rootScope.Scope scope} if one is attached directly to the
* current element. This getter should be used only on elements that contain a directive which starts a new isolate
* scope. Calling `scope()` on this element always returns the original non-isolate scope.
* Requires {@link guide/production#disabling-debug-data Debug Data} to be enabled.
* - `inheritedData()` - same as `data()`, but walks up the DOM until a value is found or the top
* parent element is reached.
*
* @knownIssue You cannot spy on `angular.element` if you are using Jasmine version 1.x. See
* https://github.com/angular/angular.js/issues/14251 for more information.
*
* @param {string|DOMElement} element HTML string or DOMElement to be wrapped into jQuery.
* @returns {Object} jQuery object.
*/
JQLite.expando = 'ng339';
var jqCache = JQLite.cache = {},
jqId = 1;
/*
* !!! This is an undocumented "private" function !!!
*/
JQLite._data = function(node) {
//jQuery always returns an object on cache miss
return this.cache[node[this.expando]] || {};
};
function jqNextId() { return ++jqId; }
var DASH_LOWERCASE_REGEXP = /-([a-z])/g;
var MS_HACK_REGEXP = /^-ms-/;
var MOUSE_EVENT_MAP = { mouseleave: 'mouseout', mouseenter: 'mouseover' };
var jqLiteMinErr = minErr('jqLite');
/**
* Converts kebab-case to camelCase.
* There is also a special case for the ms prefix starting with a lowercase letter.
* @param name Name to normalize
*/
function cssKebabToCamel(name) {
return kebabToCamel(name.replace(MS_HACK_REGEXP, 'ms-'));
}
function fnCamelCaseReplace(all, letter) {
return letter.toUpperCase();
}
/**
* Converts kebab-case to camelCase.
* @param name Name to normalize
*/
function kebabToCamel(name) {
return name
.replace(DASH_LOWERCASE_REGEXP, fnCamelCaseReplace);
}
var SINGLE_TAG_REGEXP = /^<([\w-]+)\s*\/?>(?:<\/\1>|)$/;
var HTML_REGEXP = /<|?\w+;/;
var TAG_NAME_REGEXP = /<([\w:-]+)/;
var XHTML_TAG_REGEXP = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:-]+)[^>]*)\/>/gi;
var wrapMap = {
'option': [1, ''],
'thead': [1, '
', '
'],
'col': [2, '
', '
'],
'tr': [2, '
', '
'],
'td': [3, '
', '
'],
'_default': [0, '', '']
};
wrapMap.optgroup = wrapMap.option;
wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead;
wrapMap.th = wrapMap.td;
function jqLiteIsTextNode(html) {
return !HTML_REGEXP.test(html);
}
function jqLiteAcceptsData(node) {
// The window object can accept data but has no nodeType
// Otherwise we are only interested in elements (1) and documents (9)
var nodeType = node.nodeType;
return nodeType === NODE_TYPE_ELEMENT || !nodeType || nodeType === NODE_TYPE_DOCUMENT;
}
function jqLiteHasData(node) {
for (var key in jqCache[node.ng339]) {
return true;
}
return false;
}
function jqLiteBuildFragment(html, context) {
var tmp, tag, wrap,
fragment = context.createDocumentFragment(),
nodes = [], i;
if (jqLiteIsTextNode(html)) {
// Convert non-html into a text node
nodes.push(context.createTextNode(html));
} else {
// Convert html into DOM nodes
tmp = fragment.appendChild(context.createElement('div'));
tag = (TAG_NAME_REGEXP.exec(html) || ['', ''])[1].toLowerCase();
wrap = wrapMap[tag] || wrapMap._default;
tmp.innerHTML = wrap[1] + html.replace(XHTML_TAG_REGEXP, '<$1>$2>') + wrap[2];
// Descend through wrappers to the right content
i = wrap[0];
while (i--) {
tmp = tmp.lastChild;
}
nodes = concat(nodes, tmp.childNodes);
tmp = fragment.firstChild;
tmp.textContent = '';
}
// Remove wrapper from fragment
fragment.textContent = '';
fragment.innerHTML = ''; // Clear inner HTML
forEach(nodes, function(node) {
fragment.appendChild(node);
});
return fragment;
}
function jqLiteParseHTML(html, context) {
context = context || window.document;
var parsed;
if ((parsed = SINGLE_TAG_REGEXP.exec(html))) {
return [context.createElement(parsed[1])];
}
if ((parsed = jqLiteBuildFragment(html, context))) {
return parsed.childNodes;
}
return [];
}
function jqLiteWrapNode(node, wrapper) {
var parent = node.parentNode;
if (parent) {
parent.replaceChild(wrapper, node);
}
wrapper.appendChild(node);
}
// IE9-11 has no method "contains" in SVG element and in Node.prototype. Bug #10259.
var jqLiteContains = window.Node.prototype.contains || /** @this */ function(arg) {
// eslint-disable-next-line no-bitwise
return !!(this.compareDocumentPosition(arg) & 16);
};
/////////////////////////////////////////////
function JQLite(element) {
if (element instanceof JQLite) {
return element;
}
var argIsString;
if (isString(element)) {
element = trim(element);
argIsString = true;
}
if (!(this instanceof JQLite)) {
if (argIsString && element.charAt(0) !== '<') {
throw jqLiteMinErr('nosel', 'Looking up elements via selectors is not supported by jqLite! See: http://docs.angularjs.org/api/angular.element');
}
return new JQLite(element);
}
if (argIsString) {
jqLiteAddNodes(this, jqLiteParseHTML(element));
} else if (isFunction(element)) {
jqLiteReady(element);
} else {
jqLiteAddNodes(this, element);
}
}
function jqLiteClone(element) {
return element.cloneNode(true);
}
function jqLiteDealoc(element, onlyDescendants) {
if (!onlyDescendants && jqLiteAcceptsData(element)) jqLite.cleanData([element]);
if (element.querySelectorAll) {
jqLite.cleanData(element.querySelectorAll('*'));
}
}
function isEmptyObject(obj) {
var name;
for (name in obj) {
return false;
}
return true;
}
function removeIfEmptyData(element) {
var expandoId = element.ng339;
var expandoStore = expandoId && jqCache[expandoId];
var events = expandoStore && expandoStore.events;
var data = expandoStore && expandoStore.data;
if ((!data || isEmptyObject(data)) && (!events || isEmptyObject(events))) {
delete jqCache[expandoId];
element.ng339 = undefined; // don't delete DOM expandos. IE and Chrome don't like it
}
}
function jqLiteOff(element, type, fn, unsupported) {
if (isDefined(unsupported)) throw jqLiteMinErr('offargs', 'jqLite#off() does not support the `selector` argument');
var expandoStore = jqLiteExpandoStore(element);
var events = expandoStore && expandoStore.events;
var handle = expandoStore && expandoStore.handle;
if (!handle) return; //no listeners registered
if (!type) {
for (type in events) {
if (type !== '$destroy') {
element.removeEventListener(type, handle);
}
delete events[type];
}
} else {
var removeHandler = function(type) {
var listenerFns = events[type];
if (isDefined(fn)) {
arrayRemove(listenerFns || [], fn);
}
if (!(isDefined(fn) && listenerFns && listenerFns.length > 0)) {
element.removeEventListener(type, handle);
delete events[type];
}
};
forEach(type.split(' '), function(type) {
removeHandler(type);
if (MOUSE_EVENT_MAP[type]) {
removeHandler(MOUSE_EVENT_MAP[type]);
}
});
}
removeIfEmptyData(element);
}
function jqLiteRemoveData(element, name) {
var expandoId = element.ng339;
var expandoStore = expandoId && jqCache[expandoId];
if (expandoStore) {
if (name) {
delete expandoStore.data[name];
} else {
expandoStore.data = {};
}
removeIfEmptyData(element);
}
}
function jqLiteExpandoStore(element, createIfNecessary) {
var expandoId = element.ng339,
expandoStore = expandoId && jqCache[expandoId];
if (createIfNecessary && !expandoStore) {
element.ng339 = expandoId = jqNextId();
expandoStore = jqCache[expandoId] = {events: {}, data: {}, handle: undefined};
}
return expandoStore;
}
function jqLiteData(element, key, value) {
if (jqLiteAcceptsData(element)) {
var prop;
var isSimpleSetter = isDefined(value);
var isSimpleGetter = !isSimpleSetter && key && !isObject(key);
var massGetter = !key;
var expandoStore = jqLiteExpandoStore(element, !isSimpleGetter);
var data = expandoStore && expandoStore.data;
if (isSimpleSetter) { // data('key', value)
data[kebabToCamel(key)] = value;
} else {
if (massGetter) { // data()
return data;
} else {
if (isSimpleGetter) { // data('key')
// don't force creation of expandoStore if it doesn't exist yet
return data && data[kebabToCamel(key)];
} else { // mass-setter: data({key1: val1, key2: val2})
for (prop in key) {
data[kebabToCamel(prop)] = key[prop];
}
}
}
}
}
}
function jqLiteHasClass(element, selector) {
if (!element.getAttribute) return false;
return ((' ' + (element.getAttribute('class') || '') + ' ').replace(/[\n\t]/g, ' ').
indexOf(' ' + selector + ' ') > -1);
}
function jqLiteRemoveClass(element, cssClasses) {
if (cssClasses && element.setAttribute) {
var existingClasses = (' ' + (element.getAttribute('class') || '') + ' ')
.replace(/[\n\t]/g, ' ');
var newClasses = existingClasses;
forEach(cssClasses.split(' '), function(cssClass) {
cssClass = trim(cssClass);
newClasses = newClasses.replace(' ' + cssClass + ' ', ' ');
});
if (newClasses !== existingClasses) {
element.setAttribute('class', trim(newClasses));
}
}
}
function jqLiteAddClass(element, cssClasses) {
if (cssClasses && element.setAttribute) {
var existingClasses = (' ' + (element.getAttribute('class') || '') + ' ')
.replace(/[\n\t]/g, ' ');
var newClasses = existingClasses;
forEach(cssClasses.split(' '), function(cssClass) {
cssClass = trim(cssClass);
if (newClasses.indexOf(' ' + cssClass + ' ') === -1) {
newClasses += cssClass + ' ';
}
});
if (newClasses !== existingClasses) {
element.setAttribute('class', trim(newClasses));
}
}
}
function jqLiteAddNodes(root, elements) {
// THIS CODE IS VERY HOT. Don't make changes without benchmarking.
if (elements) {
// if a Node (the most common case)
if (elements.nodeType) {
root[root.length++] = elements;
} else {
var length = elements.length;
// if an Array or NodeList and not a Window
if (typeof length === 'number' && elements.window !== elements) {
if (length) {
for (var i = 0; i < length; i++) {
root[root.length++] = elements[i];
}
}
} else {
root[root.length++] = elements;
}
}
}
}
function jqLiteController(element, name) {
return jqLiteInheritedData(element, '$' + (name || 'ngController') + 'Controller');
}
function jqLiteInheritedData(element, name, value) {
// if element is the document object work with the html element instead
// this makes $(document).scope() possible
if (element.nodeType === NODE_TYPE_DOCUMENT) {
element = element.documentElement;
}
var names = isArray(name) ? name : [name];
while (element) {
for (var i = 0, ii = names.length; i < ii; i++) {
if (isDefined(value = jqLite.data(element, names[i]))) return value;
}
// If dealing with a document fragment node with a host element, and no parent, use the host
// element as the parent. This enables directives within a Shadow DOM or polyfilled Shadow DOM
// to lookup parent controllers.
element = element.parentNode || (element.nodeType === NODE_TYPE_DOCUMENT_FRAGMENT && element.host);
}
}
function jqLiteEmpty(element) {
jqLiteDealoc(element, true);
while (element.firstChild) {
element.removeChild(element.firstChild);
}
}
function jqLiteRemove(element, keepData) {
if (!keepData) jqLiteDealoc(element);
var parent = element.parentNode;
if (parent) parent.removeChild(element);
}
function jqLiteDocumentLoaded(action, win) {
win = win || window;
if (win.document.readyState === 'complete') {
// Force the action to be run async for consistent behavior
// from the action's point of view
// i.e. it will definitely not be in a $apply
win.setTimeout(action);
} else {
// No need to unbind this handler as load is only ever called once
jqLite(win).on('load', action);
}
}
function jqLiteReady(fn) {
function trigger() {
window.document.removeEventListener('DOMContentLoaded', trigger);
window.removeEventListener('load', trigger);
fn();
}
// check if document is already loaded
if (window.document.readyState === 'complete') {
window.setTimeout(fn);
} else {
// We can not use jqLite since we are not done loading and jQuery could be loaded later.
// Works for modern browsers and IE9
window.document.addEventListener('DOMContentLoaded', trigger);
// Fallback to window.onload for others
window.addEventListener('load', trigger);
}
}
//////////////////////////////////////////
// Functions which are declared directly.
//////////////////////////////////////////
var JQLitePrototype = JQLite.prototype = {
ready: jqLiteReady,
toString: function() {
var value = [];
forEach(this, function(e) { value.push('' + e);});
return '[' + value.join(', ') + ']';
},
eq: function(index) {
return (index >= 0) ? jqLite(this[index]) : jqLite(this[this.length + index]);
},
length: 0,
push: push,
sort: [].sort,
splice: [].splice
};
//////////////////////////////////////////
// Functions iterating getter/setters.
// these functions return self on setter and
// value on get.
//////////////////////////////////////////
var BOOLEAN_ATTR = {};
forEach('multiple,selected,checked,disabled,readOnly,required,open'.split(','), function(value) {
BOOLEAN_ATTR[lowercase(value)] = value;
});
var BOOLEAN_ELEMENTS = {};
forEach('input,select,option,textarea,button,form,details'.split(','), function(value) {
BOOLEAN_ELEMENTS[value] = true;
});
var ALIASED_ATTR = {
'ngMinlength': 'minlength',
'ngMaxlength': 'maxlength',
'ngMin': 'min',
'ngMax': 'max',
'ngPattern': 'pattern',
'ngStep': 'step'
};
function getBooleanAttrName(element, name) {
// check dom last since we will most likely fail on name
var booleanAttr = BOOLEAN_ATTR[name.toLowerCase()];
// booleanAttr is here twice to minimize DOM access
return booleanAttr && BOOLEAN_ELEMENTS[nodeName_(element)] && booleanAttr;
}
function getAliasedAttrName(name) {
return ALIASED_ATTR[name];
}
forEach({
data: jqLiteData,
removeData: jqLiteRemoveData,
hasData: jqLiteHasData,
cleanData: function jqLiteCleanData(nodes) {
for (var i = 0, ii = nodes.length; i < ii; i++) {
jqLiteRemoveData(nodes[i]);
jqLiteOff(nodes[i]);
}
}
}, function(fn, name) {
JQLite[name] = fn;
});
forEach({
data: jqLiteData,
inheritedData: jqLiteInheritedData,
scope: function(element) {
// Can't use jqLiteData here directly so we stay compatible with jQuery!
return jqLite.data(element, '$scope') || jqLiteInheritedData(element.parentNode || element, ['$isolateScope', '$scope']);
},
isolateScope: function(element) {
// Can't use jqLiteData here directly so we stay compatible with jQuery!
return jqLite.data(element, '$isolateScope') || jqLite.data(element, '$isolateScopeNoTemplate');
},
controller: jqLiteController,
injector: function(element) {
return jqLiteInheritedData(element, '$injector');
},
removeAttr: function(element, name) {
element.removeAttribute(name);
},
hasClass: jqLiteHasClass,
css: function(element, name, value) {
name = cssKebabToCamel(name);
if (isDefined(value)) {
element.style[name] = value;
} else {
return element.style[name];
}
},
attr: function(element, name, value) {
var ret;
var nodeType = element.nodeType;
if (nodeType === NODE_TYPE_TEXT || nodeType === NODE_TYPE_ATTRIBUTE || nodeType === NODE_TYPE_COMMENT ||
!element.getAttribute) {
return;
}
var lowercasedName = lowercase(name);
var isBooleanAttr = BOOLEAN_ATTR[lowercasedName];
if (isDefined(value)) {
// setter
if (value === null || (value === false && isBooleanAttr)) {
element.removeAttribute(name);
} else {
element.setAttribute(name, isBooleanAttr ? lowercasedName : value);
}
} else {
// getter
ret = element.getAttribute(name);
if (isBooleanAttr && ret !== null) {
ret = lowercasedName;
}
// Normalize non-existing attributes to undefined (as jQuery).
return ret === null ? undefined : ret;
}
},
prop: function(element, name, value) {
if (isDefined(value)) {
element[name] = value;
} else {
return element[name];
}
},
text: (function() {
getText.$dv = '';
return getText;
function getText(element, value) {
if (isUndefined(value)) {
var nodeType = element.nodeType;
return (nodeType === NODE_TYPE_ELEMENT || nodeType === NODE_TYPE_TEXT) ? element.textContent : '';
}
element.textContent = value;
}
})(),
val: function(element, value) {
if (isUndefined(value)) {
if (element.multiple && nodeName_(element) === 'select') {
var result = [];
forEach(element.options, function(option) {
if (option.selected) {
result.push(option.value || option.text);
}
});
return result;
}
return element.value;
}
element.value = value;
},
html: function(element, value) {
if (isUndefined(value)) {
return element.innerHTML;
}
jqLiteDealoc(element, true);
element.innerHTML = value;
},
empty: jqLiteEmpty
}, function(fn, name) {
/**
* Properties: writes return selection, reads return first value
*/
JQLite.prototype[name] = function(arg1, arg2) {
var i, key;
var nodeCount = this.length;
// jqLiteHasClass has only two arguments, but is a getter-only fn, so we need to special-case it
// in a way that survives minification.
// jqLiteEmpty takes no arguments but is a setter.
if (fn !== jqLiteEmpty &&
(isUndefined((fn.length === 2 && (fn !== jqLiteHasClass && fn !== jqLiteController)) ? arg1 : arg2))) {
if (isObject(arg1)) {
// we are a write, but the object properties are the key/values
for (i = 0; i < nodeCount; i++) {
if (fn === jqLiteData) {
// data() takes the whole object in jQuery
fn(this[i], arg1);
} else {
for (key in arg1) {
fn(this[i], key, arg1[key]);
}
}
}
// return self for chaining
return this;
} else {
// we are a read, so read the first child.
// TODO: do we still need this?
var value = fn.$dv;
// Only if we have $dv do we iterate over all, otherwise it is just the first element.
var jj = (isUndefined(value)) ? Math.min(nodeCount, 1) : nodeCount;
for (var j = 0; j < jj; j++) {
var nodeValue = fn(this[j], arg1, arg2);
value = value ? value + nodeValue : nodeValue;
}
return value;
}
} else {
// we are a write, so apply to all children
for (i = 0; i < nodeCount; i++) {
fn(this[i], arg1, arg2);
}
// return self for chaining
return this;
}
};
});
function createEventHandler(element, events) {
var eventHandler = function(event, type) {
// jQuery specific api
event.isDefaultPrevented = function() {
return event.defaultPrevented;
};
var eventFns = events[type || event.type];
var eventFnsLength = eventFns ? eventFns.length : 0;
if (!eventFnsLength) return;
if (isUndefined(event.immediatePropagationStopped)) {
var originalStopImmediatePropagation = event.stopImmediatePropagation;
event.stopImmediatePropagation = function() {
event.immediatePropagationStopped = true;
if (event.stopPropagation) {
event.stopPropagation();
}
if (originalStopImmediatePropagation) {
originalStopImmediatePropagation.call(event);
}
};
}
event.isImmediatePropagationStopped = function() {
return event.immediatePropagationStopped === true;
};
// Some events have special handlers that wrap the real handler
var handlerWrapper = eventFns.specialHandlerWrapper || defaultHandlerWrapper;
// Copy event handlers in case event handlers array is modified during execution.
if ((eventFnsLength > 1)) {
eventFns = shallowCopy(eventFns);
}
for (var i = 0; i < eventFnsLength; i++) {
if (!event.isImmediatePropagationStopped()) {
handlerWrapper(element, event, eventFns[i]);
}
}
};
// TODO: this is a hack for angularMocks/clearDataCache that makes it possible to deregister all
// events on `element`
eventHandler.elem = element;
return eventHandler;
}
function defaultHandlerWrapper(element, event, handler) {
handler.call(element, event);
}
function specialMouseHandlerWrapper(target, event, handler) {
// Refer to jQuery's implementation of mouseenter & mouseleave
// Read about mouseenter and mouseleave:
// http://www.quirksmode.org/js/events_mouse.html#link8
var related = event.relatedTarget;
// For mousenter/leave call the handler if related is outside the target.
// NB: No relatedTarget if the mouse left/entered the browser window
if (!related || (related !== target && !jqLiteContains.call(target, related))) {
handler.call(target, event);
}
}
//////////////////////////////////////////
// Functions iterating traversal.
// These functions chain results into a single
// selector.
//////////////////////////////////////////
forEach({
removeData: jqLiteRemoveData,
on: function jqLiteOn(element, type, fn, unsupported) {
if (isDefined(unsupported)) throw jqLiteMinErr('onargs', 'jqLite#on() does not support the `selector` or `eventData` parameters');
// Do not add event handlers to non-elements because they will not be cleaned up.
if (!jqLiteAcceptsData(element)) {
return;
}
var expandoStore = jqLiteExpandoStore(element, true);
var events = expandoStore.events;
var handle = expandoStore.handle;
if (!handle) {
handle = expandoStore.handle = createEventHandler(element, events);
}
// http://jsperf.com/string-indexof-vs-split
var types = type.indexOf(' ') >= 0 ? type.split(' ') : [type];
var i = types.length;
var addHandler = function(type, specialHandlerWrapper, noEventListener) {
var eventFns = events[type];
if (!eventFns) {
eventFns = events[type] = [];
eventFns.specialHandlerWrapper = specialHandlerWrapper;
if (type !== '$destroy' && !noEventListener) {
element.addEventListener(type, handle);
}
}
eventFns.push(fn);
};
while (i--) {
type = types[i];
if (MOUSE_EVENT_MAP[type]) {
addHandler(MOUSE_EVENT_MAP[type], specialMouseHandlerWrapper);
addHandler(type, undefined, true);
} else {
addHandler(type);
}
}
},
off: jqLiteOff,
one: function(element, type, fn) {
element = jqLite(element);
//add the listener twice so that when it is called
//you can remove the original function and still be
//able to call element.off(ev, fn) normally
element.on(type, function onFn() {
element.off(type, fn);
element.off(type, onFn);
});
element.on(type, fn);
},
replaceWith: function(element, replaceNode) {
var index, parent = element.parentNode;
jqLiteDealoc(element);
forEach(new JQLite(replaceNode), function(node) {
if (index) {
parent.insertBefore(node, index.nextSibling);
} else {
parent.replaceChild(node, element);
}
index = node;
});
},
children: function(element) {
var children = [];
forEach(element.childNodes, function(element) {
if (element.nodeType === NODE_TYPE_ELEMENT) {
children.push(element);
}
});
return children;
},
contents: function(element) {
return element.contentDocument || element.childNodes || [];
},
append: function(element, node) {
var nodeType = element.nodeType;
if (nodeType !== NODE_TYPE_ELEMENT && nodeType !== NODE_TYPE_DOCUMENT_FRAGMENT) return;
node = new JQLite(node);
for (var i = 0, ii = node.length; i < ii; i++) {
var child = node[i];
element.appendChild(child);
}
},
prepend: function(element, node) {
if (element.nodeType === NODE_TYPE_ELEMENT) {
var index = element.firstChild;
forEach(new JQLite(node), function(child) {
element.insertBefore(child, index);
});
}
},
wrap: function(element, wrapNode) {
jqLiteWrapNode(element, jqLite(wrapNode).eq(0).clone()[0]);
},
remove: jqLiteRemove,
detach: function(element) {
jqLiteRemove(element, true);
},
after: function(element, newElement) {
var index = element, parent = element.parentNode;
if (parent) {
newElement = new JQLite(newElement);
for (var i = 0, ii = newElement.length; i < ii; i++) {
var node = newElement[i];
parent.insertBefore(node, index.nextSibling);
index = node;
}
}
},
addClass: jqLiteAddClass,
removeClass: jqLiteRemoveClass,
toggleClass: function(element, selector, condition) {
if (selector) {
forEach(selector.split(' '), function(className) {
var classCondition = condition;
if (isUndefined(classCondition)) {
classCondition = !jqLiteHasClass(element, className);
}
(classCondition ? jqLiteAddClass : jqLiteRemoveClass)(element, className);
});
}
},
parent: function(element) {
var parent = element.parentNode;
return parent && parent.nodeType !== NODE_TYPE_DOCUMENT_FRAGMENT ? parent : null;
},
next: function(element) {
return element.nextElementSibling;
},
find: function(element, selector) {
if (element.getElementsByTagName) {
return element.getElementsByTagName(selector);
} else {
return [];
}
},
clone: jqLiteClone,
triggerHandler: function(element, event, extraParameters) {
var dummyEvent, eventFnsCopy, handlerArgs;
var eventName = event.type || event;
var expandoStore = jqLiteExpandoStore(element);
var events = expandoStore && expandoStore.events;
var eventFns = events && events[eventName];
if (eventFns) {
// Create a dummy event to pass to the handlers
dummyEvent = {
preventDefault: function() { this.defaultPrevented = true; },
isDefaultPrevented: function() { return this.defaultPrevented === true; },
stopImmediatePropagation: function() { this.immediatePropagationStopped = true; },
isImmediatePropagationStopped: function() { return this.immediatePropagationStopped === true; },
stopPropagation: noop,
type: eventName,
target: element
};
// If a custom event was provided then extend our dummy event with it
if (event.type) {
dummyEvent = extend(dummyEvent, event);
}
// Copy event handlers in case event handlers array is modified during execution.
eventFnsCopy = shallowCopy(eventFns);
handlerArgs = extraParameters ? [dummyEvent].concat(extraParameters) : [dummyEvent];
forEach(eventFnsCopy, function(fn) {
if (!dummyEvent.isImmediatePropagationStopped()) {
fn.apply(element, handlerArgs);
}
});
}
}
}, function(fn, name) {
/**
* chaining functions
*/
JQLite.prototype[name] = function(arg1, arg2, arg3) {
var value;
for (var i = 0, ii = this.length; i < ii; i++) {
if (isUndefined(value)) {
value = fn(this[i], arg1, arg2, arg3);
if (isDefined(value)) {
// any function which returns a value needs to be wrapped
value = jqLite(value);
}
} else {
jqLiteAddNodes(value, fn(this[i], arg1, arg2, arg3));
}
}
return isDefined(value) ? value : this;
};
});
// bind legacy bind/unbind to on/off
JQLite.prototype.bind = JQLite.prototype.on;
JQLite.prototype.unbind = JQLite.prototype.off;
// Provider for private $$jqLite service
/** @this */
function $$jqLiteProvider() {
this.$get = function $$jqLite() {
return extend(JQLite, {
hasClass: function(node, classes) {
if (node.attr) node = node[0];
return jqLiteHasClass(node, classes);
},
addClass: function(node, classes) {
if (node.attr) node = node[0];
return jqLiteAddClass(node, classes);
},
removeClass: function(node, classes) {
if (node.attr) node = node[0];
return jqLiteRemoveClass(node, classes);
}
});
};
}
/**
* Computes a hash of an 'obj'.
* Hash of a:
* string is string
* number is number as string
* object is either result of calling $$hashKey function on the object or uniquely generated id,
* that is also assigned to the $$hashKey property of the object.
*
* @param obj
* @returns {string} hash string such that the same input will have the same hash string.
* The resulting string key is in 'type:hashKey' format.
*/
function hashKey(obj, nextUidFn) {
var key = obj && obj.$$hashKey;
if (key) {
if (typeof key === 'function') {
key = obj.$$hashKey();
}
return key;
}
var objType = typeof obj;
if (objType === 'function' || (objType === 'object' && obj !== null)) {
key = obj.$$hashKey = objType + ':' + (nextUidFn || nextUid)();
} else {
key = objType + ':' + obj;
}
return key;
}
// A minimal ES2015 Map implementation.
// Should be bug/feature equivalent to the native implementations of supported browsers
// (for the features required in Angular).
// See https://kangax.github.io/compat-table/es6/#test-Map
var nanKey = Object.create(null);
function NgMapShim() {
this._keys = [];
this._values = [];
this._lastKey = NaN;
this._lastIndex = -1;
}
NgMapShim.prototype = {
_idx: function(key) {
if (key !== this._lastKey) {
this._lastKey = key;
this._lastIndex = this._keys.indexOf(key);
}
return this._lastIndex;
},
_transformKey: function(key) {
return isNumberNaN(key) ? nanKey : key;
},
get: function(key) {
key = this._transformKey(key);
var idx = this._idx(key);
if (idx !== -1) {
return this._values[idx];
}
},
has: function(key) {
key = this._transformKey(key);
var idx = this._idx(key);
return idx !== -1;
},
set: function(key, value) {
key = this._transformKey(key);
var idx = this._idx(key);
if (idx === -1) {
idx = this._lastIndex = this._keys.length;
}
this._keys[idx] = key;
this._values[idx] = value;
// Support: IE11
// Do not `return this` to simulate the partial IE11 implementation
},
delete: function(key) {
key = this._transformKey(key);
var idx = this._idx(key);
if (idx === -1) {
return false;
}
this._keys.splice(idx, 1);
this._values.splice(idx, 1);
this._lastKey = NaN;
this._lastIndex = -1;
return true;
}
};
// For now, always use `NgMapShim`, even if `window.Map` is available. Some native implementations
// are still buggy (often in subtle ways) and can cause hard-to-debug failures. When native `Map`
// implementations get more stable, we can reconsider switching to `window.Map` (when available).
var NgMap = NgMapShim;
var $$MapProvider = [/** @this */function() {
this.$get = [function() {
return NgMap;
}];
}];
/**
* @ngdoc function
* @module ng
* @name angular.injector
* @kind function
*
* @description
* Creates an injector object that can be used for retrieving services as well as for
* dependency injection (see {@link guide/di dependency injection}).
*
* @param {Array.} modules A list of module functions or their aliases. See
* {@link angular.module}. The `ng` module must be explicitly added.
* @param {boolean=} [strictDi=false] Whether the injector should be in strict mode, which
* disallows argument name annotation inference.
* @returns {injector} Injector object. See {@link auto.$injector $injector}.
*
* @example
* Typical usage
* ```js
* // create an injector
* var $injector = angular.injector(['ng']);
*
* // use the injector to kick off your application
* // use the type inference to auto inject arguments, or use implicit injection
* $injector.invoke(function($rootScope, $compile, $document) {
* $compile($document)($rootScope);
* $rootScope.$digest();
* });
* ```
*
* Sometimes you want to get access to the injector of a currently running AngularJS app
* from outside AngularJS. Perhaps, you want to inject and compile some markup after the
* application has been bootstrapped. You can do this using the extra `injector()` added
* to JQuery/jqLite elements. See {@link angular.element}.
*
* *This is fairly rare but could be the case if a third party library is injecting the
* markup.*
*
* In the following example a new block of HTML containing a `ng-controller`
* directive is added to the end of the document body by JQuery. We then compile and link
* it into the current AngularJS scope.
*
* ```js
* var $div = $('
{{content.label}}
');
* $(document.body).append($div);
*
* angular.element(document).injector().invoke(function($compile) {
* var scope = angular.element($div).scope();
* $compile($div)(scope);
* });
* ```
*/
/**
* @ngdoc module
* @name auto
* @installation
* @description
*
* Implicit module which gets automatically added to each {@link auto.$injector $injector}.
*/
var ARROW_ARG = /^([^(]+?)=>/;
var FN_ARGS = /^[^(]*\(\s*([^)]*)\)/m;
var FN_ARG_SPLIT = /,/;
var FN_ARG = /^\s*(_?)(\S+?)\1\s*$/;
var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;
var $injectorMinErr = minErr('$injector');
function stringifyFn(fn) {
return Function.prototype.toString.call(fn);
}
function extractArgs(fn) {
var fnText = stringifyFn(fn).replace(STRIP_COMMENTS, ''),
args = fnText.match(ARROW_ARG) || fnText.match(FN_ARGS);
return args;
}
function anonFn(fn) {
// For anonymous functions, showing at the very least the function signature can help in
// debugging.
var args = extractArgs(fn);
if (args) {
return 'function(' + (args[1] || '').replace(/[\s\r\n]+/, ' ') + ')';
}
return 'fn';
}
function annotate(fn, strictDi, name) {
var $inject,
argDecl,
last;
if (typeof fn === 'function') {
if (!($inject = fn.$inject)) {
$inject = [];
if (fn.length) {
if (strictDi) {
if (!isString(name) || !name) {
name = fn.name || anonFn(fn);
}
throw $injectorMinErr('strictdi',
'{0} is not using explicit annotation and cannot be invoked in strict mode', name);
}
argDecl = extractArgs(fn);
forEach(argDecl[1].split(FN_ARG_SPLIT), function(arg) {
arg.replace(FN_ARG, function(all, underscore, name) {
$inject.push(name);
});
});
}
fn.$inject = $inject;
}
} else if (isArray(fn)) {
last = fn.length - 1;
assertArgFn(fn[last], 'fn');
$inject = fn.slice(0, last);
} else {
assertArgFn(fn, 'fn', true);
}
return $inject;
}
///////////////////////////////////////
/**
* @ngdoc service
* @name $injector
*
* @description
*
* `$injector` is used to retrieve object instances as defined by
* {@link auto.$provide provider}, instantiate types, invoke methods,
* and load modules.
*
* The following always holds true:
*
* ```js
* var $injector = angular.injector();
* expect($injector.get('$injector')).toBe($injector);
* expect($injector.invoke(function($injector) {
* return $injector;
* })).toBe($injector);
* ```
*
* ## Injection Function Annotation
*
* JavaScript does not have annotations, and annotations are needed for dependency injection. The
* following are all valid ways of annotating function with injection arguments and are equivalent.
*
* ```js
* // inferred (only works if code not minified/obfuscated)
* $injector.invoke(function(serviceA){});
*
* // annotated
* function explicit(serviceA) {};
* explicit.$inject = ['serviceA'];
* $injector.invoke(explicit);
*
* // inline
* $injector.invoke(['serviceA', function(serviceA){}]);
* ```
*
* ### Inference
*
* In JavaScript calling `toString()` on a function returns the function definition. The definition
* can then be parsed and the function arguments can be extracted. This method of discovering
* annotations is disallowed when the injector is in strict mode.
* *NOTE:* This does not work with minification, and obfuscation tools since these tools change the
* argument names.
*
* ### `$inject` Annotation
* By adding an `$inject` property onto a function the injection parameters can be specified.
*
* ### Inline
* As an array of injection names, where the last item in the array is the function to call.
*/
/**
* @ngdoc property
* @name $injector#modules
* @type {Object}
* @description
* A hash containing all the modules that have been loaded into the
* $injector.
*
* You can use this property to find out information about a module via the
* {@link angular.Module#info `myModule.info(...)`} method.
*
* For example:
*
* ```
* var info = $injector.modules['ngAnimate'].info();
* ```
*
* **Do not use this property to attempt to modify the modules after the application
* has been bootstrapped.**
*/
/**
* @ngdoc method
* @name $injector#get
*
* @description
* Return an instance of the service.
*
* @param {string} name The name of the instance to retrieve.
* @param {string=} caller An optional string to provide the origin of the function call for error messages.
* @return {*} The instance.
*/
/**
* @ngdoc method
* @name $injector#invoke
*
* @description
* Invoke the method and supply the method arguments from the `$injector`.
*
* @param {Function|Array.} fn The injectable function to invoke. Function parameters are
* injected according to the {@link guide/di $inject Annotation} rules.
* @param {Object=} self The `this` for the invoked method.
* @param {Object=} locals Optional object. If preset then any argument names are read from this
* object first, before the `$injector` is consulted.
* @returns {*} the value returned by the invoked `fn` function.
*/
/**
* @ngdoc method
* @name $injector#has
*
* @description
* Allows the user to query if the particular service exists.
*
* @param {string} name Name of the service to query.
* @returns {boolean} `true` if injector has given service.
*/
/**
* @ngdoc method
* @name $injector#instantiate
* @description
* Create a new instance of JS type. The method takes a constructor function, invokes the new
* operator, and supplies all of the arguments to the constructor function as specified by the
* constructor annotation.
*
* @param {Function} Type Annotated constructor function.
* @param {Object=} locals Optional object. If preset then any argument names are read from this
* object first, before the `$injector` is consulted.
* @returns {Object} new instance of `Type`.
*/
/**
* @ngdoc method
* @name $injector#annotate
*
* @description
* Returns an array of service names which the function is requesting for injection. This API is
* used by the injector to determine which services need to be injected into the function when the
* function is invoked. There are three ways in which the function can be annotated with the needed
* dependencies.
*
* #### Argument names
*
* The simplest form is to extract the dependencies from the arguments of the function. This is done
* by converting the function into a string using `toString()` method and extracting the argument
* names.
* ```js
* // Given
* function MyController($scope, $route) {
* // ...
* }
*
* // Then
* expect(injector.annotate(MyController)).toEqual(['$scope', '$route']);
* ```
*
* You can disallow this method by using strict injection mode.
*
* This method does not work with code minification / obfuscation. For this reason the following
* annotation strategies are supported.
*
* #### The `$inject` property
*
* If a function has an `$inject` property and its value is an array of strings, then the strings
* represent names of services to be injected into the function.
* ```js
* // Given
* var MyController = function(obfuscatedScope, obfuscatedRoute) {
* // ...
* }
* // Define function dependencies
* MyController['$inject'] = ['$scope', '$route'];
*
* // Then
* expect(injector.annotate(MyController)).toEqual(['$scope', '$route']);
* ```
*
* #### The array notation
*
* It is often desirable to inline Injected functions and that's when setting the `$inject` property
* is very inconvenient. In these situations using the array notation to specify the dependencies in
* a way that survives minification is a better choice:
*
* ```js
* // We wish to write this (not minification / obfuscation safe)
* injector.invoke(function($compile, $rootScope) {
* // ...
* });
*
* // We are forced to write break inlining
* var tmpFn = function(obfuscatedCompile, obfuscatedRootScope) {
* // ...
* };
* tmpFn.$inject = ['$compile', '$rootScope'];
* injector.invoke(tmpFn);
*
* // To better support inline function the inline annotation is supported
* injector.invoke(['$compile', '$rootScope', function(obfCompile, obfRootScope) {
* // ...
* }]);
*
* // Therefore
* expect(injector.annotate(
* ['$compile', '$rootScope', function(obfus_$compile, obfus_$rootScope) {}])
* ).toEqual(['$compile', '$rootScope']);
* ```
*
* @param {Function|Array.} fn Function for which dependent service names need to
* be retrieved as described above.
*
* @param {boolean=} [strictDi=false] Disallow argument name annotation inference.
*
* @returns {Array.} The names of the services which the function requires.
*/
/**
* @ngdoc method
* @name $injector#loadNewModules
*
* @description
*
* **This is a dangerous API, which you use at your own risk!**
*
* Add the specified modules to the current injector.
*
* This method will add each of the injectables to the injector and execute all of the config and run
* blocks for each module passed to the method.
*
* If a module has already been loaded into the injector then it will not be loaded again.
*
* * The application developer is responsible for loading the code containing the modules; and for
* ensuring that lazy scripts are not downloaded and executed more often that desired.
* * Previously compiled HTML will not be affected by newly loaded directives, filters and components.
* * Modules cannot be unloaded.
*
* You can use {@link $injector#modules `$injector.modules`} to check whether a module has been loaded
* into the injector, which may indicate whether the script has been executed already.
*
* @example
* Here is an example of loading a bundle of modules, with a utility method called `getScript`:
*
* ```javascript
* app.factory('loadModule', function($injector) {
* return function loadModule(moduleName, bundleUrl) {
* return getScript(bundleUrl).then(function() { $injector.loadNewModules([moduleName]); });
* };
* })
* ```
*
* @param {Array=} mods an array of modules to load into the application.
* Each item in the array should be the name of a predefined module or a (DI annotated)
* function that will be invoked by the injector as a `config` block.
* See: {@link angular.module modules}
*/
/**
* @ngdoc service
* @name $provide
*
* @description
*
* The {@link auto.$provide $provide} service has a number of methods for registering components
* with the {@link auto.$injector $injector}. Many of these functions are also exposed on
* {@link angular.Module}.
*
* An AngularJS **service** is a singleton object created by a **service factory**. These **service
* factories** are functions which, in turn, are created by a **service provider**.
* The **service providers** are constructor functions. When instantiated they must contain a
* property called `$get`, which holds the **service factory** function.
*
* When you request a service, the {@link auto.$injector $injector} is responsible for finding the
* correct **service provider**, instantiating it and then calling its `$get` **service factory**
* function to get the instance of the **service**.
*
* Often services have no configuration options and there is no need to add methods to the service
* provider. The provider will be no more than a constructor function with a `$get` property. For
* these cases the {@link auto.$provide $provide} service has additional helper methods to register
* services without specifying a provider.
*
* * {@link auto.$provide#provider provider(name, provider)} - registers a **service provider** with the
* {@link auto.$injector $injector}
* * {@link auto.$provide#constant constant(name, obj)} - registers a value/object that can be accessed by
* providers and services.
* * {@link auto.$provide#value value(name, obj)} - registers a value/object that can only be accessed by
* services, not providers.
* * {@link auto.$provide#factory factory(name, fn)} - registers a service **factory function**
* that will be wrapped in a **service provider** object, whose `$get` property will contain the
* given factory function.
* * {@link auto.$provide#service service(name, Fn)} - registers a **constructor function**
* that will be wrapped in a **service provider** object, whose `$get` property will instantiate
* a new object using the given constructor function.
* * {@link auto.$provide#decorator decorator(name, decorFn)} - registers a **decorator function** that
* will be able to modify or replace the implementation of another service.
*
* See the individual methods for more information and examples.
*/
/**
* @ngdoc method
* @name $provide#provider
* @description
*
* Register a **provider function** with the {@link auto.$injector $injector}. Provider functions
* are constructor functions, whose instances are responsible for "providing" a factory for a
* service.
*
* Service provider names start with the name of the service they provide followed by `Provider`.
* For example, the {@link ng.$log $log} service has a provider called
* {@link ng.$logProvider $logProvider}.
*
* Service provider objects can have additional methods which allow configuration of the provider
* and its service. Importantly, you can configure what kind of service is created by the `$get`
* method, or how that service will act. For example, the {@link ng.$logProvider $logProvider} has a
* method {@link ng.$logProvider#debugEnabled debugEnabled}
* which lets you specify whether the {@link ng.$log $log} service will log debug messages to the
* console or not.
*
* It is possible to inject other providers into the provider function,
* but the injected provider must have been defined before the one that requires it.
*
* @param {string} name The name of the instance. NOTE: the provider will be available under `name +
'Provider'` key.
* @param {(Object|function())} provider If the provider is:
*
* - `Object`: then it should have a `$get` method. The `$get` method will be invoked using
* {@link auto.$injector#invoke $injector.invoke()} when an instance needs to be created.
* - `Constructor`: a new instance of the provider will be created using
* {@link auto.$injector#instantiate $injector.instantiate()}, then treated as `object`.
*
* @returns {Object} registered provider instance
* @example
*
* The following example shows how to create a simple event tracking service and register it using
* {@link auto.$provide#provider $provide.provider()}.
*
* ```js
* // Define the eventTracker provider
* function EventTrackerProvider() {
* var trackingUrl = '/track';
*
* // A provider method for configuring where the tracked events should been saved
* this.setTrackingUrl = function(url) {
* trackingUrl = url;
* };
*
* // The service factory function
* this.$get = ['$http', function($http) {
* var trackedEvents = {};
* return {
* // Call this to track an event
* event: function(event) {
* var count = trackedEvents[event] || 0;
* count += 1;
* trackedEvents[event] = count;
* return count;
* },
* // Call this to save the tracked events to the trackingUrl
* save: function() {
* $http.post(trackingUrl, trackedEvents);
* }
* };
* }];
* }
*
* describe('eventTracker', function() {
* var postSpy;
*
* beforeEach(module(function($provide) {
* // Register the eventTracker provider
* $provide.provider('eventTracker', EventTrackerProvider);
* }));
*
* beforeEach(module(function(eventTrackerProvider) {
* // Configure eventTracker provider
* eventTrackerProvider.setTrackingUrl('/custom-track');
* }));
*
* it('tracks events', inject(function(eventTracker) {
* expect(eventTracker.event('login')).toEqual(1);
* expect(eventTracker.event('login')).toEqual(2);
* }));
*
* it('saves to the tracking url', inject(function(eventTracker, $http) {
* postSpy = spyOn($http, 'post');
* eventTracker.event('login');
* eventTracker.save();
* expect(postSpy).toHaveBeenCalled();
* expect(postSpy.mostRecentCall.args[0]).not.toEqual('/track');
* expect(postSpy.mostRecentCall.args[0]).toEqual('/custom-track');
* expect(postSpy.mostRecentCall.args[1]).toEqual({ 'login': 1 });
* }));
* });
* ```
*/
/**
* @ngdoc method
* @name $provide#factory
* @description
*
* Register a **service factory**, which will be called to return the service instance.
* This is short for registering a service where its provider consists of only a `$get` property,
* which is the given service factory function.
* You should use {@link auto.$provide#factory $provide.factory(getFn)} if you do not need to
* configure your service in a provider.
*
* @param {string} name The name of the instance.
* @param {Function|Array.} $getFn The injectable $getFn for the instance creation.
* Internally this is a short hand for `$provide.provider(name, {$get: $getFn})`.
* @returns {Object} registered provider instance
*
* @example
* Here is an example of registering a service
* ```js
* $provide.factory('ping', ['$http', function($http) {
* return function ping() {
* return $http.send('/ping');
* };
* }]);
* ```
* You would then inject and use this service like this:
* ```js
* someModule.controller('Ctrl', ['ping', function(ping) {
* ping();
* }]);
* ```
*/
/**
* @ngdoc method
* @name $provide#service
* @description
*
* Register a **service constructor**, which will be invoked with `new` to create the service
* instance.
* This is short for registering a service where its provider's `$get` property is a factory
* function that returns an instance instantiated by the injector from the service constructor
* function.
*
* Internally it looks a bit like this:
*
* ```
* {
* $get: function() {
* return $injector.instantiate(constructor);
* }
* }
* ```
*
*
* You should use {@link auto.$provide#service $provide.service(class)} if you define your service
* as a type/class.
*
* @param {string} name The name of the instance.
* @param {Function|Array.} constructor An injectable class (constructor function)
* that will be instantiated.
* @returns {Object} registered provider instance
*
* @example
* Here is an example of registering a service using
* {@link auto.$provide#service $provide.service(class)}.
* ```js
* var Ping = function($http) {
* this.$http = $http;
* };
*
* Ping.$inject = ['$http'];
*
* Ping.prototype.send = function() {
* return this.$http.get('/ping');
* };
* $provide.service('ping', Ping);
* ```
* You would then inject and use this service like this:
* ```js
* someModule.controller('Ctrl', ['ping', function(ping) {
* ping.send();
* }]);
* ```
*/
/**
* @ngdoc method
* @name $provide#value
* @description
*
* Register a **value service** with the {@link auto.$injector $injector}, such as a string, a
* number, an array, an object or a function. This is short for registering a service where its
* provider's `$get` property is a factory function that takes no arguments and returns the **value
* service**. That also means it is not possible to inject other services into a value service.
*
* Value services are similar to constant services, except that they cannot be injected into a
* module configuration function (see {@link angular.Module#config}) but they can be overridden by
* an AngularJS {@link auto.$provide#decorator decorator}.
*
* @param {string} name The name of the instance.
* @param {*} value The value.
* @returns {Object} registered provider instance
*
* @example
* Here are some examples of creating value services.
* ```js
* $provide.value('ADMIN_USER', 'admin');
*
* $provide.value('RoleLookup', { admin: 0, writer: 1, reader: 2 });
*
* $provide.value('halfOf', function(value) {
* return value / 2;
* });
* ```
*/
/**
* @ngdoc method
* @name $provide#constant
* @description
*
* Register a **constant service** with the {@link auto.$injector $injector}, such as a string,
* a number, an array, an object or a function. Like the {@link auto.$provide#value value}, it is not
* possible to inject other services into a constant.
*
* But unlike {@link auto.$provide#value value}, a constant can be
* injected into a module configuration function (see {@link angular.Module#config}) and it cannot
* be overridden by an AngularJS {@link auto.$provide#decorator decorator}.
*
* @param {string} name The name of the constant.
* @param {*} value The constant value.
* @returns {Object} registered instance
*
* @example
* Here a some examples of creating constants:
* ```js
* $provide.constant('SHARD_HEIGHT', 306);
*
* $provide.constant('MY_COLOURS', ['red', 'blue', 'grey']);
*
* $provide.constant('double', function(value) {
* return value * 2;
* });
* ```
*/
/**
* @ngdoc method
* @name $provide#decorator
* @description
*
* Register a **decorator function** with the {@link auto.$injector $injector}. A decorator function
* intercepts the creation of a service, allowing it to override or modify the behavior of the
* service. The return value of the decorator function may be the original service, or a new service
* that replaces (or wraps and delegates to) the original service.
*
* You can find out more about using decorators in the {@link guide/decorators} guide.
*
* @param {string} name The name of the service to decorate.
* @param {Function|Array.} decorator This function will be invoked when the service needs to be
* provided and should return the decorated service instance. The function is called using
* the {@link auto.$injector#invoke injector.invoke} method and is therefore fully injectable.
* Local injection arguments:
*
* * `$delegate` - The original service instance, which can be replaced, monkey patched, configured,
* decorated or delegated to.
*
* @example
* Here we decorate the {@link ng.$log $log} service to convert warnings to errors by intercepting
* calls to {@link ng.$log#error $log.warn()}.
* ```js
* $provide.decorator('$log', ['$delegate', function($delegate) {
* $delegate.warn = $delegate.error;
* return $delegate;
* }]);
* ```
*/
function createInjector(modulesToLoad, strictDi) {
strictDi = (strictDi === true);
var INSTANTIATING = {},
providerSuffix = 'Provider',
path = [],
loadedModules = new NgMap(),
providerCache = {
$provide: {
provider: supportObject(provider),
factory: supportObject(factory),
service: supportObject(service),
value: supportObject(value),
constant: supportObject(constant),
decorator: decorator
}
},
providerInjector = (providerCache.$injector =
createInternalInjector(providerCache, function(serviceName, caller) {
if (angular.isString(caller)) {
path.push(caller);
}
throw $injectorMinErr('unpr', 'Unknown provider: {0}', path.join(' <- '));
})),
instanceCache = {},
protoInstanceInjector =
createInternalInjector(instanceCache, function(serviceName, caller) {
var provider = providerInjector.get(serviceName + providerSuffix, caller);
return instanceInjector.invoke(
provider.$get, provider, undefined, serviceName);
}),
instanceInjector = protoInstanceInjector;
providerCache['$injector' + providerSuffix] = { $get: valueFn(protoInstanceInjector) };
instanceInjector.modules = providerInjector.modules = createMap();
var runBlocks = loadModules(modulesToLoad);
instanceInjector = protoInstanceInjector.get('$injector');
instanceInjector.strictDi = strictDi;
forEach(runBlocks, function(fn) { if (fn) instanceInjector.invoke(fn); });
instanceInjector.loadNewModules = function(mods) {
forEach(loadModules(mods), function(fn) { if (fn) instanceInjector.invoke(fn); });
};
return instanceInjector;
////////////////////////////////////
// $provider
////////////////////////////////////
function supportObject(delegate) {
return function(key, value) {
if (isObject(key)) {
forEach(key, reverseParams(delegate));
} else {
return delegate(key, value);
}
};
}
function provider(name, provider_) {
assertNotHasOwnProperty(name, 'service');
if (isFunction(provider_) || isArray(provider_)) {
provider_ = providerInjector.instantiate(provider_);
}
if (!provider_.$get) {
throw $injectorMinErr('pget', 'Provider \'{0}\' must define $get factory method.', name);
}
return (providerCache[name + providerSuffix] = provider_);
}
function enforceReturnValue(name, factory) {
return /** @this */ function enforcedReturnValue() {
var result = instanceInjector.invoke(factory, this);
if (isUndefined(result)) {
throw $injectorMinErr('undef', 'Provider \'{0}\' must return a value from $get factory method.', name);
}
return result;
};
}
function factory(name, factoryFn, enforce) {
return provider(name, {
$get: enforce !== false ? enforceReturnValue(name, factoryFn) : factoryFn
});
}
function service(name, constructor) {
return factory(name, ['$injector', function($injector) {
return $injector.instantiate(constructor);
}]);
}
function value(name, val) { return factory(name, valueFn(val), false); }
function constant(name, value) {
assertNotHasOwnProperty(name, 'constant');
providerCache[name] = value;
instanceCache[name] = value;
}
function decorator(serviceName, decorFn) {
var origProvider = providerInjector.get(serviceName + providerSuffix),
orig$get = origProvider.$get;
origProvider.$get = function() {
var origInstance = instanceInjector.invoke(orig$get, origProvider);
return instanceInjector.invoke(decorFn, null, {$delegate: origInstance});
};
}
////////////////////////////////////
// Module Loading
////////////////////////////////////
function loadModules(modulesToLoad) {
assertArg(isUndefined(modulesToLoad) || isArray(modulesToLoad), 'modulesToLoad', 'not an array');
var runBlocks = [], moduleFn;
forEach(modulesToLoad, function(module) {
if (loadedModules.get(module)) return;
loadedModules.set(module, true);
function runInvokeQueue(queue) {
var i, ii;
for (i = 0, ii = queue.length; i < ii; i++) {
var invokeArgs = queue[i],
provider = providerInjector.get(invokeArgs[0]);
provider[invokeArgs[1]].apply(provider, invokeArgs[2]);
}
}
try {
if (isString(module)) {
moduleFn = angularModule(module);
instanceInjector.modules[module] = moduleFn;
runBlocks = runBlocks.concat(loadModules(moduleFn.requires)).concat(moduleFn._runBlocks);
runInvokeQueue(moduleFn._invokeQueue);
runInvokeQueue(moduleFn._configBlocks);
} else if (isFunction(module)) {
runBlocks.push(providerInjector.invoke(module));
} else if (isArray(module)) {
runBlocks.push(providerInjector.invoke(module));
} else {
assertArgFn(module, 'module');
}
} catch (e) {
if (isArray(module)) {
module = module[module.length - 1];
}
if (e.message && e.stack && e.stack.indexOf(e.message) === -1) {
// Safari & FF's stack traces don't contain error.message content
// unlike those of Chrome and IE
// So if stack doesn't contain message, we create a new string that contains both.
// Since error.stack is read-only in Safari, I'm overriding e and not e.stack here.
// eslint-disable-next-line no-ex-assign
e = e.message + '\n' + e.stack;
}
throw $injectorMinErr('modulerr', 'Failed to instantiate module {0} due to:\n{1}',
module, e.stack || e.message || e);
}
});
return runBlocks;
}
////////////////////////////////////
// internal Injector
////////////////////////////////////
function createInternalInjector(cache, factory) {
function getService(serviceName, caller) {
if (cache.hasOwnProperty(serviceName)) {
if (cache[serviceName] === INSTANTIATING) {
throw $injectorMinErr('cdep', 'Circular dependency found: {0}',
serviceName + ' <- ' + path.join(' <- '));
}
return cache[serviceName];
} else {
try {
path.unshift(serviceName);
cache[serviceName] = INSTANTIATING;
cache[serviceName] = factory(serviceName, caller);
return cache[serviceName];
} catch (err) {
if (cache[serviceName] === INSTANTIATING) {
delete cache[serviceName];
}
throw err;
} finally {
path.shift();
}
}
}
function injectionArgs(fn, locals, serviceName) {
var args = [],
$inject = createInjector.$$annotate(fn, strictDi, serviceName);
for (var i = 0, length = $inject.length; i < length; i++) {
var key = $inject[i];
if (typeof key !== 'string') {
throw $injectorMinErr('itkn',
'Incorrect injection token! Expected service name as string, got {0}', key);
}
args.push(locals && locals.hasOwnProperty(key) ? locals[key] :
getService(key, serviceName));
}
return args;
}
function isClass(func) {
// Support: IE 9-11 only
// IE 9-11 do not support classes and IE9 leaks with the code below.
if (msie || typeof func !== 'function') {
return false;
}
var result = func.$$ngIsClass;
if (!isBoolean(result)) {
result = func.$$ngIsClass = /^class\b/.test(stringifyFn(func));
}
return result;
}
function invoke(fn, self, locals, serviceName) {
if (typeof locals === 'string') {
serviceName = locals;
locals = null;
}
var args = injectionArgs(fn, locals, serviceName);
if (isArray(fn)) {
fn = fn[fn.length - 1];
}
if (!isClass(fn)) {
// http://jsperf.com/angularjs-invoke-apply-vs-switch
// #5388
return fn.apply(self, args);
} else {
args.unshift(null);
return new (Function.prototype.bind.apply(fn, args))();
}
}
function instantiate(Type, locals, serviceName) {
// Check if Type is annotated and use just the given function at n-1 as parameter
// e.g. someModule.factory('greeter', ['$window', function(renamed$window) {}]);
var ctor = (isArray(Type) ? Type[Type.length - 1] : Type);
var args = injectionArgs(Type, locals, serviceName);
// Empty object at position 0 is ignored for invocation with `new`, but required.
args.unshift(null);
return new (Function.prototype.bind.apply(ctor, args))();
}
return {
invoke: invoke,
instantiate: instantiate,
get: getService,
annotate: createInjector.$$annotate,
has: function(name) {
return providerCache.hasOwnProperty(name + providerSuffix) || cache.hasOwnProperty(name);
}
};
}
}
createInjector.$$annotate = annotate;
/**
* @ngdoc provider
* @name $anchorScrollProvider
* @this
*
* @description
* Use `$anchorScrollProvider` to disable automatic scrolling whenever
* {@link ng.$location#hash $location.hash()} changes.
*/
function $AnchorScrollProvider() {
var autoScrollingEnabled = true;
/**
* @ngdoc method
* @name $anchorScrollProvider#disableAutoScrolling
*
* @description
* By default, {@link ng.$anchorScroll $anchorScroll()} will automatically detect changes to
* {@link ng.$location#hash $location.hash()} and scroll to the element matching the new hash.
* Use this method to disable automatic scrolling.
*
* If automatic scrolling is disabled, one must explicitly call
* {@link ng.$anchorScroll $anchorScroll()} in order to scroll to the element related to the
* current hash.
*/
this.disableAutoScrolling = function() {
autoScrollingEnabled = false;
};
/**
* @ngdoc service
* @name $anchorScroll
* @kind function
* @requires $window
* @requires $location
* @requires $rootScope
*
* @description
* When called, it scrolls to the element related to the specified `hash` or (if omitted) to the
* current value of {@link ng.$location#hash $location.hash()}, according to the rules specified
* in the
* [HTML5 spec](http://www.w3.org/html/wg/drafts/html/master/browsers.html#an-indicated-part-of-the-document).
*
* It also watches the {@link ng.$location#hash $location.hash()} and automatically scrolls to
* match any anchor whenever it changes. This can be disabled by calling
* {@link ng.$anchorScrollProvider#disableAutoScrolling $anchorScrollProvider.disableAutoScrolling()}.
*
* Additionally, you can use its {@link ng.$anchorScroll#yOffset yOffset} property to specify a
* vertical scroll-offset (either fixed or dynamic).
*
* @param {string=} hash The hash specifying the element to scroll to. If omitted, the value of
* {@link ng.$location#hash $location.hash()} will be used.
*
* @property {(number|function|jqLite)} yOffset
* If set, specifies a vertical scroll-offset. This is often useful when there are fixed
* positioned elements at the top of the page, such as navbars, headers etc.
*
* `yOffset` can be specified in various ways:
* - **number**: A fixed number of pixels to be used as offset.
* - **function**: A getter function called everytime `$anchorScroll()` is executed. Must return
* a number representing the offset (in pixels).
* - **jqLite**: A jqLite/jQuery element to be used for specifying the offset. The distance from
* the top of the page to the element's bottom will be used as offset.
* **Note**: The element will be taken into account only as long as its `position` is set to
* `fixed`. This option is useful, when dealing with responsive navbars/headers that adjust
* their height and/or positioning according to the viewport's size.
*
*
*
* In order for `yOffset` to work properly, scrolling should take place on the document's root and
* not some child element.
*
angular.module('anchorScrollExample', [])
.controller('ScrollController', ['$scope', '$location', '$anchorScroll',
function($scope, $location, $anchorScroll) {
$scope.gotoBottom = function() {
// set the location.hash to the id of
// the element you wish to scroll to.
$location.hash('bottom');
// call $anchorScroll()
$anchorScroll();
};
}]);
#scrollArea {
height: 280px;
overflow: auto;
}
#bottom {
display: block;
margin-top: 2000px;
}
*
*
* The example below illustrates the use of a vertical scroll-offset (specified as a fixed value).
* See {@link ng.$anchorScroll#yOffset $anchorScroll.yOffset} for more details.
*
* @example
angular.module('anchorScrollOffsetExample', [])
.run(['$anchorScroll', function($anchorScroll) {
$anchorScroll.yOffset = 50; // always scroll by 50 extra pixels
}])
.controller('headerCtrl', ['$anchorScroll', '$location', '$scope',
function($anchorScroll, $location, $scope) {
$scope.gotoAnchor = function(x) {
var newHash = 'anchor' + x;
if ($location.hash() !== newHash) {
// set the $location.hash to `newHash` and
// $anchorScroll will automatically scroll to it
$location.hash('anchor' + x);
} else {
// call $anchorScroll() explicitly,
// since $location.hash hasn't changed
$anchorScroll();
}
};
}
]);
body {
padding-top: 50px;
}
.anchor {
border: 2px dashed DarkOrchid;
padding: 10px 10px 200px 10px;
}
.fixed-header {
background-color: rgba(0, 0, 0, 0.2);
height: 50px;
position: fixed;
top: 0; left: 0; right: 0;
}
.fixed-header > a {
display: inline-block;
margin: 5px 15px;
}
*/
this.$get = ['$window', '$location', '$rootScope', function($window, $location, $rootScope) {
var document = $window.document;
// Helper function to get first anchor from a NodeList
// (using `Array#some()` instead of `angular#forEach()` since it's more performant
// and working in all supported browsers.)
function getFirstAnchor(list) {
var result = null;
Array.prototype.some.call(list, function(element) {
if (nodeName_(element) === 'a') {
result = element;
return true;
}
});
return result;
}
function getYOffset() {
var offset = scroll.yOffset;
if (isFunction(offset)) {
offset = offset();
} else if (isElement(offset)) {
var elem = offset[0];
var style = $window.getComputedStyle(elem);
if (style.position !== 'fixed') {
offset = 0;
} else {
offset = elem.getBoundingClientRect().bottom;
}
} else if (!isNumber(offset)) {
offset = 0;
}
return offset;
}
function scrollTo(elem) {
if (elem) {
elem.scrollIntoView();
var offset = getYOffset();
if (offset) {
// `offset` is the number of pixels we should scroll UP in order to align `elem` properly.
// This is true ONLY if the call to `elem.scrollIntoView()` initially aligns `elem` at the
// top of the viewport.
//
// IF the number of pixels from the top of `elem` to the end of the page's content is less
// than the height of the viewport, then `elem.scrollIntoView()` will align the `elem` some
// way down the page.
//
// This is often the case for elements near the bottom of the page.
//
// In such cases we do not need to scroll the whole `offset` up, just the difference between
// the top of the element and the offset, which is enough to align the top of `elem` at the
// desired position.
var elemTop = elem.getBoundingClientRect().top;
$window.scrollBy(0, elemTop - offset);
}
} else {
$window.scrollTo(0, 0);
}
}
function scroll(hash) {
// Allow numeric hashes
hash = isString(hash) ? hash : isNumber(hash) ? hash.toString() : $location.hash();
var elm;
// empty hash, scroll to the top of the page
if (!hash) scrollTo(null);
// element with given id
else if ((elm = document.getElementById(hash))) scrollTo(elm);
// first anchor with given name :-D
else if ((elm = getFirstAnchor(document.getElementsByName(hash)))) scrollTo(elm);
// no element and hash === 'top', scroll to the top of the page
else if (hash === 'top') scrollTo(null);
}
// does not scroll when user clicks on anchor link that is currently on
// (no url change, no $location.hash() change), browser native does scroll
if (autoScrollingEnabled) {
$rootScope.$watch(function autoScrollWatch() {return $location.hash();},
function autoScrollWatchAction(newVal, oldVal) {
// skip the initial scroll if $location.hash is empty
if (newVal === oldVal && newVal === '') return;
jqLiteDocumentLoaded(function() {
$rootScope.$evalAsync(scroll);
});
});
}
return scroll;
}];
}
var $animateMinErr = minErr('$animate');
var ELEMENT_NODE = 1;
var NG_ANIMATE_CLASSNAME = 'ng-animate';
function mergeClasses(a,b) {
if (!a && !b) return '';
if (!a) return b;
if (!b) return a;
if (isArray(a)) a = a.join(' ');
if (isArray(b)) b = b.join(' ');
return a + ' ' + b;
}
function extractElementNode(element) {
for (var i = 0; i < element.length; i++) {
var elm = element[i];
if (elm.nodeType === ELEMENT_NODE) {
return elm;
}
}
}
function splitClasses(classes) {
if (isString(classes)) {
classes = classes.split(' ');
}
// Use createMap() to prevent class assumptions involving property names in
// Object.prototype
var obj = createMap();
forEach(classes, function(klass) {
// sometimes the split leaves empty string values
// incase extra spaces were applied to the options
if (klass.length) {
obj[klass] = true;
}
});
return obj;
}
// if any other type of options value besides an Object value is
// passed into the $animate.method() animation then this helper code
// will be run which will ignore it. While this patch is not the
// greatest solution to this, a lot of existing plugins depend on
// $animate to either call the callback (< 1.2) or return a promise
// that can be changed. This helper function ensures that the options
// are wiped clean incase a callback function is provided.
function prepareAnimateOptions(options) {
return isObject(options)
? options
: {};
}
var $$CoreAnimateJsProvider = /** @this */ function() {
this.$get = noop;
};
// this is prefixed with Core since it conflicts with
// the animateQueueProvider defined in ngAnimate/animateQueue.js
var $$CoreAnimateQueueProvider = /** @this */ function() {
var postDigestQueue = new NgMap();
var postDigestElements = [];
this.$get = ['$$AnimateRunner', '$rootScope',
function($$AnimateRunner, $rootScope) {
return {
enabled: noop,
on: noop,
off: noop,
pin: noop,
push: function(element, event, options, domOperation) {
if (domOperation) {
domOperation();
}
options = options || {};
if (options.from) {
element.css(options.from);
}
if (options.to) {
element.css(options.to);
}
if (options.addClass || options.removeClass) {
addRemoveClassesPostDigest(element, options.addClass, options.removeClass);
}
var runner = new $$AnimateRunner();
// since there are no animations to run the runner needs to be
// notified that the animation call is complete.
runner.complete();
return runner;
}
};
function updateData(data, classes, value) {
var changed = false;
if (classes) {
classes = isString(classes) ? classes.split(' ') :
isArray(classes) ? classes : [];
forEach(classes, function(className) {
if (className) {
changed = true;
data[className] = value;
}
});
}
return changed;
}
function handleCSSClassChanges() {
forEach(postDigestElements, function(element) {
var data = postDigestQueue.get(element);
if (data) {
var existing = splitClasses(element.attr('class'));
var toAdd = '';
var toRemove = '';
forEach(data, function(status, className) {
var hasClass = !!existing[className];
if (status !== hasClass) {
if (status) {
toAdd += (toAdd.length ? ' ' : '') + className;
} else {
toRemove += (toRemove.length ? ' ' : '') + className;
}
}
});
forEach(element, function(elm) {
if (toAdd) {
jqLiteAddClass(elm, toAdd);
}
if (toRemove) {
jqLiteRemoveClass(elm, toRemove);
}
});
postDigestQueue.delete(element);
}
});
postDigestElements.length = 0;
}
function addRemoveClassesPostDigest(element, add, remove) {
var data = postDigestQueue.get(element) || {};
var classesAdded = updateData(data, add, true);
var classesRemoved = updateData(data, remove, false);
if (classesAdded || classesRemoved) {
postDigestQueue.set(element, data);
postDigestElements.push(element);
if (postDigestElements.length === 1) {
$rootScope.$$postDigest(handleCSSClassChanges);
}
}
}
}];
};
/**
* @ngdoc provider
* @name $animateProvider
*
* @description
* Default implementation of $animate that doesn't perform any animations, instead just
* synchronously performs DOM updates and resolves the returned runner promise.
*
* In order to enable animations the `ngAnimate` module has to be loaded.
*
* To see the functional implementation check out `src/ngAnimate/animate.js`.
*/
var $AnimateProvider = ['$provide', /** @this */ function($provide) {
var provider = this;
var classNameFilter = null;
var customFilter = null;
this.$$registeredAnimations = Object.create(null);
/**
* @ngdoc method
* @name $animateProvider#register
*
* @description
* Registers a new injectable animation factory function. The factory function produces the
* animation object which contains callback functions for each event that is expected to be
* animated.
*
* * `eventFn`: `function(element, ... , doneFunction, options)`
* The element to animate, the `doneFunction` and the options fed into the animation. Depending
* on the type of animation additional arguments will be injected into the animation function. The
* list below explains the function signatures for the different animation methods:
*
* - setClass: function(element, addedClasses, removedClasses, doneFunction, options)
* - addClass: function(element, addedClasses, doneFunction, options)
* - removeClass: function(element, removedClasses, doneFunction, options)
* - enter, leave, move: function(element, doneFunction, options)
* - animate: function(element, fromStyles, toStyles, doneFunction, options)
*
* Make sure to trigger the `doneFunction` once the animation is fully complete.
*
* ```js
* return {
* //enter, leave, move signature
* eventFn : function(element, done, options) {
* //code to run the animation
* //once complete, then run done()
* return function endFunction(wasCancelled) {
* //code to cancel the animation
* }
* }
* }
* ```
*
* @param {string} name The name of the animation (this is what the class-based CSS value will be compared to).
* @param {Function} factory The factory function that will be executed to return the animation
* object.
*/
this.register = function(name, factory) {
if (name && name.charAt(0) !== '.') {
throw $animateMinErr('notcsel', 'Expecting class selector starting with \'.\' got \'{0}\'.', name);
}
var key = name + '-animation';
provider.$$registeredAnimations[name.substr(1)] = key;
$provide.factory(key, factory);
};
/**
* @ngdoc method
* @name $animateProvider#customFilter
*
* @description
* Sets and/or returns the custom filter function that is used to "filter" animations, i.e.
* determine if an animation is allowed or not. When no filter is specified (the default), no
* animation will be blocked. Setting the `customFilter` value will only allow animations for
* which the filter function's return value is truthy.
*
* This allows to easily create arbitrarily complex rules for filtering animations, such as
* allowing specific events only, or enabling animations on specific subtrees of the DOM, etc.
* Filtering animations can also boost performance for low-powered devices, as well as
* applications containing a lot of structural operations.
*
*
* **Best Practice:**
* Keep the filtering function as lean as possible, because it will be called for each DOM
* action (e.g. insertion, removal, class change) performed by "animation-aware" directives.
* See {@link guide/animations#which-directives-support-animations- here} for a list of built-in
* directives that support animations.
* Performing computationally expensive or time-consuming operations on each call of the
* filtering function can make your animations sluggish.
*
*
* **Note:** If present, `customFilter` will be checked before
* {@link $animateProvider#classNameFilter classNameFilter}.
*
* @param {Function=} filterFn - The filter function which will be used to filter all animations.
* If a falsy value is returned, no animation will be performed. The function will be called
* with the following arguments:
* - **node** `{DOMElement}` - The DOM element to be animated.
* - **event** `{String}` - The name of the animation event (e.g. `enter`, `leave`, `addClass`
* etc).
* - **options** `{Object}` - A collection of options/styles used for the animation.
* @return {Function} The current filter function or `null` if there is none set.
*/
this.customFilter = function(filterFn) {
if (arguments.length === 1) {
customFilter = isFunction(filterFn) ? filterFn : null;
}
return customFilter;
};
/**
* @ngdoc method
* @name $animateProvider#classNameFilter
*
* @description
* Sets and/or returns the CSS class regular expression that is checked when performing
* an animation. Upon bootstrap the classNameFilter value is not set at all and will
* therefore enable $animate to attempt to perform an animation on any element that is triggered.
* When setting the `classNameFilter` value, animations will only be performed on elements
* that successfully match the filter expression. This in turn can boost performance
* for low-powered devices as well as applications containing a lot of structural operations.
*
* **Note:** If present, `classNameFilter` will be checked after
* {@link $animateProvider#customFilter customFilter}. If `customFilter` is present and returns
* false, `classNameFilter` will not be checked.
*
* @param {RegExp=} expression The className expression which will be checked against all animations
* @return {RegExp} The current CSS className expression value. If null then there is no expression value
*/
this.classNameFilter = function(expression) {
if (arguments.length === 1) {
classNameFilter = (expression instanceof RegExp) ? expression : null;
if (classNameFilter) {
var reservedRegex = new RegExp('[(\\s|\\/)]' + NG_ANIMATE_CLASSNAME + '[(\\s|\\/)]');
if (reservedRegex.test(classNameFilter.toString())) {
classNameFilter = null;
throw $animateMinErr('nongcls', '$animateProvider.classNameFilter(regex) prohibits accepting a regex value which matches/contains the "{0}" CSS class.', NG_ANIMATE_CLASSNAME);
}
}
}
return classNameFilter;
};
this.$get = ['$$animateQueue', function($$animateQueue) {
function domInsert(element, parentElement, afterElement) {
// if for some reason the previous element was removed
// from the dom sometime before this code runs then let's
// just stick to using the parent element as the anchor
if (afterElement) {
var afterNode = extractElementNode(afterElement);
if (afterNode && !afterNode.parentNode && !afterNode.previousElementSibling) {
afterElement = null;
}
}
if (afterElement) {
afterElement.after(element);
} else {
parentElement.prepend(element);
}
}
/**
* @ngdoc service
* @name $animate
* @description The $animate service exposes a series of DOM utility methods that provide support
* for animation hooks. The default behavior is the application of DOM operations, however,
* when an animation is detected (and animations are enabled), $animate will do the heavy lifting
* to ensure that animation runs with the triggered DOM operation.
*
* By default $animate doesn't trigger any animations. This is because the `ngAnimate` module isn't
* included and only when it is active then the animation hooks that `$animate` triggers will be
* functional. Once active then all structural `ng-` directives will trigger animations as they perform
* their DOM-related operations (enter, leave and move). Other directives such as `ngClass`,
* `ngShow`, `ngHide` and `ngMessages` also provide support for animations.
*
* It is recommended that the`$animate` service is always used when executing DOM-related procedures within directives.
*
* To learn more about enabling animation support, click here to visit the
* {@link ngAnimate ngAnimate module page}.
*/
return {
// we don't call it directly since non-existant arguments may
// be interpreted as null within the sub enabled function
/**
*
* @ngdoc method
* @name $animate#on
* @kind function
* @description Sets up an event listener to fire whenever the animation event (enter, leave, move, etc...)
* has fired on the given element or among any of its children. Once the listener is fired, the provided callback
* is fired with the following params:
*
* ```js
* $animate.on('enter', container,
* function callback(element, phase) {
* // cool we detected an enter animation within the container
* }
* );
* ```
*
*
* **Note**: Generally, the events that are fired correspond 1:1 to `$animate` method names,
* e.g. {@link ng.$animate#addClass addClass()} will fire `addClass`, and {@link ng.ngClass}
* will fire `addClass` if classes are added, and `removeClass` if classes are removed.
* However, there are two exceptions:
*
*
*
if both an {@link ng.$animate#addClass addClass()} and a
* {@link ng.$animate#removeClass removeClass()} action are performed during the same
* animation, the event fired will be `setClass`. This is true even for `ngClass`.
*
an {@link ng.$animate#animate animate()} call that adds and removes classes will fire
* the `setClass` event, but if it either removes or adds classes,
* it will fire `animate` instead.
*
*
*
*
* @param {string} event the animation event that will be captured (e.g. enter, leave, move, addClass, removeClass, etc...)
* @param {DOMElement} container the container element that will capture each of the animation events that are fired on itself
* as well as among its children
* @param {Function} callback the callback function that will be fired when the listener is triggered.
*
* The arguments present in the callback function are:
* * `element` - The captured DOM element that the animation was fired on.
* * `phase` - The phase of the animation. The two possible phases are **start** (when the animation starts) and **close** (when it ends).
* * `data` - an object with these properties:
* * addClass - `{string|null}` - space-separated CSS classes to add to the element
* * removeClass - `{string|null}` - space-separated CSS classes to remove from the element
* * from - `{Object|null}` - CSS properties & values at the beginning of the animation
* * to - `{Object|null}` - CSS properties & values at the end of the animation
*
* Note that the callback does not trigger a scope digest. Wrap your call into a
* {@link $rootScope.Scope#$apply scope.$apply} to propagate changes to the scope.
*/
on: $$animateQueue.on,
/**
*
* @ngdoc method
* @name $animate#off
* @kind function
* @description Deregisters an event listener based on the event which has been associated with the provided element. This method
* can be used in three different ways depending on the arguments:
*
* ```js
* // remove all the animation event listeners listening for `enter`
* $animate.off('enter');
*
* // remove listeners for all animation events from the container element
* $animate.off(container);
*
* // remove all the animation event listeners listening for `enter` on the given element and its children
* $animate.off('enter', container);
*
* // remove the event listener function provided by `callback` that is set
* // to listen for `enter` on the given `container` as well as its children
* $animate.off('enter', container, callback);
* ```
*
* @param {string|DOMElement} event|container the animation event (e.g. enter, leave, move,
* addClass, removeClass, etc...), or the container element. If it is the element, all other
* arguments are ignored.
* @param {DOMElement=} container the container element the event listener was placed on
* @param {Function=} callback the callback function that was registered as the listener
*/
off: $$animateQueue.off,
/**
* @ngdoc method
* @name $animate#pin
* @kind function
* @description Associates the provided element with a host parent element to allow the element to be animated even if it exists
* outside of the DOM structure of the AngularJS application. By doing so, any animation triggered via `$animate` can be issued on the
* element despite being outside the realm of the application or within another application. Say for example if the application
* was bootstrapped on an element that is somewhere inside of the `` tag, but we wanted to allow for an element to be situated
* as a direct child of `document.body`, then this can be achieved by pinning the element via `$animate.pin(element)`. Keep in mind
* that calling `$animate.pin(element, parentElement)` will not actually insert into the DOM anywhere; it will just create the association.
*
* Note that this feature is only active when the `ngAnimate` module is used.
*
* @param {DOMElement} element the external element that will be pinned
* @param {DOMElement} parentElement the host parent element that will be associated with the external element
*/
pin: $$animateQueue.pin,
/**
*
* @ngdoc method
* @name $animate#enabled
* @kind function
* @description Used to get and set whether animations are enabled or not on the entire application or on an element and its children. This
* function can be called in four ways:
*
* ```js
* // returns true or false
* $animate.enabled();
*
* // changes the enabled state for all animations
* $animate.enabled(false);
* $animate.enabled(true);
*
* // returns true or false if animations are enabled for an element
* $animate.enabled(element);
*
* // changes the enabled state for an element and its children
* $animate.enabled(element, true);
* $animate.enabled(element, false);
* ```
*
* @param {DOMElement=} element the element that will be considered for checking/setting the enabled state
* @param {boolean=} enabled whether or not the animations will be enabled for the element
*
* @return {boolean} whether or not animations are enabled
*/
enabled: $$animateQueue.enabled,
/**
* @ngdoc method
* @name $animate#cancel
* @kind function
* @description Cancels the provided animation and applies the end state of the animation.
* Note that this does not cancel the underlying operation, e.g. the setting of classes or
* adding the element to the DOM.
*
* @param {animationRunner} animationRunner An animation runner returned by an $animate function.
*
* @example
angular.module('animationExample', ['ngAnimate']).component('cancelExample', {
templateUrl: 'template.html',
controller: function($element, $animate) {
this.runner = null;
this.addClass = function() {
this.runner = $animate.addClass($element.find('div'), 'red');
var ctrl = this;
this.runner.finally(function() {
ctrl.runner = null;
});
};
this.removeClass = function() {
this.runner = $animate.removeClass($element.find('div'), 'red');
var ctrl = this;
this.runner.finally(function() {
ctrl.runner = null;
});
};
this.cancel = function() {
$animate.cancel(this.runner);
};
}
});
CSS-Animated Text
.red-add, .red-remove {
transition: all 4s cubic-bezier(0.250, 0.460, 0.450, 0.940);
}
.red,
.red-add.red-add-active {
color: #FF0000;
font-size: 40px;
}
.red-remove.red-remove-active {
font-size: 10px;
color: black;
}
*/
cancel: function(runner) {
if (runner.cancel) {
runner.cancel();
}
},
/**
*
* @ngdoc method
* @name $animate#enter
* @kind function
* @description Inserts the element into the DOM either after the `after` element (if provided) or
* as the first child within the `parent` element and then triggers an animation.
* A promise is returned that will be resolved during the next digest once the animation
* has completed.
*
* @param {DOMElement} element the element which will be inserted into the DOM
* @param {DOMElement} parent the parent element which will append the element as
* a child (so long as the after element is not present)
* @param {DOMElement=} after the sibling element after which the element will be appended
* @param {object=} options an optional collection of options/styles that will be applied to the element.
* The object can have the following properties:
*
* - **addClass** - `{string}` - space-separated CSS classes to add to element
* - **from** - `{Object}` - CSS properties & values at the beginning of animation. Must have matching `to`
* - **removeClass** - `{string}` - space-separated CSS classes to remove from element
* - **to** - `{Object}` - CSS properties & values at end of animation. Must have matching `from`
*
* @return {Runner} the animation runner
*/
enter: function(element, parent, after, options) {
parent = parent && jqLite(parent);
after = after && jqLite(after);
parent = parent || after.parent();
domInsert(element, parent, after);
return $$animateQueue.push(element, 'enter', prepareAnimateOptions(options));
},
/**
*
* @ngdoc method
* @name $animate#move
* @kind function
* @description Inserts (moves) the element into its new position in the DOM either after
* the `after` element (if provided) or as the first child within the `parent` element
* and then triggers an animation. A promise is returned that will be resolved
* during the next digest once the animation has completed.
*
* @param {DOMElement} element the element which will be moved into the new DOM position
* @param {DOMElement} parent the parent element which will append the element as
* a child (so long as the after element is not present)
* @param {DOMElement=} after the sibling element after which the element will be appended
* @param {object=} options an optional collection of options/styles that will be applied to the element.
* The object can have the following properties:
*
* - **addClass** - `{string}` - space-separated CSS classes to add to element
* - **from** - `{Object}` - CSS properties & values at the beginning of animation. Must have matching `to`
* - **removeClass** - `{string}` - space-separated CSS classes to remove from element
* - **to** - `{Object}` - CSS properties & values at end of animation. Must have matching `from`
*
* @return {Runner} the animation runner
*/
move: function(element, parent, after, options) {
parent = parent && jqLite(parent);
after = after && jqLite(after);
parent = parent || after.parent();
domInsert(element, parent, after);
return $$animateQueue.push(element, 'move', prepareAnimateOptions(options));
},
/**
* @ngdoc method
* @name $animate#leave
* @kind function
* @description Triggers an animation and then removes the element from the DOM.
* When the function is called a promise is returned that will be resolved during the next
* digest once the animation has completed.
*
* @param {DOMElement} element the element which will be removed from the DOM
* @param {object=} options an optional collection of options/styles that will be applied to the element.
* The object can have the following properties:
*
* - **addClass** - `{string}` - space-separated CSS classes to add to element
* - **from** - `{Object}` - CSS properties & values at the beginning of animation. Must have matching `to`
* - **removeClass** - `{string}` - space-separated CSS classes to remove from element
* - **to** - `{Object}` - CSS properties & values at end of animation. Must have matching `from`
*
* @return {Runner} the animation runner
*/
leave: function(element, options) {
return $$animateQueue.push(element, 'leave', prepareAnimateOptions(options), function() {
element.remove();
});
},
/**
* @ngdoc method
* @name $animate#addClass
* @kind function
*
* @description Triggers an addClass animation surrounding the addition of the provided CSS class(es). Upon
* execution, the addClass operation will only be handled after the next digest and it will not trigger an
* animation if element already contains the CSS class or if the class is removed at a later step.
* Note that class-based animations are treated differently compared to structural animations
* (like enter, move and leave) since the CSS classes may be added/removed at different points
* depending if CSS or JavaScript animations are used.
*
* @param {DOMElement} element the element which the CSS classes will be applied to
* @param {string} className the CSS class(es) that will be added (multiple classes are separated via spaces)
* @param {object=} options an optional collection of options/styles that will be applied to the element.
* The object can have the following properties:
*
* - **removeClass** - `{string}` - space-separated CSS classes to remove from element
* - **from** - `{Object}` - CSS properties & values at the beginning of animation. Must have matching `to`
* - **to** - `{Object}` - CSS properties & values at end of animation. Must have matching `from`
*
* @return {Runner} animationRunner the animation runner
*/
addClass: function(element, className, options) {
options = prepareAnimateOptions(options);
options.addClass = mergeClasses(options.addclass, className);
return $$animateQueue.push(element, 'addClass', options);
},
/**
* @ngdoc method
* @name $animate#removeClass
* @kind function
*
* @description Triggers a removeClass animation surrounding the removal of the provided CSS class(es). Upon
* execution, the removeClass operation will only be handled after the next digest and it will not trigger an
* animation if element does not contain the CSS class or if the class is added at a later step.
* Note that class-based animations are treated differently compared to structural animations
* (like enter, move and leave) since the CSS classes may be added/removed at different points
* depending if CSS or JavaScript animations are used.
*
* @param {DOMElement} element the element which the CSS classes will be applied to
* @param {string} className the CSS class(es) that will be removed (multiple classes are separated via spaces)
* @param {object=} options an optional collection of options/styles that will be applied to the element.
* The object can have the following properties:
*
* - **addClass** - `{string}` - space-separated CSS classes to add to element
* - **from** - `{Object}` - CSS properties & values at the beginning of animation. Must have matching `to`
* - **to** - `{Object}` - CSS properties & values at end of animation. Must have matching `from`
*
* @return {Runner} the animation runner
*/
removeClass: function(element, className, options) {
options = prepareAnimateOptions(options);
options.removeClass = mergeClasses(options.removeClass, className);
return $$animateQueue.push(element, 'removeClass', options);
},
/**
* @ngdoc method
* @name $animate#setClass
* @kind function
*
* @description Performs both the addition and removal of a CSS classes on an element and (during the process)
* triggers an animation surrounding the class addition/removal. Much like `$animate.addClass` and
* `$animate.removeClass`, `setClass` will only evaluate the classes being added/removed once a digest has
* passed. Note that class-based animations are treated differently compared to structural animations
* (like enter, move and leave) since the CSS classes may be added/removed at different points
* depending if CSS or JavaScript animations are used.
*
* @param {DOMElement} element the element which the CSS classes will be applied to
* @param {string} add the CSS class(es) that will be added (multiple classes are separated via spaces)
* @param {string} remove the CSS class(es) that will be removed (multiple classes are separated via spaces)
* @param {object=} options an optional collection of options/styles that will be applied to the element.
* The object can have the following properties:
*
* - **addClass** - `{string}` - space-separated CSS classes to add to element
* - **removeClass** - `{string}` - space-separated CSS classes to remove from element
* - **from** - `{Object}` - CSS properties & values at the beginning of animation. Must have matching `to`
* - **to** - `{Object}` - CSS properties & values at end of animation. Must have matching `from`
*
* @return {Runner} the animation runner
*/
setClass: function(element, add, remove, options) {
options = prepareAnimateOptions(options);
options.addClass = mergeClasses(options.addClass, add);
options.removeClass = mergeClasses(options.removeClass, remove);
return $$animateQueue.push(element, 'setClass', options);
},
/**
* @ngdoc method
* @name $animate#animate
* @kind function
*
* @description Performs an inline animation on the element which applies the provided to and from CSS styles to the element.
* If any detected CSS transition, keyframe or JavaScript matches the provided className value, then the animation will take
* on the provided styles. For example, if a transition animation is set for the given className, then the provided `from` and
* `to` styles will be applied alongside the given transition. If the CSS style provided in `from` does not have a corresponding
* style in `to`, the style in `from` is applied immediately, and no animation is run.
* If a JavaScript animation is detected then the provided styles will be given in as function parameters into the `animate`
* method (or as part of the `options` parameter):
*
* ```js
* ngModule.animation('.my-inline-animation', function() {
* return {
* animate : function(element, from, to, done, options) {
* //animation
* done();
* }
* }
* });
* ```
*
* @param {DOMElement} element the element which the CSS styles will be applied to
* @param {object} from the from (starting) CSS styles that will be applied to the element and across the animation.
* @param {object} to the to (destination) CSS styles that will be applied to the element and across the animation.
* @param {string=} className an optional CSS class that will be applied to the element for the duration of the animation. If
* this value is left as empty then a CSS class of `ng-inline-animate` will be applied to the element.
* (Note that if no animation is detected then this value will not be applied to the element.)
* @param {object=} options an optional collection of options/styles that will be applied to the element.
* The object can have the following properties:
*
* - **addClass** - `{string}` - space-separated CSS classes to add to element
* - **from** - `{Object}` - CSS properties & values at the beginning of animation. Must have matching `to`
* - **removeClass** - `{string}` - space-separated CSS classes to remove from element
* - **to** - `{Object}` - CSS properties & values at end of animation. Must have matching `from`
*
* @return {Runner} the animation runner
*/
animate: function(element, from, to, className, options) {
options = prepareAnimateOptions(options);
options.from = options.from ? extend(options.from, from) : from;
options.to = options.to ? extend(options.to, to) : to;
className = className || 'ng-inline-animate';
options.tempClasses = mergeClasses(options.tempClasses, className);
return $$animateQueue.push(element, 'animate', options);
}
};
}];
}];
var $$AnimateAsyncRunFactoryProvider = /** @this */ function() {
this.$get = ['$$rAF', function($$rAF) {
var waitQueue = [];
function waitForTick(fn) {
waitQueue.push(fn);
if (waitQueue.length > 1) return;
$$rAF(function() {
for (var i = 0; i < waitQueue.length; i++) {
waitQueue[i]();
}
waitQueue = [];
});
}
return function() {
var passed = false;
waitForTick(function() {
passed = true;
});
return function(callback) {
if (passed) {
callback();
} else {
waitForTick(callback);
}
};
};
}];
};
var $$AnimateRunnerFactoryProvider = /** @this */ function() {
this.$get = ['$q', '$sniffer', '$$animateAsyncRun', '$$isDocumentHidden', '$timeout',
function($q, $sniffer, $$animateAsyncRun, $$isDocumentHidden, $timeout) {
var INITIAL_STATE = 0;
var DONE_PENDING_STATE = 1;
var DONE_COMPLETE_STATE = 2;
AnimateRunner.chain = function(chain, callback) {
var index = 0;
next();
function next() {
if (index === chain.length) {
callback(true);
return;
}
chain[index](function(response) {
if (response === false) {
callback(false);
return;
}
index++;
next();
});
}
};
AnimateRunner.all = function(runners, callback) {
var count = 0;
var status = true;
forEach(runners, function(runner) {
runner.done(onProgress);
});
function onProgress(response) {
status = status && response;
if (++count === runners.length) {
callback(status);
}
}
};
function AnimateRunner(host) {
this.setHost(host);
var rafTick = $$animateAsyncRun();
var timeoutTick = function(fn) {
$timeout(fn, 0, false);
};
this._doneCallbacks = [];
this._tick = function(fn) {
if ($$isDocumentHidden()) {
timeoutTick(fn);
} else {
rafTick(fn);
}
};
this._state = 0;
}
AnimateRunner.prototype = {
setHost: function(host) {
this.host = host || {};
},
done: function(fn) {
if (this._state === DONE_COMPLETE_STATE) {
fn();
} else {
this._doneCallbacks.push(fn);
}
},
progress: noop,
getPromise: function() {
if (!this.promise) {
var self = this;
this.promise = $q(function(resolve, reject) {
self.done(function(status) {
if (status === false) {
reject();
} else {
resolve();
}
});
});
}
return this.promise;
},
then: function(resolveHandler, rejectHandler) {
return this.getPromise().then(resolveHandler, rejectHandler);
},
'catch': function(handler) {
return this.getPromise()['catch'](handler);
},
'finally': function(handler) {
return this.getPromise()['finally'](handler);
},
pause: function() {
if (this.host.pause) {
this.host.pause();
}
},
resume: function() {
if (this.host.resume) {
this.host.resume();
}
},
end: function() {
if (this.host.end) {
this.host.end();
}
this._resolve(true);
},
cancel: function() {
if (this.host.cancel) {
this.host.cancel();
}
this._resolve(false);
},
complete: function(response) {
var self = this;
if (self._state === INITIAL_STATE) {
self._state = DONE_PENDING_STATE;
self._tick(function() {
self._resolve(response);
});
}
},
_resolve: function(response) {
if (this._state !== DONE_COMPLETE_STATE) {
forEach(this._doneCallbacks, function(fn) {
fn(response);
});
this._doneCallbacks.length = 0;
this._state = DONE_COMPLETE_STATE;
}
}
};
return AnimateRunner;
}];
};
/* exported $CoreAnimateCssProvider */
/**
* @ngdoc service
* @name $animateCss
* @kind object
* @this
*
* @description
* This is the core version of `$animateCss`. By default, only when the `ngAnimate` is included,
* then the `$animateCss` service will actually perform animations.
*
* Click here {@link ngAnimate.$animateCss to read the documentation for $animateCss}.
*/
var $CoreAnimateCssProvider = function() {
this.$get = ['$$rAF', '$q', '$$AnimateRunner', function($$rAF, $q, $$AnimateRunner) {
return function(element, initialOptions) {
// all of the animation functions should create
// a copy of the options data, however, if a
// parent service has already created a copy then
// we should stick to using that
var options = initialOptions || {};
if (!options.$$prepared) {
options = copy(options);
}
// there is no point in applying the styles since
// there is no animation that goes on at all in
// this version of $animateCss.
if (options.cleanupStyles) {
options.from = options.to = null;
}
if (options.from) {
element.css(options.from);
options.from = null;
}
var closed, runner = new $$AnimateRunner();
return {
start: run,
end: run
};
function run() {
$$rAF(function() {
applyAnimationContents();
if (!closed) {
runner.complete();
}
closed = true;
});
return runner;
}
function applyAnimationContents() {
if (options.addClass) {
element.addClass(options.addClass);
options.addClass = null;
}
if (options.removeClass) {
element.removeClass(options.removeClass);
options.removeClass = null;
}
if (options.to) {
element.css(options.to);
options.to = null;
}
}
};
}];
};
/* global getHash: true, stripHash: false */
function getHash(url) {
var index = url.indexOf('#');
return index === -1 ? '' : url.substr(index);
}
function trimEmptyHash(url) {
return url.replace(/#$/, '');
}
/**
* ! This is a private undocumented service !
*
* @name $browser
* @requires $log
* @description
* This object has two goals:
*
* - hide all the global state in the browser caused by the window object
* - abstract away all the browser specific features and inconsistencies
*
* For tests we provide {@link ngMock.$browser mock implementation} of the `$browser`
* service, which can be used for convenient testing of the application without the interaction with
* the real browser apis.
*/
/**
* @param {object} window The global window object.
* @param {object} document jQuery wrapped document.
* @param {object} $log window.console or an object with the same interface.
* @param {object} $sniffer $sniffer service
*/
function Browser(window, document, $log, $sniffer, $$taskTrackerFactory) {
var self = this,
location = window.location,
history = window.history,
setTimeout = window.setTimeout,
clearTimeout = window.clearTimeout,
pendingDeferIds = {},
taskTracker = $$taskTrackerFactory($log);
self.isMock = false;
//////////////////////////////////////////////////////////////
// Task-tracking API
//////////////////////////////////////////////////////////////
// TODO(vojta): remove this temporary api
self.$$completeOutstandingRequest = taskTracker.completeTask;
self.$$incOutstandingRequestCount = taskTracker.incTaskCount;
// TODO(vojta): prefix this method with $$ ?
self.notifyWhenNoOutstandingRequests = taskTracker.notifyWhenNoPendingTasks;
//////////////////////////////////////////////////////////////
// URL API
//////////////////////////////////////////////////////////////
var cachedState, lastHistoryState,
lastBrowserUrl = location.href,
baseElement = document.find('base'),
pendingLocation = null,
getCurrentState = !$sniffer.history ? noop : function getCurrentState() {
try {
return history.state;
} catch (e) {
// MSIE can reportedly throw when there is no state (UNCONFIRMED).
}
};
cacheState();
/**
* @name $browser#url
*
* @description
* GETTER:
* Without any argument, this method just returns current value of `location.href` (with a
* trailing `#` stripped of if the hash is empty).
*
* SETTER:
* With at least one argument, this method sets url to new value.
* If html5 history api supported, `pushState`/`replaceState` is used, otherwise
* `location.href`/`location.replace` is used.
* Returns its own instance to allow chaining.
*
* NOTE: this api is intended for use only by the `$location` service. Please use the
* {@link ng.$location $location service} to change url.
*
* @param {string} url New url (when used as setter)
* @param {boolean=} replace Should new url replace current history record?
* @param {object=} state State object to use with `pushState`/`replaceState`
*/
self.url = function(url, replace, state) {
// In modern browsers `history.state` is `null` by default; treating it separately
// from `undefined` would cause `$browser.url('/foo')` to change `history.state`
// to undefined via `pushState`. Instead, let's change `undefined` to `null` here.
if (isUndefined(state)) {
state = null;
}
// Android Browser BFCache causes location, history reference to become stale.
if (location !== window.location) location = window.location;
if (history !== window.history) history = window.history;
// setter
if (url) {
var sameState = lastHistoryState === state;
// Normalize the inputted URL
url = urlResolve(url).href;
// Don't change anything if previous and current URLs and states match. This also prevents
// IE<10 from getting into redirect loop when in LocationHashbangInHtml5Url mode.
// See https://github.com/angular/angular.js/commit/ffb2701
if (lastBrowserUrl === url && (!$sniffer.history || sameState)) {
return self;
}
var sameBase = lastBrowserUrl && stripHash(lastBrowserUrl) === stripHash(url);
lastBrowserUrl = url;
lastHistoryState = state;
// Don't use history API if only the hash changed
// due to a bug in IE10/IE11 which leads
// to not firing a `hashchange` nor `popstate` event
// in some cases (see #9143).
if ($sniffer.history && (!sameBase || !sameState)) {
history[replace ? 'replaceState' : 'pushState'](state, '', url);
cacheState();
} else {
if (!sameBase) {
pendingLocation = url;
}
if (replace) {
location.replace(url);
} else if (!sameBase) {
location.href = url;
} else {
location.hash = getHash(url);
}
if (location.href !== url) {
pendingLocation = url;
}
}
if (pendingLocation) {
pendingLocation = url;
}
return self;
// getter
} else {
// - pendingLocation is needed as browsers don't allow to read out
// the new location.href if a reload happened or if there is a bug like in iOS 9 (see
// https://openradar.appspot.com/22186109).
return trimEmptyHash(pendingLocation || location.href);
}
};
/**
* @name $browser#state
*
* @description
* This method is a getter.
*
* Return history.state or null if history.state is undefined.
*
* @returns {object} state
*/
self.state = function() {
return cachedState;
};
var urlChangeListeners = [],
urlChangeInit = false;
function cacheStateAndFireUrlChange() {
pendingLocation = null;
fireStateOrUrlChange();
}
// This variable should be used *only* inside the cacheState function.
var lastCachedState = null;
function cacheState() {
// This should be the only place in $browser where `history.state` is read.
cachedState = getCurrentState();
cachedState = isUndefined(cachedState) ? null : cachedState;
// Prevent callbacks fo fire twice if both hashchange & popstate were fired.
if (equals(cachedState, lastCachedState)) {
cachedState = lastCachedState;
}
lastCachedState = cachedState;
lastHistoryState = cachedState;
}
function fireStateOrUrlChange() {
var prevLastHistoryState = lastHistoryState;
cacheState();
if (lastBrowserUrl === self.url() && prevLastHistoryState === cachedState) {
return;
}
lastBrowserUrl = self.url();
lastHistoryState = cachedState;
forEach(urlChangeListeners, function(listener) {
listener(self.url(), cachedState);
});
}
/**
* @name $browser#onUrlChange
*
* @description
* Register callback function that will be called, when url changes.
*
* It's only called when the url is changed from outside of AngularJS:
* - user types different url into address bar
* - user clicks on history (forward/back) button
* - user clicks on a link
*
* It's not called when url is changed by $browser.url() method
*
* The listener gets called with new url as parameter.
*
* NOTE: this api is intended for use only by the $location service. Please use the
* {@link ng.$location $location service} to monitor url changes in AngularJS apps.
*
* @param {function(string)} listener Listener function to be called when url changes.
* @return {function(string)} Returns the registered listener fn - handy if the fn is anonymous.
*/
self.onUrlChange = function(callback) {
// TODO(vojta): refactor to use node's syntax for events
if (!urlChangeInit) {
// We listen on both (hashchange/popstate) when available, as some browsers don't
// fire popstate when user changes the address bar and don't fire hashchange when url
// changed by push/replaceState
// html5 history api - popstate event
if ($sniffer.history) jqLite(window).on('popstate', cacheStateAndFireUrlChange);
// hashchange event
jqLite(window).on('hashchange', cacheStateAndFireUrlChange);
urlChangeInit = true;
}
urlChangeListeners.push(callback);
return callback;
};
/**
* @private
* Remove popstate and hashchange handler from window.
*
* NOTE: this api is intended for use only by $rootScope.
*/
self.$$applicationDestroyed = function() {
jqLite(window).off('hashchange popstate', cacheStateAndFireUrlChange);
};
/**
* Checks whether the url has changed outside of AngularJS.
* Needs to be exported to be able to check for changes that have been done in sync,
* as hashchange/popstate events fire in async.
*/
self.$$checkUrlChange = fireStateOrUrlChange;
//////////////////////////////////////////////////////////////
// Misc API
//////////////////////////////////////////////////////////////
/**
* @name $browser#baseHref
*
* @description
* Returns current
* (always relative - without domain)
*
* @returns {string} The current base href
*/
self.baseHref = function() {
var href = baseElement.attr('href');
return href ? href.replace(/^(https?:)?\/\/[^/]*/, '') : '';
};
/**
* @name $browser#defer
* @param {function()} fn A function, who's execution should be deferred.
* @param {number=} [delay=0] Number of milliseconds to defer the function execution.
* @param {string=} [taskType=DEFAULT_TASK_TYPE] The type of task that is deferred.
* @returns {*} DeferId that can be used to cancel the task via `$browser.defer.cancel()`.
*
* @description
* Executes a fn asynchronously via `setTimeout(fn, delay)`.
*
* Unlike when calling `setTimeout` directly, in test this function is mocked and instead of using
* `setTimeout` in tests, the fns are queued in an array, which can be programmatically flushed
* via `$browser.defer.flush()`.
*
*/
self.defer = function(fn, delay, taskType) {
var timeoutId;
delay = delay || 0;
taskType = taskType || taskTracker.DEFAULT_TASK_TYPE;
taskTracker.incTaskCount(taskType);
timeoutId = setTimeout(function() {
delete pendingDeferIds[timeoutId];
taskTracker.completeTask(fn, taskType);
}, delay);
pendingDeferIds[timeoutId] = taskType;
return timeoutId;
};
/**
* @name $browser#defer.cancel
*
* @description
* Cancels a deferred task identified with `deferId`.
*
* @param {*} deferId Token returned by the `$browser.defer` function.
* @returns {boolean} Returns `true` if the task hasn't executed yet and was successfully
* canceled.
*/
self.defer.cancel = function(deferId) {
if (pendingDeferIds.hasOwnProperty(deferId)) {
var taskType = pendingDeferIds[deferId];
delete pendingDeferIds[deferId];
clearTimeout(deferId);
taskTracker.completeTask(noop, taskType);
return true;
}
return false;
};
}
/** @this */
function $BrowserProvider() {
this.$get = ['$window', '$log', '$sniffer', '$document', '$$taskTrackerFactory',
function($window, $log, $sniffer, $document, $$taskTrackerFactory) {
return new Browser($window, $document, $log, $sniffer, $$taskTrackerFactory);
}];
}
/**
* @ngdoc service
* @name $cacheFactory
* @this
*
* @description
* Factory that constructs {@link $cacheFactory.Cache Cache} objects and gives access to
* them.
*
* ```js
*
* var cache = $cacheFactory('cacheId');
* expect($cacheFactory.get('cacheId')).toBe(cache);
* expect($cacheFactory.get('noSuchCacheId')).not.toBeDefined();
*
* cache.put("key", "value");
* cache.put("another key", "another value");
*
* // We've specified no options on creation
* expect(cache.info()).toEqual({id: 'cacheId', size: 2});
*
* ```
*
*
* @param {string} cacheId Name or id of the newly created cache.
* @param {object=} options Options object that specifies the cache behavior. Properties:
*
* - `{number=}` `capacity` — turns the cache into LRU cache.
*
* @returns {object} Newly created cache object with the following set of methods:
*
* - `{object}` `info()` — Returns id, size, and options of cache.
* - `{{*}}` `put({string} key, {*} value)` — Puts a new key-value pair into the cache and returns
* it.
* - `{{*}}` `get({string} key)` — Returns cached value for `key` or undefined for cache miss.
* - `{void}` `remove({string} key)` — Removes a key-value pair from the cache.
* - `{void}` `removeAll()` — Removes all cached values.
* - `{void}` `destroy()` — Removes references to this cache from $cacheFactory.
*
* @example
Cached Values
:
Cache Info
:
angular.module('cacheExampleApp', []).
controller('CacheController', ['$scope', '$cacheFactory', function($scope, $cacheFactory) {
$scope.keys = [];
$scope.cache = $cacheFactory('cacheId');
$scope.put = function(key, value) {
if (angular.isUndefined($scope.cache.get(key))) {
$scope.keys.push(key);
}
$scope.cache.put(key, angular.isUndefined(value) ? null : value);
};
}]);
p {
margin: 10px 0 3px;
}
*/
function $CacheFactoryProvider() {
this.$get = function() {
var caches = {};
function cacheFactory(cacheId, options) {
if (cacheId in caches) {
throw minErr('$cacheFactory')('iid', 'CacheId \'{0}\' is already taken!', cacheId);
}
var size = 0,
stats = extend({}, options, {id: cacheId}),
data = createMap(),
capacity = (options && options.capacity) || Number.MAX_VALUE,
lruHash = createMap(),
freshEnd = null,
staleEnd = null;
/**
* @ngdoc type
* @name $cacheFactory.Cache
*
* @description
* A cache object used to store and retrieve data, primarily used by
* {@link $templateRequest $templateRequest} and the {@link ng.directive:script script}
* directive to cache templates and other data.
*
* ```js
* angular.module('superCache')
* .factory('superCache', ['$cacheFactory', function($cacheFactory) {
* return $cacheFactory('super-cache');
* }]);
* ```
*
* Example test:
*
* ```js
* it('should behave like a cache', inject(function(superCache) {
* superCache.put('key', 'value');
* superCache.put('another key', 'another value');
*
* expect(superCache.info()).toEqual({
* id: 'super-cache',
* size: 2
* });
*
* superCache.remove('another key');
* expect(superCache.get('another key')).toBeUndefined();
*
* superCache.removeAll();
* expect(superCache.info()).toEqual({
* id: 'super-cache',
* size: 0
* });
* }));
* ```
*/
return (caches[cacheId] = {
/**
* @ngdoc method
* @name $cacheFactory.Cache#put
* @kind function
*
* @description
* Inserts a named entry into the {@link $cacheFactory.Cache Cache} object to be
* retrieved later, and incrementing the size of the cache if the key was not already
* present in the cache. If behaving like an LRU cache, it will also remove stale
* entries from the set.
*
* It will not insert undefined values into the cache.
*
* @param {string} key the key under which the cached data is stored.
* @param {*} value the value to store alongside the key. If it is undefined, the key
* will not be stored.
* @returns {*} the value stored.
*/
put: function(key, value) {
if (isUndefined(value)) return;
if (capacity < Number.MAX_VALUE) {
var lruEntry = lruHash[key] || (lruHash[key] = {key: key});
refresh(lruEntry);
}
if (!(key in data)) size++;
data[key] = value;
if (size > capacity) {
this.remove(staleEnd.key);
}
return value;
},
/**
* @ngdoc method
* @name $cacheFactory.Cache#get
* @kind function
*
* @description
* Retrieves named data stored in the {@link $cacheFactory.Cache Cache} object.
*
* @param {string} key the key of the data to be retrieved
* @returns {*} the value stored.
*/
get: function(key) {
if (capacity < Number.MAX_VALUE) {
var lruEntry = lruHash[key];
if (!lruEntry) return;
refresh(lruEntry);
}
return data[key];
},
/**
* @ngdoc method
* @name $cacheFactory.Cache#remove
* @kind function
*
* @description
* Removes an entry from the {@link $cacheFactory.Cache Cache} object.
*
* @param {string} key the key of the entry to be removed
*/
remove: function(key) {
if (capacity < Number.MAX_VALUE) {
var lruEntry = lruHash[key];
if (!lruEntry) return;
if (lruEntry === freshEnd) freshEnd = lruEntry.p;
if (lruEntry === staleEnd) staleEnd = lruEntry.n;
link(lruEntry.n,lruEntry.p);
delete lruHash[key];
}
if (!(key in data)) return;
delete data[key];
size--;
},
/**
* @ngdoc method
* @name $cacheFactory.Cache#removeAll
* @kind function
*
* @description
* Clears the cache object of any entries.
*/
removeAll: function() {
data = createMap();
size = 0;
lruHash = createMap();
freshEnd = staleEnd = null;
},
/**
* @ngdoc method
* @name $cacheFactory.Cache#destroy
* @kind function
*
* @description
* Destroys the {@link $cacheFactory.Cache Cache} object entirely,
* removing it from the {@link $cacheFactory $cacheFactory} set.
*/
destroy: function() {
data = null;
stats = null;
lruHash = null;
delete caches[cacheId];
},
/**
* @ngdoc method
* @name $cacheFactory.Cache#info
* @kind function
*
* @description
* Retrieve information regarding a particular {@link $cacheFactory.Cache Cache}.
*
* @returns {object} an object with the following properties:
*
*
**id**: the id of the cache instance
*
**size**: the number of entries kept in the cache instance
*
**...**: any additional properties from the options object when creating the
* cache.
*
*/
info: function() {
return extend({}, stats, {size: size});
}
});
/**
* makes the `entry` the freshEnd of the LRU linked list
*/
function refresh(entry) {
if (entry !== freshEnd) {
if (!staleEnd) {
staleEnd = entry;
} else if (staleEnd === entry) {
staleEnd = entry.n;
}
link(entry.n, entry.p);
link(entry, freshEnd);
freshEnd = entry;
freshEnd.n = null;
}
}
/**
* bidirectionally links two entries of the LRU linked list
*/
function link(nextEntry, prevEntry) {
if (nextEntry !== prevEntry) {
if (nextEntry) nextEntry.p = prevEntry; //p stands for previous, 'prev' didn't minify
if (prevEntry) prevEntry.n = nextEntry; //n stands for next, 'next' didn't minify
}
}
}
/**
* @ngdoc method
* @name $cacheFactory#info
*
* @description
* Get information about all the caches that have been created
*
* @returns {Object} - key-value map of `cacheId` to the result of calling `cache#info`
*/
cacheFactory.info = function() {
var info = {};
forEach(caches, function(cache, cacheId) {
info[cacheId] = cache.info();
});
return info;
};
/**
* @ngdoc method
* @name $cacheFactory#get
*
* @description
* Get access to a cache object by the `cacheId` used when it was created.
*
* @param {string} cacheId Name or id of a cache to access.
* @returns {object} Cache object identified by the cacheId or undefined if no such cache.
*/
cacheFactory.get = function(cacheId) {
return caches[cacheId];
};
return cacheFactory;
};
}
/**
* @ngdoc service
* @name $templateCache
* @this
*
* @description
* `$templateCache` is a {@link $cacheFactory.Cache Cache object} created by the
* {@link ng.$cacheFactory $cacheFactory}.
*
* The first time a template is used, it is loaded in the template cache for quick retrieval. You
* can load templates directly into the cache in a `script` tag, by using {@link $templateRequest},
* or by consuming the `$templateCache` service directly.
*
* Adding via the `script` tag:
*
* ```html
*
* ```
*
* **Note:** the `script` tag containing the template does not need to be included in the `head` of
* the document, but it must be a descendent of the {@link ng.$rootElement $rootElement} (e.g.
* element with {@link ngApp} attribute), otherwise the template will be ignored.
*
* Adding via the `$templateCache` service:
*
* ```js
* var myApp = angular.module('myApp', []);
* myApp.run(function($templateCache) {
* $templateCache.put('templateId.html', 'This is the content of the template');
* });
* ```
*
* To retrieve the template later, simply use it in your component:
* ```js
* myApp.component('myComponent', {
* templateUrl: 'templateId.html'
* });
* ```
*
* or get it via the `$templateCache` service:
* ```js
* $templateCache.get('templateId.html')
* ```
*
*/
function $TemplateCacheProvider() {
this.$get = ['$cacheFactory', function($cacheFactory) {
return $cacheFactory('templates');
}];
}
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Any commits to this file should be reviewed with security in mind. *
* Changes to this file can potentially create security vulnerabilities. *
* An approval from 2 Core members with history of modifying *
* this file is required. *
* *
* Does the change somehow allow for arbitrary javascript to be executed? *
* Or allows for someone to change the prototype of built-in objects? *
* Or gives undesired access to variables like document or window? *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/* ! VARIABLE/FUNCTION NAMING CONVENTIONS THAT APPLY TO THIS FILE!
*
* DOM-related variables:
*
* - "node" - DOM Node
* - "element" - DOM Element or Node
* - "$node" or "$element" - jqLite-wrapped node or element
*
*
* Compiler related stuff:
*
* - "linkFn" - linking fn of a single directive
* - "nodeLinkFn" - function that aggregates all linking fns for a particular node
* - "childLinkFn" - function that aggregates all linking fns for child nodes of a particular node
* - "compositeLinkFn" - function that aggregates all linking fns for a compilation root (nodeList)
*/
/**
* @ngdoc service
* @name $compile
* @kind function
*
* @description
* Compiles an HTML string or DOM into a template and produces a template function, which
* can then be used to link {@link ng.$rootScope.Scope `scope`} and the template together.
*
* The compilation is a process of walking the DOM tree and matching DOM elements to
* {@link ng.$compileProvider#directive directives}.
*
*
* **Note:** This document is an in-depth reference of all directive options.
* For a gentle introduction to directives with examples of common use cases,
* see the {@link guide/directive directive guide}.
*
*
* ## Comprehensive Directive API
*
* There are many different options for a directive.
*
* The difference resides in the return value of the factory function.
* You can either return a {@link $compile#directive-definition-object Directive Definition Object (see below)}
* that defines the directive properties, or just the `postLink` function (all other properties will have
* the default values).
*
*
* **Best Practice:** It's recommended to use the "directive definition object" form.
*
* **Note:** Any unspecified options will use the default value. You can see the default values below.
*
*
* Therefore the above can be simplified as:
*
* ```js
* var myModule = angular.module(...);
*
* myModule.directive('directiveName', function factory(injectables) {
* var directiveDefinitionObject = {
* link: function postLink(scope, iElement, iAttrs) { ... }
* };
* return directiveDefinitionObject;
* // or
* // return function postLink(scope, iElement, iAttrs) { ... }
* });
* ```
*
* ### Life-cycle hooks
* Directive controllers can provide the following methods that are called by AngularJS at points in the life-cycle of the
* directive:
* * `$onInit()` - Called on each controller after all the controllers on an element have been constructed and
* had their bindings initialized (and before the pre & post linking functions for the directives on
* this element). This is a good place to put initialization code for your controller.
* * `$onChanges(changesObj)` - Called whenever one-way (`<`) or interpolation (`@`) bindings are updated. The
* `changesObj` is a hash whose keys are the names of the bound properties that have changed, and the values are an
* object of the form `{ currentValue, previousValue, isFirstChange() }`. Use this hook to trigger updates within a
* component such as cloning the bound value to prevent accidental mutation of the outer value. Note that this will
* also be called when your bindings are initialized.
* * `$doCheck()` - Called on each turn of the digest cycle. Provides an opportunity to detect and act on
* changes. Any actions that you wish to take in response to the changes that you detect must be
* invoked from this hook; implementing this has no effect on when `$onChanges` is called. For example, this hook
* could be useful if you wish to perform a deep equality check, or to check a Date object, changes to which would not
* be detected by AngularJS's change detector and thus not trigger `$onChanges`. This hook is invoked with no arguments;
* if detecting changes, you must store the previous value(s) for comparison to the current values.
* * `$onDestroy()` - Called on a controller when its containing scope is destroyed. Use this hook for releasing
* external resources, watches and event handlers. Note that components have their `$onDestroy()` hooks called in
* the same order as the `$scope.$broadcast` events are triggered, which is top down. This means that parent
* components will have their `$onDestroy()` hook called before child components.
* * `$postLink()` - Called after this controller's element and its children have been linked. Similar to the post-link
* function this hook can be used to set up DOM event handlers and do direct DOM manipulation.
* Note that child elements that contain `templateUrl` directives will not have been compiled and linked since
* they are waiting for their template to load asynchronously and their own compilation and linking has been
* suspended until that occurs.
*
* #### Comparison with life-cycle hooks in the new Angular
* The new Angular also uses life-cycle hooks for its components. While the AngularJS life-cycle hooks are similar there are
* some differences that you should be aware of, especially when it comes to moving your code from AngularJS to Angular:
*
* * AngularJS hooks are prefixed with `$`, such as `$onInit`. Angular hooks are prefixed with `ng`, such as `ngOnInit`.
* * AngularJS hooks can be defined on the controller prototype or added to the controller inside its constructor.
* In Angular you can only define hooks on the prototype of the Component class.
* * Due to the differences in change-detection, you may get many more calls to `$doCheck` in AngularJS than you would to
* `ngDoCheck` in Angular.
* * Changes to the model inside `$doCheck` will trigger new turns of the digest loop, which will cause the changes to be
* propagated throughout the application.
* Angular does not allow the `ngDoCheck` hook to trigger a change outside of the component. It will either throw an
* error or do nothing depending upon the state of `enableProdMode()`.
*
* #### Life-cycle hook examples
*
* This example shows how you can check for mutations to a Date object even though the identity of the object
* has not changed.
*
*
*
* angular.module('do-check-module', [])
* .component('app', {
* template:
* 'Month: ' +
* 'Date: {{ $ctrl.date }}' +
* '',
* controller: function() {
* this.date = new Date();
* this.month = this.date.getMonth();
* this.updateDate = function() {
* this.date.setMonth(this.month);
* };
* }
* })
* .component('test', {
* bindings: { date: '<' },
* template:
* '
{{ $ctrl.log | json }}
',
* controller: function() {
* var previousValue;
* this.log = [];
* this.$doCheck = function() {
* var currentValue = this.date && this.date.valueOf();
* if (previousValue !== currentValue) {
* this.log.push('doCheck: date mutated: ' + this.date);
* previousValue = currentValue;
* }
* };
* }
* });
*
*
*
*
*
*
* This example show how you might use `$doCheck` to trigger changes in your component's inputs even if the
* actual identity of the component doesn't change. (Be aware that cloning and deep equality checks on large
* arrays or objects can have a negative impact on your application performance.)
*
*
*
*
',
* controller: function() {
* this.log = [];
*
* this.$doCheck = function() {
* if (this.items_ref !== this.items) {
* this.log.push('doCheck: items changed');
* this.items_ref = this.items;
* }
* if (!angular.equals(this.items_clone, this.items)) {
* this.log.push('doCheck: items mutated');
* this.items_clone = angular.copy(this.items);
* }
* };
* }
* });
*
*
*
*
* ### Directive Definition Object
*
* The directive definition object provides instructions to the {@link ng.$compile
* compiler}. The attributes are:
*
* #### `multiElement`
* When this property is set to true (default is `false`), the HTML compiler will collect DOM nodes between
* nodes with the attributes `directive-name-start` and `directive-name-end`, and group them
* together as the directive elements. It is recommended that this feature be used on directives
* which are not strictly behavioral (such as {@link ngClick}), and which
* do not manipulate or replace child nodes (such as {@link ngInclude}).
*
* #### `priority`
* When there are multiple directives defined on a single DOM element, sometimes it
* is necessary to specify the order in which the directives are applied. The `priority` is used
* to sort the directives before their `compile` functions get called. Priority is defined as a
* number. Directives with greater numerical `priority` are compiled first. Pre-link functions
* are also run in priority order, but post-link functions are run in reverse order. The order
* of directives with the same priority is undefined. The default priority is `0`.
*
* #### `terminal`
* If set to true then the current `priority` will be the last set of directives
* which will execute (any directives at the current priority will still execute
* as the order of execution on same `priority` is undefined). Note that expressions
* and other directives used in the directive's template will also be excluded from execution.
*
* #### `scope`
* The scope property can be `false`, `true`, or an object:
*
* * **`false` (default):** No scope will be created for the directive. The directive will use its
* parent's scope.
*
* * **`true`:** A new child scope that prototypically inherits from its parent will be created for
* the directive's element. If multiple directives on the same element request a new scope,
* only one new scope is created.
*
* * **`{...}` (an object hash):** A new "isolate" scope is created for the directive's template.
* The 'isolate' scope differs from normal scope in that it does not prototypically
* inherit from its parent scope. This is useful when creating reusable components, which should not
* accidentally read or modify data in the parent scope. Note that an isolate scope
* directive without a `template` or `templateUrl` will not apply the isolate scope
* to its children elements.
*
* The 'isolate' scope object hash defines a set of local scope properties derived from attributes on the
* directive's element. These local properties are useful for aliasing values for templates. The keys in
* the object hash map to the name of the property on the isolate scope; the values define how the property
* is bound to the parent scope, via matching attributes on the directive's element:
*
* * `@` or `@attr` - bind a local scope property to the value of DOM attribute. The result is
* always a string since DOM attributes are strings. If no `attr` name is specified then the
* attribute name is assumed to be the same as the local name. Given `` and the isolate scope definition `scope: { localName:'@myAttr' }`,
* the directive's scope property `localName` will reflect the interpolated value of `hello
* {{name}}`. As the `name` attribute changes so will the `localName` property on the directive's
* scope. The `name` is read from the parent scope (not the directive's scope).
*
* * `=` or `=attr` - set up a bidirectional binding between a local scope property and an expression
* passed via the attribute `attr`. The expression is evaluated in the context of the parent scope.
* If no `attr` name is specified then the attribute name is assumed to be the same as the local
* name. Given `` and the isolate scope definition `scope: {
* localModel: '=myAttr' }`, the property `localModel` on the directive's scope will reflect the
* value of `parentModel` on the parent scope. Changes to `parentModel` will be reflected in
* `localModel` and vice versa. If the binding expression is non-assignable, or if the attribute
* isn't optional and doesn't exist, an exception
* ({@link error/$compile/nonassign `$compile:nonassign`}) will be thrown upon discovering changes
* to the local value, since it will be impossible to sync them back to the parent scope.
*
* By default, the {@link ng.$rootScope.Scope#$watch `$watch`}
* method is used for tracking changes, and the equality check is based on object identity.
* However, if an object literal or an array literal is passed as the binding expression, the
* equality check is done by value (using the {@link angular.equals} function). It's also possible
* to watch the evaluated value shallowly with {@link ng.$rootScope.Scope#$watchCollection
* `$watchCollection`}: use `=*` or `=*attr`
*
* * `<` or `` and directive definition of
* `scope: { localModel:'` and the isolate scope definition `scope: {
* localFn:'&myAttr' }`, the isolate scope property `localFn` will point to a function wrapper for
* the `count = count + value` expression. Often it's desirable to pass data from the isolated scope
* via an expression to the parent scope. This can be done by passing a map of local variable names
* and values into the expression wrapper fn. For example, if the expression is `increment(amount)`
* then we can specify the amount value by calling the `localFn` as `localFn({amount: 22})`.
*
* All 4 kinds of bindings (`@`, `=`, `<`, and `&`) can be made optional by adding `?` to the expression.
* The marker must come after the mode and before the attribute name.
* See the {@link error/$compile/iscp Invalid Isolate Scope Definition error} for definition examples.
* This is useful to refine the interface directives provide.
* One subtle difference between optional and non-optional happens **when the binding attribute is not
* set**:
* - the binding is optional: the property will not be defined
* - the binding is not optional: the property is defined
*
* ```js
*app.directive('testDir', function() {
return {
scope: {
notoptional: '=',
optional: '=?',
},
bindToController: true,
controller: function() {
this.$onInit = function() {
console.log(this.hasOwnProperty('notoptional')) // true
console.log(this.hasOwnProperty('optional')) // false
}
}
}
})
*```
*
*
* ##### Combining directives with different scope defintions
*
* In general it's possible to apply more than one directive to one element, but there might be limitations
* depending on the type of scope required by the directives. The following points will help explain these limitations.
* For simplicity only two directives are taken into account, but it is also applicable for several directives:
*
* * **no scope** + **no scope** => Two directives which don't require their own scope will use their parent's scope
* * **child scope** + **no scope** => Both directives will share one single child scope
* * **child scope** + **child scope** => Both directives will share one single child scope
* * **isolated scope** + **no scope** => The isolated directive will use it's own created isolated scope. The other directive will use
* its parent's scope
* * **isolated scope** + **child scope** => **Won't work!** Only one scope can be related to one element. Therefore these directives cannot
* be applied to the same element.
* * **isolated scope** + **isolated scope** => **Won't work!** Only one scope can be related to one element. Therefore these directives
* cannot be applied to the same element.
*
*
* #### `bindToController`
* This property is used to bind scope properties directly to the controller. It can be either
* `true` or an object hash with the same format as the `scope` property.
*
* When an isolate scope is used for a directive (see above), `bindToController: true` will
* allow a component to have its properties bound to the controller, rather than to scope.
*
* After the controller is instantiated, the initial values of the isolate scope bindings will be bound to the controller
* properties. You can access these bindings once they have been initialized by providing a controller method called
* `$onInit`, which is called after all the controllers on an element have been constructed and had their bindings
* initialized.
*
* It is also possible to set `bindToController` to an object hash with the same format as the `scope` property.
* This will set up the scope bindings to the controller directly. Note that `scope` can still be used
* to define which kind of scope is created. By default, no scope is created. Use `scope: {}` to create an isolate
* scope (useful for component directives).
*
* If both `bindToController` and `scope` are defined and have object hashes, `bindToController` overrides `scope`.
*
*
* #### `controller`
* Controller constructor function. The controller is instantiated before the
* pre-linking phase and can be accessed by other directives (see
* `require` attribute). This allows the directives to communicate with each other and augment
* each other's behavior. The controller is injectable (and supports bracket notation) with the following locals:
*
* * `$scope` - Current scope associated with the element
* * `$element` - Current element
* * `$attrs` - Current attributes object for the element
* * `$transclude` - A transclude linking function pre-bound to the correct transclusion scope:
* `function([scope], cloneLinkingFn, futureParentElement, slotName)`:
* * `scope`: (optional) override the scope.
* * `cloneLinkingFn`: (optional) argument to create clones of the original transcluded content.
* * `futureParentElement` (optional):
* * defines the parent to which the `cloneLinkingFn` will add the cloned elements.
* * default: `$element.parent()` resp. `$element` for `transclude:'element'` resp. `transclude:true`.
* * only needed for transcludes that are allowed to contain non html elements (e.g. SVG elements)
* and when the `cloneLinkingFn` is passed,
* as those elements need to created and cloned in a special way when they are defined outside their
* usual containers (e.g. like `