diff --git a/.github/actions/javascript/awaitStagingDeploys/awaitStagingDeploys.js b/.github/actions/javascript/awaitStagingDeploys/awaitStagingDeploys.js index 02cdcfa5e11f..950a8e7092cc 100644 --- a/.github/actions/javascript/awaitStagingDeploys/awaitStagingDeploys.js +++ b/.github/actions/javascript/awaitStagingDeploys/awaitStagingDeploys.js @@ -5,46 +5,59 @@ const GitHubUtils = require('../../../libs/GithubUtils'); const {promiseDoWhile} = require('../../../libs/promiseWhile'); function run() { + console.info('[awaitStagingDeploys] run()'); + console.info('[awaitStagingDeploys] ActionUtils', ActionUtils); + console.info('[awaitStagingDeploys] GitHubUtils', GitHubUtils); + console.info('[awaitStagingDeploys] promiseDoWhile', promiseDoWhile); + const tag = ActionUtils.getStringInput('TAG', {required: false}); + console.info('[awaitStagingDeploys] run() tag', tag); + let currentStagingDeploys = []; + + console.info('[awaitStagingDeploys] run() _.throttle', _.throttle); + + const throttleFunc = () => + Promise.all([ + // These are active deploys + GitHubUtils.octokit.actions.listWorkflowRuns({ + owner: CONST.GITHUB_OWNER, + repo: CONST.APP_REPO, + workflow_id: 'platformDeploy.yml', + event: 'push', + branch: tag, + }), + + // These have the potential to become active deploys, so we need to wait for them to finish as well (unless we're looking for a specific tag) + // In this context, we'll refer to unresolved preDeploy workflow runs as staging deploys as well + !tag && + GitHubUtils.octokit.actions.listWorkflowRuns({ + owner: CONST.GITHUB_OWNER, + repo: CONST.APP_REPO, + workflow_id: 'preDeploy.yml', + }), + ]) + .then((responses) => { + const workflowRuns = responses[0].data.workflow_runs; + if (!tag) { + workflowRuns.push(...responses[1].data.workflow_runs); + } + return workflowRuns; + }) + .then((workflowRuns) => (currentStagingDeploys = _.filter(workflowRuns, (workflowRun) => workflowRun.status !== 'completed'))) + .then(() => + console.log( + _.isEmpty(currentStagingDeploys) + ? 'No current staging deploys found' + : `Found ${currentStagingDeploys.length} staging deploy${currentStagingDeploys.length > 1 ? 's' : ''} still running...`, + ), + ); + console.info('[awaitStagingDeploys] run() throttleFunc', throttleFunc); + return promiseDoWhile( () => !_.isEmpty(currentStagingDeploys), _.throttle( - () => - Promise.all([ - // These are active deploys - GitHubUtils.octokit.actions.listWorkflowRuns({ - owner: CONST.GITHUB_OWNER, - repo: CONST.APP_REPO, - workflow_id: 'platformDeploy.yml', - event: 'push', - branch: tag, - }), - - // These have the potential to become active deploys, so we need to wait for them to finish as well (unless we're looking for a specific tag) - // In this context, we'll refer to unresolved preDeploy workflow runs as staging deploys as well - !tag && - GitHubUtils.octokit.actions.listWorkflowRuns({ - owner: CONST.GITHUB_OWNER, - repo: CONST.APP_REPO, - workflow_id: 'preDeploy.yml', - }), - ]) - .then((responses) => { - const workflowRuns = responses[0].data.workflow_runs; - if (!tag) { - workflowRuns.push(...responses[1].data.workflow_runs); - } - return workflowRuns; - }) - .then((workflowRuns) => (currentStagingDeploys = _.filter(workflowRuns, (workflowRun) => workflowRun.status !== 'completed'))) - .then(() => - console.log( - _.isEmpty(currentStagingDeploys) - ? 'No current staging deploys found' - : `Found ${currentStagingDeploys.length} staging deploy${currentStagingDeploys.length > 1 ? 's' : ''} still running...`, - ), - ), + throttleFunc, // Poll every 60 seconds instead of every 10 seconds GitHubUtils.POLL_RATE * 6, diff --git a/.github/actions/javascript/awaitStagingDeploys/index.js b/.github/actions/javascript/awaitStagingDeploys/index.js index 66c6efd7b67f..6dc6a4a213e3 100644 --- a/.github/actions/javascript/awaitStagingDeploys/index.js +++ b/.github/actions/javascript/awaitStagingDeploys/index.js @@ -14,46 +14,59 @@ const GitHubUtils = __nccwpck_require__(9296); const {promiseDoWhile} = __nccwpck_require__(4502); function run() { + console.info('[awaitStagingDeploys] run()'); + console.info('[awaitStagingDeploys] ActionUtils', ActionUtils); + console.info('[awaitStagingDeploys] GitHubUtils', GitHubUtils); + console.info('[awaitStagingDeploys] promiseDoWhile', promiseDoWhile); + const tag = ActionUtils.getStringInput('TAG', {required: false}); + console.info('[awaitStagingDeploys] run() tag', tag); + let currentStagingDeploys = []; + + console.info('[awaitStagingDeploys] run() _.throttle', _.throttle); + + const throttleFunc = () => + Promise.all([ + // These are active deploys + GitHubUtils.octokit.actions.listWorkflowRuns({ + owner: CONST.GITHUB_OWNER, + repo: CONST.APP_REPO, + workflow_id: 'platformDeploy.yml', + event: 'push', + branch: tag, + }), + + // These have the potential to become active deploys, so we need to wait for them to finish as well (unless we're looking for a specific tag) + // In this context, we'll refer to unresolved preDeploy workflow runs as staging deploys as well + !tag && + GitHubUtils.octokit.actions.listWorkflowRuns({ + owner: CONST.GITHUB_OWNER, + repo: CONST.APP_REPO, + workflow_id: 'preDeploy.yml', + }), + ]) + .then((responses) => { + const workflowRuns = responses[0].data.workflow_runs; + if (!tag) { + workflowRuns.push(...responses[1].data.workflow_runs); + } + return workflowRuns; + }) + .then((workflowRuns) => (currentStagingDeploys = _.filter(workflowRuns, (workflowRun) => workflowRun.status !== 'completed'))) + .then(() => + console.log( + _.isEmpty(currentStagingDeploys) + ? 'No current staging deploys found' + : `Found ${currentStagingDeploys.length} staging deploy${currentStagingDeploys.length > 1 ? 's' : ''} still running...`, + ), + ); + console.info('[awaitStagingDeploys] run() throttleFunc', throttleFunc); + return promiseDoWhile( () => !_.isEmpty(currentStagingDeploys), _.throttle( - () => - Promise.all([ - // These are active deploys - GitHubUtils.octokit.actions.listWorkflowRuns({ - owner: CONST.GITHUB_OWNER, - repo: CONST.APP_REPO, - workflow_id: 'platformDeploy.yml', - event: 'push', - branch: tag, - }), - - // These have the potential to become active deploys, so we need to wait for them to finish as well (unless we're looking for a specific tag) - // In this context, we'll refer to unresolved preDeploy workflow runs as staging deploys as well - !tag && - GitHubUtils.octokit.actions.listWorkflowRuns({ - owner: CONST.GITHUB_OWNER, - repo: CONST.APP_REPO, - workflow_id: 'preDeploy.yml', - }), - ]) - .then((responses) => { - const workflowRuns = responses[0].data.workflow_runs; - if (!tag) { - workflowRuns.push(...responses[1].data.workflow_runs); - } - return workflowRuns; - }) - .then((workflowRuns) => (currentStagingDeploys = _.filter(workflowRuns, (workflowRun) => workflowRun.status !== 'completed'))) - .then(() => - console.log( - _.isEmpty(currentStagingDeploys) - ? 'No current staging deploys found' - : `Found ${currentStagingDeploys.length} staging deploy${currentStagingDeploys.length > 1 ? 's' : ''} still running...`, - ), - ), + throttleFunc, // Poll every 60 seconds instead of every 10 seconds GitHubUtils.POLL_RATE * 6, @@ -151,12 +164,16 @@ module.exports = CONST; * @returns {Promise} */ function promiseWhile(condition, action) { + console.info('[promiseWhile] promiseWhile()'); + return new Promise((resolve, reject) => { const loop = function () { if (!condition()) { resolve(); } else { - Promise.resolve(action()).then(loop).catch(reject); + const actionResult = action(); + console.info('[promiseWhile] promiseWhile() actionResult', actionResult); + Promise.resolve(actionResult).then(loop).catch(reject); } }; loop(); @@ -171,8 +188,13 @@ function promiseWhile(condition, action) { * @returns {Promise} */ function promiseDoWhile(condition, action) { + console.info('[promiseWhile] promiseDoWhile()'); + return new Promise((resolve, reject) => { - action() + console.info('[promiseWhile] promiseDoWhile() condition', condition); + const actionResult = action(); + console.info('[promiseWhile] promiseDoWhile() actionResult', actionResult); + actionResult .then(() => promiseWhile(condition, action)) .then(() => resolve()) .catch(reject); diff --git a/.github/actions/javascript/getArtifactInfo/getArtifactInfo.js b/.github/actions/javascript/getArtifactInfo/getArtifactInfo.ts similarity index 74% rename from .github/actions/javascript/getArtifactInfo/getArtifactInfo.js rename to .github/actions/javascript/getArtifactInfo/getArtifactInfo.ts index c2398a34db4b..9781fa3c51d3 100644 --- a/.github/actions/javascript/getArtifactInfo/getArtifactInfo.js +++ b/.github/actions/javascript/getArtifactInfo/getArtifactInfo.ts @@ -1,13 +1,12 @@ -const _ = require('underscore'); -const core = require('@actions/core'); -const GithubUtils = require('../../../libs/GithubUtils'); +import * as core from '@actions/core'; +import GithubUtils from '@github/libs/GithubUtils'; -const run = function () { +const run = function (): Promise { const artifactName = core.getInput('ARTIFACT_NAME', {required: true}); return GithubUtils.getArtifactByName(artifactName) .then((artifact) => { - if (_.isUndefined(artifact)) { + if (artifact === undefined) { console.log(`No artifact found with the name ${artifactName}`); core.setOutput('ARTIFACT_FOUND', false); return; @@ -16,9 +15,9 @@ const run = function () { console.log('Artifact info', artifact); core.setOutput('ARTIFACT_FOUND', true); core.setOutput('ARTIFACT_ID', artifact.id); - core.setOutput('ARTIFACT_WORKFLOW_ID', artifact.workflow_run.id); + core.setOutput('ARTIFACT_WORKFLOW_ID', artifact.workflow_run?.id); }) - .catch((error) => { + .catch((error: Error) => { console.error('A problem occurred while trying to communicate with the GitHub API', error); core.setFailed(error); }); @@ -28,4 +27,4 @@ if (require.main === module) { run(); } -module.exports = run; +export default run; diff --git a/.github/actions/javascript/getArtifactInfo/index.js b/.github/actions/javascript/getArtifactInfo/index.js index 11adfd8bf842..7dc0300895b0 100644 --- a/.github/actions/javascript/getArtifactInfo/index.js +++ b/.github/actions/javascript/getArtifactInfo/index.js @@ -4,44 +4,6 @@ /******/ (() => { // webpackBootstrap /******/ var __webpack_modules__ = ({ -/***/ 1307: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -const _ = __nccwpck_require__(5067); -const core = __nccwpck_require__(2186); -const GithubUtils = __nccwpck_require__(9296); - -const run = function () { - const artifactName = core.getInput('ARTIFACT_NAME', {required: true}); - - return GithubUtils.getArtifactByName(artifactName) - .then((artifact) => { - if (_.isUndefined(artifact)) { - console.log(`No artifact found with the name ${artifactName}`); - core.setOutput('ARTIFACT_FOUND', false); - return; - } - - console.log('Artifact info', artifact); - core.setOutput('ARTIFACT_FOUND', true); - core.setOutput('ARTIFACT_ID', artifact.id); - core.setOutput('ARTIFACT_WORKFLOW_ID', artifact.workflow_run.id); - }) - .catch((error) => { - console.error('A problem occurred while trying to communicate with the GitHub API', error); - core.setFailed(error); - }); -}; - -if (require.main === require.cache[eval('__filename')]) { - run(); -} - -module.exports = run; - - -/***/ }), - /***/ 4097: /***/ ((module) => { @@ -11481,6 +11443,67 @@ function wrappy (fn, cb) { } +/***/ }), + +/***/ 7750: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + +"use strict"; + +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +const core = __importStar(__nccwpck_require__(2186)); +const GithubUtils_1 = __importDefault(__nccwpck_require__(9296)); +const run = function () { + const artifactName = core.getInput('ARTIFACT_NAME', { required: true }); + return GithubUtils_1.default.getArtifactByName(artifactName) + .then((artifact) => { + if (artifact === undefined) { + console.log(`No artifact found with the name ${artifactName}`); + core.setOutput('ARTIFACT_FOUND', false); + return; + } + console.log('Artifact info', artifact); + core.setOutput('ARTIFACT_FOUND', true); + core.setOutput('ARTIFACT_ID', artifact.id); + core.setOutput('ARTIFACT_WORKFLOW_ID', artifact.workflow_run?.id); + }) + .catch((error) => { + console.error('A problem occurred while trying to communicate with the GitHub API', error); + core.setFailed(error); + }); +}; +if (require.main === require.cache[eval('__filename')]) { + run(); +} +exports["default"] = run; + + /***/ }), /***/ 9296: @@ -12095,2189 +12118,6 @@ module.exports = require("util"); "use strict"; module.exports = require("zlib"); -/***/ }), - -/***/ 6717: -/***/ ((__unused_webpack_module, exports) => { - -// Underscore.js 1.13.6 -// https://underscorejs.org -// (c) 2009-2022 Jeremy Ashkenas, Julian Gonggrijp, and DocumentCloud and Investigative Reporters & Editors -// Underscore may be freely distributed under the MIT license. - -Object.defineProperty(exports, "__esModule", ({ value: true })); - -// Current version. -var VERSION = '1.13.6'; - -// Establish the root object, `window` (`self`) in the browser, `global` -// on the server, or `this` in some virtual machines. We use `self` -// instead of `window` for `WebWorker` support. -var root = (typeof self == 'object' && self.self === self && self) || - (typeof global == 'object' && global.global === global && global) || - Function('return this')() || - {}; - -// Save bytes in the minified (but not gzipped) version: -var ArrayProto = Array.prototype, ObjProto = Object.prototype; -var SymbolProto = typeof Symbol !== 'undefined' ? Symbol.prototype : null; - -// Create quick reference variables for speed access to core prototypes. -var push = ArrayProto.push, - slice = ArrayProto.slice, - toString = ObjProto.toString, - hasOwnProperty = ObjProto.hasOwnProperty; - -// Modern feature detection. -var supportsArrayBuffer = typeof ArrayBuffer !== 'undefined', - supportsDataView = typeof DataView !== 'undefined'; - -// All **ECMAScript 5+** native function implementations that we hope to use -// are declared here. -var nativeIsArray = Array.isArray, - nativeKeys = Object.keys, - nativeCreate = Object.create, - nativeIsView = supportsArrayBuffer && ArrayBuffer.isView; - -// Create references to these builtin functions because we override them. -var _isNaN = isNaN, - _isFinite = isFinite; - -// Keys in IE < 9 that won't be iterated by `for key in ...` and thus missed. -var hasEnumBug = !{toString: null}.propertyIsEnumerable('toString'); -var nonEnumerableProps = ['valueOf', 'isPrototypeOf', 'toString', - 'propertyIsEnumerable', 'hasOwnProperty', 'toLocaleString']; - -// The largest integer that can be represented exactly. -var MAX_ARRAY_INDEX = Math.pow(2, 53) - 1; - -// Some functions take a variable number of arguments, or a few expected -// arguments at the beginning and then a variable number of values to operate -// on. This helper accumulates all remaining arguments past the function’s -// argument length (or an explicit `startIndex`), into an array that becomes -// the last argument. Similar to ES6’s "rest parameter". -function restArguments(func, startIndex) { - startIndex = startIndex == null ? func.length - 1 : +startIndex; - return function() { - var length = Math.max(arguments.length - startIndex, 0), - rest = Array(length), - index = 0; - for (; index < length; index++) { - rest[index] = arguments[index + startIndex]; - } - switch (startIndex) { - case 0: return func.call(this, rest); - case 1: return func.call(this, arguments[0], rest); - case 2: return func.call(this, arguments[0], arguments[1], rest); - } - var args = Array(startIndex + 1); - for (index = 0; index < startIndex; index++) { - args[index] = arguments[index]; - } - args[startIndex] = rest; - return func.apply(this, args); - }; -} - -// Is a given variable an object? -function isObject(obj) { - var type = typeof obj; - return type === 'function' || (type === 'object' && !!obj); -} - -// Is a given value equal to null? -function isNull(obj) { - return obj === null; -} - -// Is a given variable undefined? -function isUndefined(obj) { - return obj === void 0; -} - -// Is a given value a boolean? -function isBoolean(obj) { - return obj === true || obj === false || toString.call(obj) === '[object Boolean]'; -} - -// Is a given value a DOM element? -function isElement(obj) { - return !!(obj && obj.nodeType === 1); -} - -// Internal function for creating a `toString`-based type tester. -function tagTester(name) { - var tag = '[object ' + name + ']'; - return function(obj) { - return toString.call(obj) === tag; - }; -} - -var isString = tagTester('String'); - -var isNumber = tagTester('Number'); - -var isDate = tagTester('Date'); - -var isRegExp = tagTester('RegExp'); - -var isError = tagTester('Error'); - -var isSymbol = tagTester('Symbol'); - -var isArrayBuffer = tagTester('ArrayBuffer'); - -var isFunction = tagTester('Function'); - -// Optimize `isFunction` if appropriate. Work around some `typeof` bugs in old -// v8, IE 11 (#1621), Safari 8 (#1929), and PhantomJS (#2236). -var nodelist = root.document && root.document.childNodes; -if ( true && typeof Int8Array != 'object' && typeof nodelist != 'function') { - isFunction = function(obj) { - return typeof obj == 'function' || false; - }; -} - -var isFunction$1 = isFunction; - -var hasObjectTag = tagTester('Object'); - -// In IE 10 - Edge 13, `DataView` has string tag `'[object Object]'`. -// In IE 11, the most common among them, this problem also applies to -// `Map`, `WeakMap` and `Set`. -var hasStringTagBug = ( - supportsDataView && hasObjectTag(new DataView(new ArrayBuffer(8))) - ), - isIE11 = (typeof Map !== 'undefined' && hasObjectTag(new Map)); - -var isDataView = tagTester('DataView'); - -// In IE 10 - Edge 13, we need a different heuristic -// to determine whether an object is a `DataView`. -function ie10IsDataView(obj) { - return obj != null && isFunction$1(obj.getInt8) && isArrayBuffer(obj.buffer); -} - -var isDataView$1 = (hasStringTagBug ? ie10IsDataView : isDataView); - -// Is a given value an array? -// Delegates to ECMA5's native `Array.isArray`. -var isArray = nativeIsArray || tagTester('Array'); - -// Internal function to check whether `key` is an own property name of `obj`. -function has$1(obj, key) { - return obj != null && hasOwnProperty.call(obj, key); -} - -var isArguments = tagTester('Arguments'); - -// Define a fallback version of the method in browsers (ahem, IE < 9), where -// there isn't any inspectable "Arguments" type. -(function() { - if (!isArguments(arguments)) { - isArguments = function(obj) { - return has$1(obj, 'callee'); - }; - } -}()); - -var isArguments$1 = isArguments; - -// Is a given object a finite number? -function isFinite$1(obj) { - return !isSymbol(obj) && _isFinite(obj) && !isNaN(parseFloat(obj)); -} - -// Is the given value `NaN`? -function isNaN$1(obj) { - return isNumber(obj) && _isNaN(obj); -} - -// Predicate-generating function. Often useful outside of Underscore. -function constant(value) { - return function() { - return value; - }; -} - -// Common internal logic for `isArrayLike` and `isBufferLike`. -function createSizePropertyCheck(getSizeProperty) { - return function(collection) { - var sizeProperty = getSizeProperty(collection); - return typeof sizeProperty == 'number' && sizeProperty >= 0 && sizeProperty <= MAX_ARRAY_INDEX; - } -} - -// Internal helper to generate a function to obtain property `key` from `obj`. -function shallowProperty(key) { - return function(obj) { - return obj == null ? void 0 : obj[key]; - }; -} - -// Internal helper to obtain the `byteLength` property of an object. -var getByteLength = shallowProperty('byteLength'); - -// Internal helper to determine whether we should spend extensive checks against -// `ArrayBuffer` et al. -var isBufferLike = createSizePropertyCheck(getByteLength); - -// Is a given value a typed array? -var typedArrayPattern = /\[object ((I|Ui)nt(8|16|32)|Float(32|64)|Uint8Clamped|Big(I|Ui)nt64)Array\]/; -function isTypedArray(obj) { - // `ArrayBuffer.isView` is the most future-proof, so use it when available. - // Otherwise, fall back on the above regular expression. - return nativeIsView ? (nativeIsView(obj) && !isDataView$1(obj)) : - isBufferLike(obj) && typedArrayPattern.test(toString.call(obj)); -} - -var isTypedArray$1 = supportsArrayBuffer ? isTypedArray : constant(false); - -// Internal helper to obtain the `length` property of an object. -var getLength = shallowProperty('length'); - -// Internal helper to create a simple lookup structure. -// `collectNonEnumProps` used to depend on `_.contains`, but this led to -// circular imports. `emulatedSet` is a one-off solution that only works for -// arrays of strings. -function emulatedSet(keys) { - var hash = {}; - for (var l = keys.length, i = 0; i < l; ++i) hash[keys[i]] = true; - return { - contains: function(key) { return hash[key] === true; }, - push: function(key) { - hash[key] = true; - return keys.push(key); - } - }; -} - -// Internal helper. Checks `keys` for the presence of keys in IE < 9 that won't -// be iterated by `for key in ...` and thus missed. Extends `keys` in place if -// needed. -function collectNonEnumProps(obj, keys) { - keys = emulatedSet(keys); - var nonEnumIdx = nonEnumerableProps.length; - var constructor = obj.constructor; - var proto = (isFunction$1(constructor) && constructor.prototype) || ObjProto; - - // Constructor is a special case. - var prop = 'constructor'; - if (has$1(obj, prop) && !keys.contains(prop)) keys.push(prop); - - while (nonEnumIdx--) { - prop = nonEnumerableProps[nonEnumIdx]; - if (prop in obj && obj[prop] !== proto[prop] && !keys.contains(prop)) { - keys.push(prop); - } - } -} - -// Retrieve the names of an object's own properties. -// Delegates to **ECMAScript 5**'s native `Object.keys`. -function keys(obj) { - if (!isObject(obj)) return []; - if (nativeKeys) return nativeKeys(obj); - var keys = []; - for (var key in obj) if (has$1(obj, key)) keys.push(key); - // Ahem, IE < 9. - if (hasEnumBug) collectNonEnumProps(obj, keys); - return keys; -} - -// Is a given array, string, or object empty? -// An "empty" object has no enumerable own-properties. -function isEmpty(obj) { - if (obj == null) return true; - // Skip the more expensive `toString`-based type checks if `obj` has no - // `.length`. - var length = getLength(obj); - if (typeof length == 'number' && ( - isArray(obj) || isString(obj) || isArguments$1(obj) - )) return length === 0; - return getLength(keys(obj)) === 0; -} - -// Returns whether an object has a given set of `key:value` pairs. -function isMatch(object, attrs) { - var _keys = keys(attrs), length = _keys.length; - if (object == null) return !length; - var obj = Object(object); - for (var i = 0; i < length; i++) { - var key = _keys[i]; - if (attrs[key] !== obj[key] || !(key in obj)) return false; - } - return true; -} - -// If Underscore is called as a function, it returns a wrapped object that can -// be used OO-style. This wrapper holds altered versions of all functions added -// through `_.mixin`. Wrapped objects may be chained. -function _$1(obj) { - if (obj instanceof _$1) return obj; - if (!(this instanceof _$1)) return new _$1(obj); - this._wrapped = obj; -} - -_$1.VERSION = VERSION; - -// Extracts the result from a wrapped and chained object. -_$1.prototype.value = function() { - return this._wrapped; -}; - -// Provide unwrapping proxies for some methods used in engine operations -// such as arithmetic and JSON stringification. -_$1.prototype.valueOf = _$1.prototype.toJSON = _$1.prototype.value; - -_$1.prototype.toString = function() { - return String(this._wrapped); -}; - -// Internal function to wrap or shallow-copy an ArrayBuffer, -// typed array or DataView to a new view, reusing the buffer. -function toBufferView(bufferSource) { - return new Uint8Array( - bufferSource.buffer || bufferSource, - bufferSource.byteOffset || 0, - getByteLength(bufferSource) - ); -} - -// We use this string twice, so give it a name for minification. -var tagDataView = '[object DataView]'; - -// Internal recursive comparison function for `_.isEqual`. -function eq(a, b, aStack, bStack) { - // Identical objects are equal. `0 === -0`, but they aren't identical. - // See the [Harmony `egal` proposal](https://wiki.ecmascript.org/doku.php?id=harmony:egal). - if (a === b) return a !== 0 || 1 / a === 1 / b; - // `null` or `undefined` only equal to itself (strict comparison). - if (a == null || b == null) return false; - // `NaN`s are equivalent, but non-reflexive. - if (a !== a) return b !== b; - // Exhaust primitive checks - var type = typeof a; - if (type !== 'function' && type !== 'object' && typeof b != 'object') return false; - return deepEq(a, b, aStack, bStack); -} - -// Internal recursive comparison function for `_.isEqual`. -function deepEq(a, b, aStack, bStack) { - // Unwrap any wrapped objects. - if (a instanceof _$1) a = a._wrapped; - if (b instanceof _$1) b = b._wrapped; - // Compare `[[Class]]` names. - var className = toString.call(a); - if (className !== toString.call(b)) return false; - // Work around a bug in IE 10 - Edge 13. - if (hasStringTagBug && className == '[object Object]' && isDataView$1(a)) { - if (!isDataView$1(b)) return false; - className = tagDataView; - } - switch (className) { - // These types are compared by value. - case '[object RegExp]': - // RegExps are coerced to strings for comparison (Note: '' + /a/i === '/a/i') - case '[object String]': - // Primitives and their corresponding object wrappers are equivalent; thus, `"5"` is - // equivalent to `new String("5")`. - return '' + a === '' + b; - case '[object Number]': - // `NaN`s are equivalent, but non-reflexive. - // Object(NaN) is equivalent to NaN. - if (+a !== +a) return +b !== +b; - // An `egal` comparison is performed for other numeric values. - return +a === 0 ? 1 / +a === 1 / b : +a === +b; - case '[object Date]': - case '[object Boolean]': - // Coerce dates and booleans to numeric primitive values. Dates are compared by their - // millisecond representations. Note that invalid dates with millisecond representations - // of `NaN` are not equivalent. - return +a === +b; - case '[object Symbol]': - return SymbolProto.valueOf.call(a) === SymbolProto.valueOf.call(b); - case '[object ArrayBuffer]': - case tagDataView: - // Coerce to typed array so we can fall through. - return deepEq(toBufferView(a), toBufferView(b), aStack, bStack); - } - - var areArrays = className === '[object Array]'; - if (!areArrays && isTypedArray$1(a)) { - var byteLength = getByteLength(a); - if (byteLength !== getByteLength(b)) return false; - if (a.buffer === b.buffer && a.byteOffset === b.byteOffset) return true; - areArrays = true; - } - if (!areArrays) { - if (typeof a != 'object' || typeof b != 'object') return false; - - // Objects with different constructors are not equivalent, but `Object`s or `Array`s - // from different frames are. - var aCtor = a.constructor, bCtor = b.constructor; - if (aCtor !== bCtor && !(isFunction$1(aCtor) && aCtor instanceof aCtor && - isFunction$1(bCtor) && bCtor instanceof bCtor) - && ('constructor' in a && 'constructor' in b)) { - return false; - } - } - // Assume equality for cyclic structures. The algorithm for detecting cyclic - // structures is adapted from ES 5.1 section 15.12.3, abstract operation `JO`. - - // Initializing stack of traversed objects. - // It's done here since we only need them for objects and arrays comparison. - aStack = aStack || []; - bStack = bStack || []; - var length = aStack.length; - while (length--) { - // Linear search. Performance is inversely proportional to the number of - // unique nested structures. - if (aStack[length] === a) return bStack[length] === b; - } - - // Add the first object to the stack of traversed objects. - aStack.push(a); - bStack.push(b); - - // Recursively compare objects and arrays. - if (areArrays) { - // Compare array lengths to determine if a deep comparison is necessary. - length = a.length; - if (length !== b.length) return false; - // Deep compare the contents, ignoring non-numeric properties. - while (length--) { - if (!eq(a[length], b[length], aStack, bStack)) return false; - } - } else { - // Deep compare objects. - var _keys = keys(a), key; - length = _keys.length; - // Ensure that both objects contain the same number of properties before comparing deep equality. - if (keys(b).length !== length) return false; - while (length--) { - // Deep compare each member - key = _keys[length]; - if (!(has$1(b, key) && eq(a[key], b[key], aStack, bStack))) return false; - } - } - // Remove the first object from the stack of traversed objects. - aStack.pop(); - bStack.pop(); - return true; -} - -// Perform a deep comparison to check if two objects are equal. -function isEqual(a, b) { - return eq(a, b); -} - -// Retrieve all the enumerable property names of an object. -function allKeys(obj) { - if (!isObject(obj)) return []; - var keys = []; - for (var key in obj) keys.push(key); - // Ahem, IE < 9. - if (hasEnumBug) collectNonEnumProps(obj, keys); - return keys; -} - -// Since the regular `Object.prototype.toString` type tests don't work for -// some types in IE 11, we use a fingerprinting heuristic instead, based -// on the methods. It's not great, but it's the best we got. -// The fingerprint method lists are defined below. -function ie11fingerprint(methods) { - var length = getLength(methods); - return function(obj) { - if (obj == null) return false; - // `Map`, `WeakMap` and `Set` have no enumerable keys. - var keys = allKeys(obj); - if (getLength(keys)) return false; - for (var i = 0; i < length; i++) { - if (!isFunction$1(obj[methods[i]])) return false; - } - // If we are testing against `WeakMap`, we need to ensure that - // `obj` doesn't have a `forEach` method in order to distinguish - // it from a regular `Map`. - return methods !== weakMapMethods || !isFunction$1(obj[forEachName]); - }; -} - -// In the interest of compact minification, we write -// each string in the fingerprints only once. -var forEachName = 'forEach', - hasName = 'has', - commonInit = ['clear', 'delete'], - mapTail = ['get', hasName, 'set']; - -// `Map`, `WeakMap` and `Set` each have slightly different -// combinations of the above sublists. -var mapMethods = commonInit.concat(forEachName, mapTail), - weakMapMethods = commonInit.concat(mapTail), - setMethods = ['add'].concat(commonInit, forEachName, hasName); - -var isMap = isIE11 ? ie11fingerprint(mapMethods) : tagTester('Map'); - -var isWeakMap = isIE11 ? ie11fingerprint(weakMapMethods) : tagTester('WeakMap'); - -var isSet = isIE11 ? ie11fingerprint(setMethods) : tagTester('Set'); - -var isWeakSet = tagTester('WeakSet'); - -// Retrieve the values of an object's properties. -function values(obj) { - var _keys = keys(obj); - var length = _keys.length; - var values = Array(length); - for (var i = 0; i < length; i++) { - values[i] = obj[_keys[i]]; - } - return values; -} - -// Convert an object into a list of `[key, value]` pairs. -// The opposite of `_.object` with one argument. -function pairs(obj) { - var _keys = keys(obj); - var length = _keys.length; - var pairs = Array(length); - for (var i = 0; i < length; i++) { - pairs[i] = [_keys[i], obj[_keys[i]]]; - } - return pairs; -} - -// Invert the keys and values of an object. The values must be serializable. -function invert(obj) { - var result = {}; - var _keys = keys(obj); - for (var i = 0, length = _keys.length; i < length; i++) { - result[obj[_keys[i]]] = _keys[i]; - } - return result; -} - -// Return a sorted list of the function names available on the object. -function functions(obj) { - var names = []; - for (var key in obj) { - if (isFunction$1(obj[key])) names.push(key); - } - return names.sort(); -} - -// An internal function for creating assigner functions. -function createAssigner(keysFunc, defaults) { - return function(obj) { - var length = arguments.length; - if (defaults) obj = Object(obj); - if (length < 2 || obj == null) return obj; - for (var index = 1; index < length; index++) { - var source = arguments[index], - keys = keysFunc(source), - l = keys.length; - for (var i = 0; i < l; i++) { - var key = keys[i]; - if (!defaults || obj[key] === void 0) obj[key] = source[key]; - } - } - return obj; - }; -} - -// Extend a given object with all the properties in passed-in object(s). -var extend = createAssigner(allKeys); - -// Assigns a given object with all the own properties in the passed-in -// object(s). -// (https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object/assign) -var extendOwn = createAssigner(keys); - -// Fill in a given object with default properties. -var defaults = createAssigner(allKeys, true); - -// Create a naked function reference for surrogate-prototype-swapping. -function ctor() { - return function(){}; -} - -// An internal function for creating a new object that inherits from another. -function baseCreate(prototype) { - if (!isObject(prototype)) return {}; - if (nativeCreate) return nativeCreate(prototype); - var Ctor = ctor(); - Ctor.prototype = prototype; - var result = new Ctor; - Ctor.prototype = null; - return result; -} - -// Creates an object that inherits from the given prototype object. -// If additional properties are provided then they will be added to the -// created object. -function create(prototype, props) { - var result = baseCreate(prototype); - if (props) extendOwn(result, props); - return result; -} - -// Create a (shallow-cloned) duplicate of an object. -function clone(obj) { - if (!isObject(obj)) return obj; - return isArray(obj) ? obj.slice() : extend({}, obj); -} - -// Invokes `interceptor` with the `obj` and then returns `obj`. -// The primary purpose of this method is to "tap into" a method chain, in -// order to perform operations on intermediate results within the chain. -function tap(obj, interceptor) { - interceptor(obj); - return obj; -} - -// Normalize a (deep) property `path` to array. -// Like `_.iteratee`, this function can be customized. -function toPath$1(path) { - return isArray(path) ? path : [path]; -} -_$1.toPath = toPath$1; - -// Internal wrapper for `_.toPath` to enable minification. -// Similar to `cb` for `_.iteratee`. -function toPath(path) { - return _$1.toPath(path); -} - -// Internal function to obtain a nested property in `obj` along `path`. -function deepGet(obj, path) { - var length = path.length; - for (var i = 0; i < length; i++) { - if (obj == null) return void 0; - obj = obj[path[i]]; - } - return length ? obj : void 0; -} - -// Get the value of the (deep) property on `path` from `object`. -// If any property in `path` does not exist or if the value is -// `undefined`, return `defaultValue` instead. -// The `path` is normalized through `_.toPath`. -function get(object, path, defaultValue) { - var value = deepGet(object, toPath(path)); - return isUndefined(value) ? defaultValue : value; -} - -// Shortcut function for checking if an object has a given property directly on -// itself (in other words, not on a prototype). Unlike the internal `has` -// function, this public version can also traverse nested properties. -function has(obj, path) { - path = toPath(path); - var length = path.length; - for (var i = 0; i < length; i++) { - var key = path[i]; - if (!has$1(obj, key)) return false; - obj = obj[key]; - } - return !!length; -} - -// Keep the identity function around for default iteratees. -function identity(value) { - return value; -} - -// Returns a predicate for checking whether an object has a given set of -// `key:value` pairs. -function matcher(attrs) { - attrs = extendOwn({}, attrs); - return function(obj) { - return isMatch(obj, attrs); - }; -} - -// Creates a function that, when passed an object, will traverse that object’s -// properties down the given `path`, specified as an array of keys or indices. -function property(path) { - path = toPath(path); - return function(obj) { - return deepGet(obj, path); - }; -} - -// Internal function that returns an efficient (for current engines) version -// of the passed-in callback, to be repeatedly applied in other Underscore -// functions. -function optimizeCb(func, context, argCount) { - if (context === void 0) return func; - switch (argCount == null ? 3 : argCount) { - case 1: return function(value) { - return func.call(context, value); - }; - // The 2-argument case is omitted because we’re not using it. - case 3: return function(value, index, collection) { - return func.call(context, value, index, collection); - }; - case 4: return function(accumulator, value, index, collection) { - return func.call(context, accumulator, value, index, collection); - }; - } - return function() { - return func.apply(context, arguments); - }; -} - -// An internal function to generate callbacks that can be applied to each -// element in a collection, returning the desired result — either `_.identity`, -// an arbitrary callback, a property matcher, or a property accessor. -function baseIteratee(value, context, argCount) { - if (value == null) return identity; - if (isFunction$1(value)) return optimizeCb(value, context, argCount); - if (isObject(value) && !isArray(value)) return matcher(value); - return property(value); -} - -// External wrapper for our callback generator. Users may customize -// `_.iteratee` if they want additional predicate/iteratee shorthand styles. -// This abstraction hides the internal-only `argCount` argument. -function iteratee(value, context) { - return baseIteratee(value, context, Infinity); -} -_$1.iteratee = iteratee; - -// The function we call internally to generate a callback. It invokes -// `_.iteratee` if overridden, otherwise `baseIteratee`. -function cb(value, context, argCount) { - if (_$1.iteratee !== iteratee) return _$1.iteratee(value, context); - return baseIteratee(value, context, argCount); -} - -// Returns the results of applying the `iteratee` to each element of `obj`. -// In contrast to `_.map` it returns an object. -function mapObject(obj, iteratee, context) { - iteratee = cb(iteratee, context); - var _keys = keys(obj), - length = _keys.length, - results = {}; - for (var index = 0; index < length; index++) { - var currentKey = _keys[index]; - results[currentKey] = iteratee(obj[currentKey], currentKey, obj); - } - return results; -} - -// Predicate-generating function. Often useful outside of Underscore. -function noop(){} - -// Generates a function for a given object that returns a given property. -function propertyOf(obj) { - if (obj == null) return noop; - return function(path) { - return get(obj, path); - }; -} - -// Run a function **n** times. -function times(n, iteratee, context) { - var accum = Array(Math.max(0, n)); - iteratee = optimizeCb(iteratee, context, 1); - for (var i = 0; i < n; i++) accum[i] = iteratee(i); - return accum; -} - -// Return a random integer between `min` and `max` (inclusive). -function random(min, max) { - if (max == null) { - max = min; - min = 0; - } - return min + Math.floor(Math.random() * (max - min + 1)); -} - -// A (possibly faster) way to get the current timestamp as an integer. -var now = Date.now || function() { - return new Date().getTime(); -}; - -// Internal helper to generate functions for escaping and unescaping strings -// to/from HTML interpolation. -function createEscaper(map) { - var escaper = function(match) { - return map[match]; - }; - // Regexes for identifying a key that needs to be escaped. - var source = '(?:' + keys(map).join('|') + ')'; - var testRegexp = RegExp(source); - var replaceRegexp = RegExp(source, 'g'); - return function(string) { - string = string == null ? '' : '' + string; - return testRegexp.test(string) ? string.replace(replaceRegexp, escaper) : string; - }; -} - -// Internal list of HTML entities for escaping. -var escapeMap = { - '&': '&', - '<': '<', - '>': '>', - '"': '"', - "'": ''', - '`': '`' -}; - -// Function for escaping strings to HTML interpolation. -var _escape = createEscaper(escapeMap); - -// Internal list of HTML entities for unescaping. -var unescapeMap = invert(escapeMap); - -// Function for unescaping strings from HTML interpolation. -var _unescape = createEscaper(unescapeMap); - -// By default, Underscore uses ERB-style template delimiters. Change the -// following template settings to use alternative delimiters. -var templateSettings = _$1.templateSettings = { - evaluate: /<%([\s\S]+?)%>/g, - interpolate: /<%=([\s\S]+?)%>/g, - escape: /<%-([\s\S]+?)%>/g -}; - -// When customizing `_.templateSettings`, if you don't want to define an -// interpolation, evaluation or escaping regex, we need one that is -// guaranteed not to match. -var noMatch = /(.)^/; - -// Certain characters need to be escaped so that they can be put into a -// string literal. -var escapes = { - "'": "'", - '\\': '\\', - '\r': 'r', - '\n': 'n', - '\u2028': 'u2028', - '\u2029': 'u2029' -}; - -var escapeRegExp = /\\|'|\r|\n|\u2028|\u2029/g; - -function escapeChar(match) { - return '\\' + escapes[match]; -} - -// In order to prevent third-party code injection through -// `_.templateSettings.variable`, we test it against the following regular -// expression. It is intentionally a bit more liberal than just matching valid -// identifiers, but still prevents possible loopholes through defaults or -// destructuring assignment. -var bareIdentifier = /^\s*(\w|\$)+\s*$/; - -// JavaScript micro-templating, similar to John Resig's implementation. -// Underscore templating handles arbitrary delimiters, preserves whitespace, -// and correctly escapes quotes within interpolated code. -// NB: `oldSettings` only exists for backwards compatibility. -function template(text, settings, oldSettings) { - if (!settings && oldSettings) settings = oldSettings; - settings = defaults({}, settings, _$1.templateSettings); - - // Combine delimiters into one regular expression via alternation. - var matcher = RegExp([ - (settings.escape || noMatch).source, - (settings.interpolate || noMatch).source, - (settings.evaluate || noMatch).source - ].join('|') + '|$', 'g'); - - // Compile the template source, escaping string literals appropriately. - var index = 0; - var source = "__p+='"; - text.replace(matcher, function(match, escape, interpolate, evaluate, offset) { - source += text.slice(index, offset).replace(escapeRegExp, escapeChar); - index = offset + match.length; - - if (escape) { - source += "'+\n((__t=(" + escape + "))==null?'':_.escape(__t))+\n'"; - } else if (interpolate) { - source += "'+\n((__t=(" + interpolate + "))==null?'':__t)+\n'"; - } else if (evaluate) { - source += "';\n" + evaluate + "\n__p+='"; - } - - // Adobe VMs need the match returned to produce the correct offset. - return match; - }); - source += "';\n"; - - var argument = settings.variable; - if (argument) { - // Insure against third-party code injection. (CVE-2021-23358) - if (!bareIdentifier.test(argument)) throw new Error( - 'variable is not a bare identifier: ' + argument - ); - } else { - // If a variable is not specified, place data values in local scope. - source = 'with(obj||{}){\n' + source + '}\n'; - argument = 'obj'; - } - - source = "var __t,__p='',__j=Array.prototype.join," + - "print=function(){__p+=__j.call(arguments,'');};\n" + - source + 'return __p;\n'; - - var render; - try { - render = new Function(argument, '_', source); - } catch (e) { - e.source = source; - throw e; - } - - var template = function(data) { - return render.call(this, data, _$1); - }; - - // Provide the compiled source as a convenience for precompilation. - template.source = 'function(' + argument + '){\n' + source + '}'; - - return template; -} - -// Traverses the children of `obj` along `path`. If a child is a function, it -// is invoked with its parent as context. Returns the value of the final -// child, or `fallback` if any child is undefined. -function result(obj, path, fallback) { - path = toPath(path); - var length = path.length; - if (!length) { - return isFunction$1(fallback) ? fallback.call(obj) : fallback; - } - for (var i = 0; i < length; i++) { - var prop = obj == null ? void 0 : obj[path[i]]; - if (prop === void 0) { - prop = fallback; - i = length; // Ensure we don't continue iterating. - } - obj = isFunction$1(prop) ? prop.call(obj) : prop; - } - return obj; -} - -// Generate a unique integer id (unique within the entire client session). -// Useful for temporary DOM ids. -var idCounter = 0; -function uniqueId(prefix) { - var id = ++idCounter + ''; - return prefix ? prefix + id : id; -} - -// Start chaining a wrapped Underscore object. -function chain(obj) { - var instance = _$1(obj); - instance._chain = true; - return instance; -} - -// Internal function to execute `sourceFunc` bound to `context` with optional -// `args`. Determines whether to execute a function as a constructor or as a -// normal function. -function executeBound(sourceFunc, boundFunc, context, callingContext, args) { - if (!(callingContext instanceof boundFunc)) return sourceFunc.apply(context, args); - var self = baseCreate(sourceFunc.prototype); - var result = sourceFunc.apply(self, args); - if (isObject(result)) return result; - return self; -} - -// Partially apply a function by creating a version that has had some of its -// arguments pre-filled, without changing its dynamic `this` context. `_` acts -// as a placeholder by default, allowing any combination of arguments to be -// pre-filled. Set `_.partial.placeholder` for a custom placeholder argument. -var partial = restArguments(function(func, boundArgs) { - var placeholder = partial.placeholder; - var bound = function() { - var position = 0, length = boundArgs.length; - var args = Array(length); - for (var i = 0; i < length; i++) { - args[i] = boundArgs[i] === placeholder ? arguments[position++] : boundArgs[i]; - } - while (position < arguments.length) args.push(arguments[position++]); - return executeBound(func, bound, this, this, args); - }; - return bound; -}); - -partial.placeholder = _$1; - -// Create a function bound to a given object (assigning `this`, and arguments, -// optionally). -var bind = restArguments(function(func, context, args) { - if (!isFunction$1(func)) throw new TypeError('Bind must be called on a function'); - var bound = restArguments(function(callArgs) { - return executeBound(func, bound, context, this, args.concat(callArgs)); - }); - return bound; -}); - -// Internal helper for collection methods to determine whether a collection -// should be iterated as an array or as an object. -// Related: https://people.mozilla.org/~jorendorff/es6-draft.html#sec-tolength -// Avoids a very nasty iOS 8 JIT bug on ARM-64. #2094 -var isArrayLike = createSizePropertyCheck(getLength); - -// Internal implementation of a recursive `flatten` function. -function flatten$1(input, depth, strict, output) { - output = output || []; - if (!depth && depth !== 0) { - depth = Infinity; - } else if (depth <= 0) { - return output.concat(input); - } - var idx = output.length; - for (var i = 0, length = getLength(input); i < length; i++) { - var value = input[i]; - if (isArrayLike(value) && (isArray(value) || isArguments$1(value))) { - // Flatten current level of array or arguments object. - if (depth > 1) { - flatten$1(value, depth - 1, strict, output); - idx = output.length; - } else { - var j = 0, len = value.length; - while (j < len) output[idx++] = value[j++]; - } - } else if (!strict) { - output[idx++] = value; - } - } - return output; -} - -// Bind a number of an object's methods to that object. Remaining arguments -// are the method names to be bound. Useful for ensuring that all callbacks -// defined on an object belong to it. -var bindAll = restArguments(function(obj, keys) { - keys = flatten$1(keys, false, false); - var index = keys.length; - if (index < 1) throw new Error('bindAll must be passed function names'); - while (index--) { - var key = keys[index]; - obj[key] = bind(obj[key], obj); - } - return obj; -}); - -// Memoize an expensive function by storing its results. -function memoize(func, hasher) { - var memoize = function(key) { - var cache = memoize.cache; - var address = '' + (hasher ? hasher.apply(this, arguments) : key); - if (!has$1(cache, address)) cache[address] = func.apply(this, arguments); - return cache[address]; - }; - memoize.cache = {}; - return memoize; -} - -// Delays a function for the given number of milliseconds, and then calls -// it with the arguments supplied. -var delay = restArguments(function(func, wait, args) { - return setTimeout(function() { - return func.apply(null, args); - }, wait); -}); - -// Defers a function, scheduling it to run after the current call stack has -// cleared. -var defer = partial(delay, _$1, 1); - -// Returns a function, that, when invoked, will only be triggered at most once -// during a given window of time. Normally, the throttled function will run -// as much as it can, without ever going more than once per `wait` duration; -// but if you'd like to disable the execution on the leading edge, pass -// `{leading: false}`. To disable execution on the trailing edge, ditto. -function throttle(func, wait, options) { - var timeout, context, args, result; - var previous = 0; - if (!options) options = {}; - - var later = function() { - previous = options.leading === false ? 0 : now(); - timeout = null; - result = func.apply(context, args); - if (!timeout) context = args = null; - }; - - var throttled = function() { - var _now = now(); - if (!previous && options.leading === false) previous = _now; - var remaining = wait - (_now - previous); - context = this; - args = arguments; - if (remaining <= 0 || remaining > wait) { - if (timeout) { - clearTimeout(timeout); - timeout = null; - } - previous = _now; - result = func.apply(context, args); - if (!timeout) context = args = null; - } else if (!timeout && options.trailing !== false) { - timeout = setTimeout(later, remaining); - } - return result; - }; - - throttled.cancel = function() { - clearTimeout(timeout); - previous = 0; - timeout = context = args = null; - }; - - return throttled; -} - -// When a sequence of calls of the returned function ends, the argument -// function is triggered. The end of a sequence is defined by the `wait` -// parameter. If `immediate` is passed, the argument function will be -// triggered at the beginning of the sequence instead of at the end. -function debounce(func, wait, immediate) { - var timeout, previous, args, result, context; - - var later = function() { - var passed = now() - previous; - if (wait > passed) { - timeout = setTimeout(later, wait - passed); - } else { - timeout = null; - if (!immediate) result = func.apply(context, args); - // This check is needed because `func` can recursively invoke `debounced`. - if (!timeout) args = context = null; - } - }; - - var debounced = restArguments(function(_args) { - context = this; - args = _args; - previous = now(); - if (!timeout) { - timeout = setTimeout(later, wait); - if (immediate) result = func.apply(context, args); - } - return result; - }); - - debounced.cancel = function() { - clearTimeout(timeout); - timeout = args = context = null; - }; - - return debounced; -} - -// Returns the first function passed as an argument to the second, -// allowing you to adjust arguments, run code before and after, and -// conditionally execute the original function. -function wrap(func, wrapper) { - return partial(wrapper, func); -} - -// Returns a negated version of the passed-in predicate. -function negate(predicate) { - return function() { - return !predicate.apply(this, arguments); - }; -} - -// Returns a function that is the composition of a list of functions, each -// consuming the return value of the function that follows. -function compose() { - var args = arguments; - var start = args.length - 1; - return function() { - var i = start; - var result = args[start].apply(this, arguments); - while (i--) result = args[i].call(this, result); - return result; - }; -} - -// Returns a function that will only be executed on and after the Nth call. -function after(times, func) { - return function() { - if (--times < 1) { - return func.apply(this, arguments); - } - }; -} - -// Returns a function that will only be executed up to (but not including) the -// Nth call. -function before(times, func) { - var memo; - return function() { - if (--times > 0) { - memo = func.apply(this, arguments); - } - if (times <= 1) func = null; - return memo; - }; -} - -// Returns a function that will be executed at most one time, no matter how -// often you call it. Useful for lazy initialization. -var once = partial(before, 2); - -// Returns the first key on an object that passes a truth test. -function findKey(obj, predicate, context) { - predicate = cb(predicate, context); - var _keys = keys(obj), key; - for (var i = 0, length = _keys.length; i < length; i++) { - key = _keys[i]; - if (predicate(obj[key], key, obj)) return key; - } -} - -// Internal function to generate `_.findIndex` and `_.findLastIndex`. -function createPredicateIndexFinder(dir) { - return function(array, predicate, context) { - predicate = cb(predicate, context); - var length = getLength(array); - var index = dir > 0 ? 0 : length - 1; - for (; index >= 0 && index < length; index += dir) { - if (predicate(array[index], index, array)) return index; - } - return -1; - }; -} - -// Returns the first index on an array-like that passes a truth test. -var findIndex = createPredicateIndexFinder(1); - -// Returns the last index on an array-like that passes a truth test. -var findLastIndex = createPredicateIndexFinder(-1); - -// Use a comparator function to figure out the smallest index at which -// an object should be inserted so as to maintain order. Uses binary search. -function sortedIndex(array, obj, iteratee, context) { - iteratee = cb(iteratee, context, 1); - var value = iteratee(obj); - var low = 0, high = getLength(array); - while (low < high) { - var mid = Math.floor((low + high) / 2); - if (iteratee(array[mid]) < value) low = mid + 1; else high = mid; - } - return low; -} - -// Internal function to generate the `_.indexOf` and `_.lastIndexOf` functions. -function createIndexFinder(dir, predicateFind, sortedIndex) { - return function(array, item, idx) { - var i = 0, length = getLength(array); - if (typeof idx == 'number') { - if (dir > 0) { - i = idx >= 0 ? idx : Math.max(idx + length, i); - } else { - length = idx >= 0 ? Math.min(idx + 1, length) : idx + length + 1; - } - } else if (sortedIndex && idx && length) { - idx = sortedIndex(array, item); - return array[idx] === item ? idx : -1; - } - if (item !== item) { - idx = predicateFind(slice.call(array, i, length), isNaN$1); - return idx >= 0 ? idx + i : -1; - } - for (idx = dir > 0 ? i : length - 1; idx >= 0 && idx < length; idx += dir) { - if (array[idx] === item) return idx; - } - return -1; - }; -} - -// Return the position of the first occurrence of an item in an array, -// or -1 if the item is not included in the array. -// If the array is large and already in sort order, pass `true` -// for **isSorted** to use binary search. -var indexOf = createIndexFinder(1, findIndex, sortedIndex); - -// Return the position of the last occurrence of an item in an array, -// or -1 if the item is not included in the array. -var lastIndexOf = createIndexFinder(-1, findLastIndex); - -// Return the first value which passes a truth test. -function find(obj, predicate, context) { - var keyFinder = isArrayLike(obj) ? findIndex : findKey; - var key = keyFinder(obj, predicate, context); - if (key !== void 0 && key !== -1) return obj[key]; -} - -// Convenience version of a common use case of `_.find`: getting the first -// object containing specific `key:value` pairs. -function findWhere(obj, attrs) { - return find(obj, matcher(attrs)); -} - -// The cornerstone for collection functions, an `each` -// implementation, aka `forEach`. -// Handles raw objects in addition to array-likes. Treats all -// sparse array-likes as if they were dense. -function each(obj, iteratee, context) { - iteratee = optimizeCb(iteratee, context); - var i, length; - if (isArrayLike(obj)) { - for (i = 0, length = obj.length; i < length; i++) { - iteratee(obj[i], i, obj); - } - } else { - var _keys = keys(obj); - for (i = 0, length = _keys.length; i < length; i++) { - iteratee(obj[_keys[i]], _keys[i], obj); - } - } - return obj; -} - -// Return the results of applying the iteratee to each element. -function map(obj, iteratee, context) { - iteratee = cb(iteratee, context); - var _keys = !isArrayLike(obj) && keys(obj), - length = (_keys || obj).length, - results = Array(length); - for (var index = 0; index < length; index++) { - var currentKey = _keys ? _keys[index] : index; - results[index] = iteratee(obj[currentKey], currentKey, obj); - } - return results; -} - -// Internal helper to create a reducing function, iterating left or right. -function createReduce(dir) { - // Wrap code that reassigns argument variables in a separate function than - // the one that accesses `arguments.length` to avoid a perf hit. (#1991) - var reducer = function(obj, iteratee, memo, initial) { - var _keys = !isArrayLike(obj) && keys(obj), - length = (_keys || obj).length, - index = dir > 0 ? 0 : length - 1; - if (!initial) { - memo = obj[_keys ? _keys[index] : index]; - index += dir; - } - for (; index >= 0 && index < length; index += dir) { - var currentKey = _keys ? _keys[index] : index; - memo = iteratee(memo, obj[currentKey], currentKey, obj); - } - return memo; - }; - - return function(obj, iteratee, memo, context) { - var initial = arguments.length >= 3; - return reducer(obj, optimizeCb(iteratee, context, 4), memo, initial); - }; -} - -// **Reduce** builds up a single result from a list of values, aka `inject`, -// or `foldl`. -var reduce = createReduce(1); - -// The right-associative version of reduce, also known as `foldr`. -var reduceRight = createReduce(-1); - -// Return all the elements that pass a truth test. -function filter(obj, predicate, context) { - var results = []; - predicate = cb(predicate, context); - each(obj, function(value, index, list) { - if (predicate(value, index, list)) results.push(value); - }); - return results; -} - -// Return all the elements for which a truth test fails. -function reject(obj, predicate, context) { - return filter(obj, negate(cb(predicate)), context); -} - -// Determine whether all of the elements pass a truth test. -function every(obj, predicate, context) { - predicate = cb(predicate, context); - var _keys = !isArrayLike(obj) && keys(obj), - length = (_keys || obj).length; - for (var index = 0; index < length; index++) { - var currentKey = _keys ? _keys[index] : index; - if (!predicate(obj[currentKey], currentKey, obj)) return false; - } - return true; -} - -// Determine if at least one element in the object passes a truth test. -function some(obj, predicate, context) { - predicate = cb(predicate, context); - var _keys = !isArrayLike(obj) && keys(obj), - length = (_keys || obj).length; - for (var index = 0; index < length; index++) { - var currentKey = _keys ? _keys[index] : index; - if (predicate(obj[currentKey], currentKey, obj)) return true; - } - return false; -} - -// Determine if the array or object contains a given item (using `===`). -function contains(obj, item, fromIndex, guard) { - if (!isArrayLike(obj)) obj = values(obj); - if (typeof fromIndex != 'number' || guard) fromIndex = 0; - return indexOf(obj, item, fromIndex) >= 0; -} - -// Invoke a method (with arguments) on every item in a collection. -var invoke = restArguments(function(obj, path, args) { - var contextPath, func; - if (isFunction$1(path)) { - func = path; - } else { - path = toPath(path); - contextPath = path.slice(0, -1); - path = path[path.length - 1]; - } - return map(obj, function(context) { - var method = func; - if (!method) { - if (contextPath && contextPath.length) { - context = deepGet(context, contextPath); - } - if (context == null) return void 0; - method = context[path]; - } - return method == null ? method : method.apply(context, args); - }); -}); - -// Convenience version of a common use case of `_.map`: fetching a property. -function pluck(obj, key) { - return map(obj, property(key)); -} - -// Convenience version of a common use case of `_.filter`: selecting only -// objects containing specific `key:value` pairs. -function where(obj, attrs) { - return filter(obj, matcher(attrs)); -} - -// Return the maximum element (or element-based computation). -function max(obj, iteratee, context) { - var result = -Infinity, lastComputed = -Infinity, - value, computed; - if (iteratee == null || (typeof iteratee == 'number' && typeof obj[0] != 'object' && obj != null)) { - obj = isArrayLike(obj) ? obj : values(obj); - for (var i = 0, length = obj.length; i < length; i++) { - value = obj[i]; - if (value != null && value > result) { - result = value; - } - } - } else { - iteratee = cb(iteratee, context); - each(obj, function(v, index, list) { - computed = iteratee(v, index, list); - if (computed > lastComputed || (computed === -Infinity && result === -Infinity)) { - result = v; - lastComputed = computed; - } - }); - } - return result; -} - -// Return the minimum element (or element-based computation). -function min(obj, iteratee, context) { - var result = Infinity, lastComputed = Infinity, - value, computed; - if (iteratee == null || (typeof iteratee == 'number' && typeof obj[0] != 'object' && obj != null)) { - obj = isArrayLike(obj) ? obj : values(obj); - for (var i = 0, length = obj.length; i < length; i++) { - value = obj[i]; - if (value != null && value < result) { - result = value; - } - } - } else { - iteratee = cb(iteratee, context); - each(obj, function(v, index, list) { - computed = iteratee(v, index, list); - if (computed < lastComputed || (computed === Infinity && result === Infinity)) { - result = v; - lastComputed = computed; - } - }); - } - return result; -} - -// Safely create a real, live array from anything iterable. -var reStrSymbol = /[^\ud800-\udfff]|[\ud800-\udbff][\udc00-\udfff]|[\ud800-\udfff]/g; -function toArray(obj) { - if (!obj) return []; - if (isArray(obj)) return slice.call(obj); - if (isString(obj)) { - // Keep surrogate pair characters together. - return obj.match(reStrSymbol); - } - if (isArrayLike(obj)) return map(obj, identity); - return values(obj); -} - -// Sample **n** random values from a collection using the modern version of the -// [Fisher-Yates shuffle](https://en.wikipedia.org/wiki/Fisher–Yates_shuffle). -// If **n** is not specified, returns a single random element. -// The internal `guard` argument allows it to work with `_.map`. -function sample(obj, n, guard) { - if (n == null || guard) { - if (!isArrayLike(obj)) obj = values(obj); - return obj[random(obj.length - 1)]; - } - var sample = toArray(obj); - var length = getLength(sample); - n = Math.max(Math.min(n, length), 0); - var last = length - 1; - for (var index = 0; index < n; index++) { - var rand = random(index, last); - var temp = sample[index]; - sample[index] = sample[rand]; - sample[rand] = temp; - } - return sample.slice(0, n); -} - -// Shuffle a collection. -function shuffle(obj) { - return sample(obj, Infinity); -} - -// Sort the object's values by a criterion produced by an iteratee. -function sortBy(obj, iteratee, context) { - var index = 0; - iteratee = cb(iteratee, context); - return pluck(map(obj, function(value, key, list) { - return { - value: value, - index: index++, - criteria: iteratee(value, key, list) - }; - }).sort(function(left, right) { - var a = left.criteria; - var b = right.criteria; - if (a !== b) { - if (a > b || a === void 0) return 1; - if (a < b || b === void 0) return -1; - } - return left.index - right.index; - }), 'value'); -} - -// An internal function used for aggregate "group by" operations. -function group(behavior, partition) { - return function(obj, iteratee, context) { - var result = partition ? [[], []] : {}; - iteratee = cb(iteratee, context); - each(obj, function(value, index) { - var key = iteratee(value, index, obj); - behavior(result, value, key); - }); - return result; - }; -} - -// Groups the object's values by a criterion. Pass either a string attribute -// to group by, or a function that returns the criterion. -var groupBy = group(function(result, value, key) { - if (has$1(result, key)) result[key].push(value); else result[key] = [value]; -}); - -// Indexes the object's values by a criterion, similar to `_.groupBy`, but for -// when you know that your index values will be unique. -var indexBy = group(function(result, value, key) { - result[key] = value; -}); - -// Counts instances of an object that group by a certain criterion. Pass -// either a string attribute to count by, or a function that returns the -// criterion. -var countBy = group(function(result, value, key) { - if (has$1(result, key)) result[key]++; else result[key] = 1; -}); - -// Split a collection into two arrays: one whose elements all pass the given -// truth test, and one whose elements all do not pass the truth test. -var partition = group(function(result, value, pass) { - result[pass ? 0 : 1].push(value); -}, true); - -// Return the number of elements in a collection. -function size(obj) { - if (obj == null) return 0; - return isArrayLike(obj) ? obj.length : keys(obj).length; -} - -// Internal `_.pick` helper function to determine whether `key` is an enumerable -// property name of `obj`. -function keyInObj(value, key, obj) { - return key in obj; -} - -// Return a copy of the object only containing the allowed properties. -var pick = restArguments(function(obj, keys) { - var result = {}, iteratee = keys[0]; - if (obj == null) return result; - if (isFunction$1(iteratee)) { - if (keys.length > 1) iteratee = optimizeCb(iteratee, keys[1]); - keys = allKeys(obj); - } else { - iteratee = keyInObj; - keys = flatten$1(keys, false, false); - obj = Object(obj); - } - for (var i = 0, length = keys.length; i < length; i++) { - var key = keys[i]; - var value = obj[key]; - if (iteratee(value, key, obj)) result[key] = value; - } - return result; -}); - -// Return a copy of the object without the disallowed properties. -var omit = restArguments(function(obj, keys) { - var iteratee = keys[0], context; - if (isFunction$1(iteratee)) { - iteratee = negate(iteratee); - if (keys.length > 1) context = keys[1]; - } else { - keys = map(flatten$1(keys, false, false), String); - iteratee = function(value, key) { - return !contains(keys, key); - }; - } - return pick(obj, iteratee, context); -}); - -// Returns everything but the last entry of the array. Especially useful on -// the arguments object. Passing **n** will return all the values in -// the array, excluding the last N. -function initial(array, n, guard) { - return slice.call(array, 0, Math.max(0, array.length - (n == null || guard ? 1 : n))); -} - -// Get the first element of an array. Passing **n** will return the first N -// values in the array. The **guard** check allows it to work with `_.map`. -function first(array, n, guard) { - if (array == null || array.length < 1) return n == null || guard ? void 0 : []; - if (n == null || guard) return array[0]; - return initial(array, array.length - n); -} - -// Returns everything but the first entry of the `array`. Especially useful on -// the `arguments` object. Passing an **n** will return the rest N values in the -// `array`. -function rest(array, n, guard) { - return slice.call(array, n == null || guard ? 1 : n); -} - -// Get the last element of an array. Passing **n** will return the last N -// values in the array. -function last(array, n, guard) { - if (array == null || array.length < 1) return n == null || guard ? void 0 : []; - if (n == null || guard) return array[array.length - 1]; - return rest(array, Math.max(0, array.length - n)); -} - -// Trim out all falsy values from an array. -function compact(array) { - return filter(array, Boolean); -} - -// Flatten out an array, either recursively (by default), or up to `depth`. -// Passing `true` or `false` as `depth` means `1` or `Infinity`, respectively. -function flatten(array, depth) { - return flatten$1(array, depth, false); -} - -// Take the difference between one array and a number of other arrays. -// Only the elements present in just the first array will remain. -var difference = restArguments(function(array, rest) { - rest = flatten$1(rest, true, true); - return filter(array, function(value){ - return !contains(rest, value); - }); -}); - -// Return a version of the array that does not contain the specified value(s). -var without = restArguments(function(array, otherArrays) { - return difference(array, otherArrays); -}); - -// Produce a duplicate-free version of the array. If the array has already -// been sorted, you have the option of using a faster algorithm. -// The faster algorithm will not work with an iteratee if the iteratee -// is not a one-to-one function, so providing an iteratee will disable -// the faster algorithm. -function uniq(array, isSorted, iteratee, context) { - if (!isBoolean(isSorted)) { - context = iteratee; - iteratee = isSorted; - isSorted = false; - } - if (iteratee != null) iteratee = cb(iteratee, context); - var result = []; - var seen = []; - for (var i = 0, length = getLength(array); i < length; i++) { - var value = array[i], - computed = iteratee ? iteratee(value, i, array) : value; - if (isSorted && !iteratee) { - if (!i || seen !== computed) result.push(value); - seen = computed; - } else if (iteratee) { - if (!contains(seen, computed)) { - seen.push(computed); - result.push(value); - } - } else if (!contains(result, value)) { - result.push(value); - } - } - return result; -} - -// Produce an array that contains the union: each distinct element from all of -// the passed-in arrays. -var union = restArguments(function(arrays) { - return uniq(flatten$1(arrays, true, true)); -}); - -// Produce an array that contains every item shared between all the -// passed-in arrays. -function intersection(array) { - var result = []; - var argsLength = arguments.length; - for (var i = 0, length = getLength(array); i < length; i++) { - var item = array[i]; - if (contains(result, item)) continue; - var j; - for (j = 1; j < argsLength; j++) { - if (!contains(arguments[j], item)) break; - } - if (j === argsLength) result.push(item); - } - return result; -} - -// Complement of zip. Unzip accepts an array of arrays and groups -// each array's elements on shared indices. -function unzip(array) { - var length = (array && max(array, getLength).length) || 0; - var result = Array(length); - - for (var index = 0; index < length; index++) { - result[index] = pluck(array, index); - } - return result; -} - -// Zip together multiple lists into a single array -- elements that share -// an index go together. -var zip = restArguments(unzip); - -// Converts lists into objects. Pass either a single array of `[key, value]` -// pairs, or two parallel arrays of the same length -- one of keys, and one of -// the corresponding values. Passing by pairs is the reverse of `_.pairs`. -function object(list, values) { - var result = {}; - for (var i = 0, length = getLength(list); i < length; i++) { - if (values) { - result[list[i]] = values[i]; - } else { - result[list[i][0]] = list[i][1]; - } - } - return result; -} - -// Generate an integer Array containing an arithmetic progression. A port of -// the native Python `range()` function. See -// [the Python documentation](https://docs.python.org/library/functions.html#range). -function range(start, stop, step) { - if (stop == null) { - stop = start || 0; - start = 0; - } - if (!step) { - step = stop < start ? -1 : 1; - } - - var length = Math.max(Math.ceil((stop - start) / step), 0); - var range = Array(length); - - for (var idx = 0; idx < length; idx++, start += step) { - range[idx] = start; - } - - return range; -} - -// Chunk a single array into multiple arrays, each containing `count` or fewer -// items. -function chunk(array, count) { - if (count == null || count < 1) return []; - var result = []; - var i = 0, length = array.length; - while (i < length) { - result.push(slice.call(array, i, i += count)); - } - return result; -} - -// Helper function to continue chaining intermediate results. -function chainResult(instance, obj) { - return instance._chain ? _$1(obj).chain() : obj; -} - -// Add your own custom functions to the Underscore object. -function mixin(obj) { - each(functions(obj), function(name) { - var func = _$1[name] = obj[name]; - _$1.prototype[name] = function() { - var args = [this._wrapped]; - push.apply(args, arguments); - return chainResult(this, func.apply(_$1, args)); - }; - }); - return _$1; -} - -// Add all mutator `Array` functions to the wrapper. -each(['pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift'], function(name) { - var method = ArrayProto[name]; - _$1.prototype[name] = function() { - var obj = this._wrapped; - if (obj != null) { - method.apply(obj, arguments); - if ((name === 'shift' || name === 'splice') && obj.length === 0) { - delete obj[0]; - } - } - return chainResult(this, obj); - }; -}); - -// Add all accessor `Array` functions to the wrapper. -each(['concat', 'join', 'slice'], function(name) { - var method = ArrayProto[name]; - _$1.prototype[name] = function() { - var obj = this._wrapped; - if (obj != null) obj = method.apply(obj, arguments); - return chainResult(this, obj); - }; -}); - -// Named Exports - -var allExports = { - __proto__: null, - VERSION: VERSION, - restArguments: restArguments, - isObject: isObject, - isNull: isNull, - isUndefined: isUndefined, - isBoolean: isBoolean, - isElement: isElement, - isString: isString, - isNumber: isNumber, - isDate: isDate, - isRegExp: isRegExp, - isError: isError, - isSymbol: isSymbol, - isArrayBuffer: isArrayBuffer, - isDataView: isDataView$1, - isArray: isArray, - isFunction: isFunction$1, - isArguments: isArguments$1, - isFinite: isFinite$1, - isNaN: isNaN$1, - isTypedArray: isTypedArray$1, - isEmpty: isEmpty, - isMatch: isMatch, - isEqual: isEqual, - isMap: isMap, - isWeakMap: isWeakMap, - isSet: isSet, - isWeakSet: isWeakSet, - keys: keys, - allKeys: allKeys, - values: values, - pairs: pairs, - invert: invert, - functions: functions, - methods: functions, - extend: extend, - extendOwn: extendOwn, - assign: extendOwn, - defaults: defaults, - create: create, - clone: clone, - tap: tap, - get: get, - has: has, - mapObject: mapObject, - identity: identity, - constant: constant, - noop: noop, - toPath: toPath$1, - property: property, - propertyOf: propertyOf, - matcher: matcher, - matches: matcher, - times: times, - random: random, - now: now, - escape: _escape, - unescape: _unescape, - templateSettings: templateSettings, - template: template, - result: result, - uniqueId: uniqueId, - chain: chain, - iteratee: iteratee, - partial: partial, - bind: bind, - bindAll: bindAll, - memoize: memoize, - delay: delay, - defer: defer, - throttle: throttle, - debounce: debounce, - wrap: wrap, - negate: negate, - compose: compose, - after: after, - before: before, - once: once, - findKey: findKey, - findIndex: findIndex, - findLastIndex: findLastIndex, - sortedIndex: sortedIndex, - indexOf: indexOf, - lastIndexOf: lastIndexOf, - find: find, - detect: find, - findWhere: findWhere, - each: each, - forEach: each, - map: map, - collect: map, - reduce: reduce, - foldl: reduce, - inject: reduce, - reduceRight: reduceRight, - foldr: reduceRight, - filter: filter, - select: filter, - reject: reject, - every: every, - all: every, - some: some, - any: some, - contains: contains, - includes: contains, - include: contains, - invoke: invoke, - pluck: pluck, - where: where, - max: max, - min: min, - shuffle: shuffle, - sample: sample, - sortBy: sortBy, - groupBy: groupBy, - indexBy: indexBy, - countBy: countBy, - partition: partition, - toArray: toArray, - size: size, - pick: pick, - omit: omit, - first: first, - head: first, - take: first, - initial: initial, - last: last, - rest: rest, - tail: rest, - drop: rest, - compact: compact, - flatten: flatten, - without: without, - uniq: uniq, - unique: uniq, - union: union, - intersection: intersection, - difference: difference, - unzip: unzip, - transpose: unzip, - zip: zip, - object: object, - range: range, - chunk: chunk, - mixin: mixin, - 'default': _$1 -}; - -// Default Export - -// Add all of the Underscore functions to the wrapper object. -var _ = mixin(allExports); -// Legacy Node.js API. -_._ = _; - -exports.VERSION = VERSION; -exports._ = _; -exports._escape = _escape; -exports._unescape = _unescape; -exports.after = after; -exports.allKeys = allKeys; -exports.before = before; -exports.bind = bind; -exports.bindAll = bindAll; -exports.chain = chain; -exports.chunk = chunk; -exports.clone = clone; -exports.compact = compact; -exports.compose = compose; -exports.constant = constant; -exports.contains = contains; -exports.countBy = countBy; -exports.create = create; -exports.debounce = debounce; -exports.defaults = defaults; -exports.defer = defer; -exports.delay = delay; -exports.difference = difference; -exports.each = each; -exports.every = every; -exports.extend = extend; -exports.extendOwn = extendOwn; -exports.filter = filter; -exports.find = find; -exports.findIndex = findIndex; -exports.findKey = findKey; -exports.findLastIndex = findLastIndex; -exports.findWhere = findWhere; -exports.first = first; -exports.flatten = flatten; -exports.functions = functions; -exports.get = get; -exports.groupBy = groupBy; -exports.has = has; -exports.identity = identity; -exports.indexBy = indexBy; -exports.indexOf = indexOf; -exports.initial = initial; -exports.intersection = intersection; -exports.invert = invert; -exports.invoke = invoke; -exports.isArguments = isArguments$1; -exports.isArray = isArray; -exports.isArrayBuffer = isArrayBuffer; -exports.isBoolean = isBoolean; -exports.isDataView = isDataView$1; -exports.isDate = isDate; -exports.isElement = isElement; -exports.isEmpty = isEmpty; -exports.isEqual = isEqual; -exports.isError = isError; -exports.isFinite = isFinite$1; -exports.isFunction = isFunction$1; -exports.isMap = isMap; -exports.isMatch = isMatch; -exports.isNaN = isNaN$1; -exports.isNull = isNull; -exports.isNumber = isNumber; -exports.isObject = isObject; -exports.isRegExp = isRegExp; -exports.isSet = isSet; -exports.isString = isString; -exports.isSymbol = isSymbol; -exports.isTypedArray = isTypedArray$1; -exports.isUndefined = isUndefined; -exports.isWeakMap = isWeakMap; -exports.isWeakSet = isWeakSet; -exports.iteratee = iteratee; -exports.keys = keys; -exports.last = last; -exports.lastIndexOf = lastIndexOf; -exports.map = map; -exports.mapObject = mapObject; -exports.matcher = matcher; -exports.max = max; -exports.memoize = memoize; -exports.min = min; -exports.mixin = mixin; -exports.negate = negate; -exports.noop = noop; -exports.now = now; -exports.object = object; -exports.omit = omit; -exports.once = once; -exports.pairs = pairs; -exports.partial = partial; -exports.partition = partition; -exports.pick = pick; -exports.pluck = pluck; -exports.property = property; -exports.propertyOf = propertyOf; -exports.random = random; -exports.range = range; -exports.reduce = reduce; -exports.reduceRight = reduceRight; -exports.reject = reject; -exports.rest = rest; -exports.restArguments = restArguments; -exports.result = result; -exports.sample = sample; -exports.shuffle = shuffle; -exports.size = size; -exports.some = some; -exports.sortBy = sortBy; -exports.sortedIndex = sortedIndex; -exports.tap = tap; -exports.template = template; -exports.templateSettings = templateSettings; -exports.throttle = throttle; -exports.times = times; -exports.toArray = toArray; -exports.toPath = toPath$1; -exports.union = union; -exports.uniq = uniq; -exports.uniqueId = uniqueId; -exports.unzip = unzip; -exports.values = values; -exports.where = where; -exports.without = without; -exports.wrap = wrap; -exports.zip = zip; -//# sourceMappingURL=underscore-node-f.cjs.map - - -/***/ }), - -/***/ 5067: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -// Underscore.js 1.13.6 -// https://underscorejs.org -// (c) 2009-2022 Jeremy Ashkenas, Julian Gonggrijp, and DocumentCloud and Investigative Reporters & Editors -// Underscore may be freely distributed under the MIT license. - -var underscoreNodeF = __nccwpck_require__(6717); - - - -module.exports = underscoreNodeF._; -//# sourceMappingURL=underscore-node.cjs.map - - /***/ }), /***/ 1907: @@ -14330,7 +12170,7 @@ module.exports = JSON.parse('[[[0,44],"disallowed_STD3_valid"],[[45,46],"valid"] /******/ // startup /******/ // Load entry module and return exports /******/ // This entry module is referenced by other modules so it can't be inlined -/******/ var __webpack_exports__ = __nccwpck_require__(1307); +/******/ var __webpack_exports__ = __nccwpck_require__(7750); /******/ module.exports = __webpack_exports__; /******/ /******/ })() diff --git a/.github/actions/javascript/getGraphiteString/getGraphiteString.js b/.github/actions/javascript/getGraphiteString/getGraphiteString.ts similarity index 84% rename from .github/actions/javascript/getGraphiteString/getGraphiteString.js rename to .github/actions/javascript/getGraphiteString/getGraphiteString.ts index d4504a79ef6f..54132ab8c322 100644 --- a/.github/actions/javascript/getGraphiteString/getGraphiteString.js +++ b/.github/actions/javascript/getGraphiteString/getGraphiteString.ts @@ -1,6 +1,6 @@ -const core = require('@actions/core'); -const github = require('@actions/github'); -const fs = require('fs'); +import * as core from '@actions/core'; +import * as github from '@actions/github'; +import fs from 'fs'; const run = () => { // Prefix path to the graphite metric @@ -11,8 +11,10 @@ const run = () => { regressionOutput = JSON.parse(fs.readFileSync('.reassure/output.json', 'utf8')); } catch (err) { // Handle errors that occur during file reading or parsing - console.error('Error while parsing output.json:', err.message); - core.setFailed(err); + if (err instanceof Error) { + console.error('Error while parsing output.json:', err.message); + core.setFailed(err); + } } const creationDate = regressionOutput.metadata.current.creationDate; @@ -22,7 +24,7 @@ const run = () => { const timestamp = Math.floor(timestampInMili / 1000); // Get PR number from the github context - const prNumber = github.context.payload.pull_request.number; + const prNumber = github.context.payload.pull_request?.number; // We need to combine all tests from the 4 buckets const reassureTests = [...regressionOutput.meaningless, ...regressionOutput.significant, ...regressionOutput.countChanged, ...regressionOutput.added]; @@ -51,4 +53,4 @@ if (require.main === module) { run(); } -module.exports = run; +export default run; diff --git a/.github/actions/javascript/getGraphiteString/index.js b/.github/actions/javascript/getGraphiteString/index.js index f4bce400e413..43d1de6724e3 100644 --- a/.github/actions/javascript/getGraphiteString/index.js +++ b/.github/actions/javascript/getGraphiteString/index.js @@ -4,67 +4,6 @@ /******/ (() => { // webpackBootstrap /******/ var __webpack_modules__ = ({ -/***/ 1302: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -const core = __nccwpck_require__(2186); -const github = __nccwpck_require__(5438); -const fs = __nccwpck_require__(7147); - -const run = () => { - // Prefix path to the graphite metric - const GRAPHITE_PATH = 'reassure'; - - let regressionOutput; - try { - regressionOutput = JSON.parse(fs.readFileSync('.reassure/output.json', 'utf8')); - } catch (err) { - // Handle errors that occur during file reading or parsing - console.error('Error while parsing output.json:', err.message); - core.setFailed(err); - } - - const creationDate = regressionOutput.metadata.current.creationDate; - const timestampInMili = new Date(creationDate).getTime(); - - // Graphite accepts timestamp in seconds - const timestamp = Math.floor(timestampInMili / 1000); - - // Get PR number from the github context - const prNumber = github.context.payload.pull_request.number; - - // We need to combine all tests from the 4 buckets - const reassureTests = [...regressionOutput.meaningless, ...regressionOutput.significant, ...regressionOutput.countChanged, ...regressionOutput.added]; - - // Map through every test and create string for meanDuration and meanCount - // eslint-disable-next-line rulesdir/prefer-underscore-method - const graphiteString = reassureTests - .map((test) => { - const current = test.current; - // Graphite doesn't accept metrics name with space, we replace spaces with "-" - const formattedName = current.name.split(' ').join('-'); - - const renderDurationString = `${GRAPHITE_PATH}.${formattedName}.renderDuration ${current.meanDuration} ${timestamp}`; - const renderCountString = `${GRAPHITE_PATH}.${formattedName}.renderCount ${current.meanCount} ${timestamp}`; - const renderPRNumberString = `${GRAPHITE_PATH}.${formattedName}.prNumber ${prNumber} ${timestamp}`; - - return `${renderDurationString}\n${renderCountString}\n${renderPRNumberString}`; - }) - .join('\n'); - - // Set generated graphite string to the github variable - core.setOutput('GRAPHITE_STRING', graphiteString); -}; - -if (require.main === require.cache[eval('__filename')]) { - run(); -} - -module.exports = run; - - -/***/ }), - /***/ 7351: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { @@ -9565,6 +9504,87 @@ function wrappy (fn, cb) { } +/***/ }), + +/***/ 7717: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + +"use strict"; + +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +const core = __importStar(__nccwpck_require__(2186)); +const github = __importStar(__nccwpck_require__(5438)); +const fs_1 = __importDefault(__nccwpck_require__(7147)); +const run = () => { + // Prefix path to the graphite metric + const GRAPHITE_PATH = 'reassure'; + let regressionOutput; + try { + regressionOutput = JSON.parse(fs_1.default.readFileSync('.reassure/output.json', 'utf8')); + } + catch (err) { + // Handle errors that occur during file reading or parsing + if (err instanceof Error) { + console.error('Error while parsing output.json:', err.message); + core.setFailed(err); + } + } + const creationDate = regressionOutput.metadata.current.creationDate; + const timestampInMili = new Date(creationDate).getTime(); + // Graphite accepts timestamp in seconds + const timestamp = Math.floor(timestampInMili / 1000); + // Get PR number from the github context + const prNumber = github.context.payload.pull_request?.number; + // We need to combine all tests from the 4 buckets + const reassureTests = [...regressionOutput.meaningless, ...regressionOutput.significant, ...regressionOutput.countChanged, ...regressionOutput.added]; + // Map through every test and create string for meanDuration and meanCount + // eslint-disable-next-line rulesdir/prefer-underscore-method + const graphiteString = reassureTests + .map((test) => { + const current = test.current; + // Graphite doesn't accept metrics name with space, we replace spaces with "-" + const formattedName = current.name.split(' ').join('-'); + const renderDurationString = `${GRAPHITE_PATH}.${formattedName}.renderDuration ${current.meanDuration} ${timestamp}`; + const renderCountString = `${GRAPHITE_PATH}.${formattedName}.renderCount ${current.meanCount} ${timestamp}`; + const renderPRNumberString = `${GRAPHITE_PATH}.${formattedName}.prNumber ${prNumber} ${timestamp}`; + return `${renderDurationString}\n${renderCountString}\n${renderPRNumberString}`; + }) + .join('\n'); + // Set generated graphite string to the github variable + core.setOutput('GRAPHITE_STRING', graphiteString); +}; +if (require.main === require.cache[eval('__filename')]) { + run(); +} +exports["default"] = run; + + /***/ }), /***/ 2877: @@ -9745,7 +9765,7 @@ module.exports = JSON.parse('[[[0,44],"disallowed_STD3_valid"],[[45,46],"valid"] /******/ // startup /******/ // Load entry module and return exports /******/ // This entry module is referenced by other modules so it can't be inlined -/******/ var __webpack_exports__ = __nccwpck_require__(1302); +/******/ var __webpack_exports__ = __nccwpck_require__(7717); /******/ module.exports = __webpack_exports__; /******/ /******/ })() diff --git a/.github/actions/javascript/markPullRequestsAsDeployed/index.js b/.github/actions/javascript/markPullRequestsAsDeployed/index.js index 13bbfe30b05f..e43aec749df7 100644 --- a/.github/actions/javascript/markPullRequestsAsDeployed/index.js +++ b/.github/actions/javascript/markPullRequestsAsDeployed/index.js @@ -11568,7 +11568,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) { }; Object.defineProperty(exports, "__esModule", ({ value: true })); /* eslint-disable @typescript-eslint/naming-convention, import/no-import-module-exports */ -const core_1 = __importDefault(__nccwpck_require__(2186)); +const core = __importStar(__nccwpck_require__(2186)); const github_1 = __nccwpck_require__(5438); const ActionUtils = __importStar(__nccwpck_require__(970)); const CONST_1 = __importDefault(__nccwpck_require__(4097)); @@ -11600,7 +11600,7 @@ async function commentPR(PR, message) { catch (err) { console.log(`Unable to write comment on #${PR} 😞`); if (err instanceof Error) { - core_1.default.setFailed(err.message); + core.setFailed(err.message); } } } @@ -11608,11 +11608,11 @@ const workflowURL = `${process.env.GITHUB_SERVER_URL}/${process.env.GITHUB_REPOS async function run() { const prList = ActionUtils.getJSONInput('PR_LIST', { required: true }).map((num) => Number.parseInt(num, 10)); const isProd = ActionUtils.getJSONInput('IS_PRODUCTION_DEPLOY', { required: true }); - const version = core_1.default.getInput('DEPLOY_VERSION', { required: true }); - const androidResult = getDeployTableMessage(core_1.default.getInput('ANDROID', { required: true })); - const desktopResult = getDeployTableMessage(core_1.default.getInput('DESKTOP', { required: true })); - const iOSResult = getDeployTableMessage(core_1.default.getInput('IOS', { required: true })); - const webResult = getDeployTableMessage(core_1.default.getInput('WEB', { required: true })); + const version = core.getInput('DEPLOY_VERSION', { required: true }); + const androidResult = getDeployTableMessage(core.getInput('ANDROID', { required: true })); + const desktopResult = getDeployTableMessage(core.getInput('DESKTOP', { required: true })); + const iOSResult = getDeployTableMessage(core.getInput('IOS', { required: true })); + const webResult = getDeployTableMessage(core.getInput('WEB', { required: true })); function getDeployMessage(deployer, deployVerb, prTitle) { let message = `🚀 [${deployVerb}](${workflowURL}) to ${isProd ? 'production' : 'staging'}`; message += ` by https://github.com/${deployer} in version: ${version} 🚀`; @@ -11653,7 +11653,7 @@ async function run() { if (!currentTag) { const err = `Could not find tag matching ${version}`; console.error(err); - core_1.default.setFailed(err); + core.setFailed(err); return; } const { data: commit } = await GithubUtils_1.default.octokit.git.getCommit({ diff --git a/.github/actions/javascript/markPullRequestsAsDeployed/markPullRequestsAsDeployed.ts b/.github/actions/javascript/markPullRequestsAsDeployed/markPullRequestsAsDeployed.ts index ec70d1123000..fd031a98a4dc 100644 --- a/.github/actions/javascript/markPullRequestsAsDeployed/markPullRequestsAsDeployed.ts +++ b/.github/actions/javascript/markPullRequestsAsDeployed/markPullRequestsAsDeployed.ts @@ -1,5 +1,5 @@ /* eslint-disable @typescript-eslint/naming-convention, import/no-import-module-exports */ -import core from '@actions/core'; +import * as core from '@actions/core'; import {context} from '@actions/github'; import * as ActionUtils from '@github/libs/ActionUtils'; import CONST from '@github/libs/CONST'; diff --git a/.github/libs/promiseWhile.js b/.github/libs/promiseWhile.js index d3aca7eb7fd4..62c959293e89 100644 --- a/.github/libs/promiseWhile.js +++ b/.github/libs/promiseWhile.js @@ -6,12 +6,16 @@ * @returns {Promise} */ function promiseWhile(condition, action) { + console.info('[promiseWhile] promiseWhile()'); + return new Promise((resolve, reject) => { const loop = function () { if (!condition()) { resolve(); } else { - Promise.resolve(action()).then(loop).catch(reject); + const actionResult = action(); + console.info('[promiseWhile] promiseWhile() actionResult', actionResult); + Promise.resolve(actionResult).then(loop).catch(reject); } }; loop(); @@ -26,8 +30,13 @@ function promiseWhile(condition, action) { * @returns {Promise} */ function promiseDoWhile(condition, action) { + console.info('[promiseWhile] promiseDoWhile()'); + return new Promise((resolve, reject) => { - action() + console.info('[promiseWhile] promiseDoWhile() condition', condition); + const actionResult = action(); + console.info('[promiseWhile] promiseDoWhile() actionResult', actionResult); + actionResult .then(() => promiseWhile(condition, action)) .then(() => resolve()) .catch(reject); diff --git a/.github/scripts/buildActions.sh b/.github/scripts/buildActions.sh index df90e3351cc0..f9ec44cc8c12 100755 --- a/.github/scripts/buildActions.sh +++ b/.github/scripts/buildActions.sh @@ -25,8 +25,8 @@ declare -r GITHUB_ACTIONS=( "$ACTIONS_DIR/authorChecklist/authorChecklist.ts" "$ACTIONS_DIR/reviewerChecklist/reviewerChecklist.js" "$ACTIONS_DIR/validateReassureOutput/validateReassureOutput.js" - "$ACTIONS_DIR/getGraphiteString/getGraphiteString.js" - "$ACTIONS_DIR/getArtifactInfo/getArtifactInfo.js" + "$ACTIONS_DIR/getGraphiteString/getGraphiteString.ts" + "$ACTIONS_DIR/getArtifactInfo/getArtifactInfo.ts" ) # This will be inserted at the top of all compiled files as a warning to devs. diff --git a/__mocks__/pusher-js/react-native.js b/__mocks__/pusher-js/react-native.ts similarity index 100% rename from __mocks__/pusher-js/react-native.js rename to __mocks__/pusher-js/react-native.ts diff --git a/android/app/build.gradle b/android/app/build.gradle index 0b2271d16716..fb1fe29273b2 100644 --- a/android/app/build.gradle +++ b/android/app/build.gradle @@ -98,8 +98,8 @@ android { minSdkVersion rootProject.ext.minSdkVersion targetSdkVersion rootProject.ext.targetSdkVersion multiDexEnabled rootProject.ext.multiDexEnabled - versionCode 1001045605 - versionName "1.4.56-5" + versionCode 1001045702 + versionName "1.4.57-2" } flavorDimensions "default" diff --git a/docs/articles/new-expensify/bank-accounts/Connect-a-Bank-Account.md b/docs/articles/new-expensify/bank-accounts/Connect-a-Bank-Account.md index 307641c9c605..a618c80f98ed 100644 --- a/docs/articles/new-expensify/bank-accounts/Connect-a-Bank-Account.md +++ b/docs/articles/new-expensify/bank-accounts/Connect-a-Bank-Account.md @@ -94,6 +94,14 @@ If you need to enable direct debits from your verified bank account, your bank w - The ACH CompanyIDs (1270239450, 4270239450 and 2270239450) - The ACH Originator Name (Expensify) +If using Expensify to process Bill payments, you'll also need to whitelist the ACH IDs from our partner [Stripe](https://support.stripe.com/questions/ach-direct-debit-company-ids-for-stripe?): +- The ACH CompanyIDs (1800948598 and 4270465600) +- The ACH Originator Name (Stripe Payments company) + +If using Expensify to process international reimbursements from your USD bank account, you'll also need to whitelist the ACH IDs from our partner CorPay: +- The ACH CompanyIDs (1522304924 and 2522304924) +- The ACH Originator Name (Cambridge Global Payments) + To request to unlock the bank account, go to **Settings > Workspaces > _Workspace Name_ > Bank account** and click **Fix.** This sends a request to our support team to review why the bank account was locked, who will send you a message to confirm that. Unlocking a bank account can take 4-5 business days to process, to allow for ACH processing time and clawback periods. diff --git a/docs/redirects.csv b/docs/redirects.csv index 7539a2777d92..f239d95187c8 100644 --- a/docs/redirects.csv +++ b/docs/redirects.csv @@ -67,3 +67,6 @@ https://help.expensify.com/articles/expensify-classic/settings/Merge-Accounts,ht https://help.expensify.com/articles/expensify-classic/settings/Preferences,https://help.expensify.com/expensify-classic/hubs/settings/account-settings https://help.expensify.com/articles/expensify-classic/getting-started/support/Your-Expensify-Account-Manager,https://use.expensify.com/support https://help.expensify.com/articles/expensify-classic/settings/Copilot,https://help.expensify.com/expensify-classic/hubs/copilots-and-delegates/ +https://help.expensify.com/articles/expensify-classic/workspace-and-domain-settings/Budgets,https://help.expensify.com/articles/expensify-classic/workspaces/Budgets +https://help.expensify.com/articles/expensify-classic/workspace-and-domain-settings/Reimbursement,https://help.expensify.com/articles/expensify-classic/send-payments/Reimbursing-Reports +https://help.expensify.com/articles/expensify-classic/workspace-and-domain-settings/Tags,https://help.expensify.com/articles/expensify-classic/workspaces/Tags diff --git a/ios/NewExpensify/Info.plist b/ios/NewExpensify/Info.plist index 37741d484d63..a77f1c212d14 100644 --- a/ios/NewExpensify/Info.plist +++ b/ios/NewExpensify/Info.plist @@ -19,7 +19,7 @@ CFBundlePackageType APPL CFBundleShortVersionString - 1.4.56 + 1.4.57 CFBundleSignature ???? CFBundleURLTypes @@ -40,7 +40,7 @@ CFBundleVersion - 1.4.56.5 + 1.4.57.2 ITSAppUsesNonExemptEncryption LSApplicationQueriesSchemes diff --git a/ios/NewExpensifyTests/Info.plist b/ios/NewExpensifyTests/Info.plist index e228808076d0..6c6f4e526daf 100644 --- a/ios/NewExpensifyTests/Info.plist +++ b/ios/NewExpensifyTests/Info.plist @@ -15,10 +15,10 @@ CFBundlePackageType BNDL CFBundleShortVersionString - 1.4.56 + 1.4.57 CFBundleSignature ???? CFBundleVersion - 1.4.56.5 + 1.4.57.2 diff --git a/ios/NotificationServiceExtension/Info.plist b/ios/NotificationServiceExtension/Info.plist index 11f83011d47a..bbdb44e3bedf 100644 --- a/ios/NotificationServiceExtension/Info.plist +++ b/ios/NotificationServiceExtension/Info.plist @@ -11,9 +11,9 @@ CFBundleName $(PRODUCT_NAME) CFBundleShortVersionString - 1.4.56 + 1.4.57 CFBundleVersion - 1.4.56.5 + 1.4.57.2 NSExtension NSExtensionPointIdentifier diff --git a/ios/Podfile.lock b/ios/Podfile.lock index 310003ee8adc..c554ead97250 100644 --- a/ios/Podfile.lock +++ b/ios/Podfile.lock @@ -1363,7 +1363,7 @@ PODS: - RNGoogleSignin (10.0.1): - GoogleSignIn (~> 7.0) - React-Core - - RNLiveMarkdown (0.1.5): + - RNLiveMarkdown (0.1.33): - glog - RCT-Folly (= 2022.05.16.00) - React-Core @@ -1904,7 +1904,7 @@ SPEC CHECKSUMS: RNFS: 4ac0f0ea233904cb798630b3c077808c06931688 RNGestureHandler: 25b969a1ffc806b9f9ad2e170d4a3b049c6af85e RNGoogleSignin: ccaa4a81582cf713eea562c5dd9dc1961a715fd0 - RNLiveMarkdown: 35eeecf7e57eb26fdc279d5d4815982a9a9f7beb + RNLiveMarkdown: aaf75630fb2129db43fb5a873d33125e7173f3a0 RNLocalize: d4b8af4e442d4bcca54e68fc687a2129b4d71a81 rnmapbox-maps: fcf7f1cbdc8bd7569c267d07284e8a5c7bee06ed RNPermissions: 9b086c8f05b2e2faa587fdc31f4c5ab4509728aa diff --git a/package-lock.json b/package-lock.json index 6e7f23674852..e6d2e3e187fe 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,17 +1,17 @@ { "name": "new.expensify", - "version": "1.4.56-5", + "version": "1.4.57-2", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "new.expensify", - "version": "1.4.56-5", + "version": "1.4.57-2", "hasInstallScript": true, "license": "MIT", "dependencies": { "@dotlottie/react-player": "^1.6.3", - "@expensify/react-native-live-markdown": "0.1.5", + "@expensify/react-native-live-markdown": "0.1.33", "@expo/metro-runtime": "~3.1.1", "@formatjs/intl-datetimeformat": "^6.10.0", "@formatjs/intl-listformat": "^7.2.2", @@ -3095,11 +3095,9 @@ } }, "node_modules/@expensify/react-native-live-markdown": { - "version": "0.1.5", - "license": "MIT", - "workspaces": [ - "example" - ], + "version": "0.1.33", + "resolved": "https://registry.npmjs.org/@expensify/react-native-live-markdown/-/react-native-live-markdown-0.1.33.tgz", + "integrity": "sha512-K9WDwb7wdupGrOrZEFFQ57qNPYdGVNkF5qnhOfkhuvSL9UdZi3NLiyGzaohIIh1lXvElDgwaY0x0WtqkOXIsiw==", "engines": { "node": ">= 18.0.0" }, diff --git a/package.json b/package.json index 83c3095585be..1f56b465483f 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "new.expensify", - "version": "1.4.56-5", + "version": "1.4.57-2", "author": "Expensify, Inc.", "homepage": "https://new.expensify.com", "description": "New Expensify is the next generation of Expensify: a reimagination of payments based atop a foundation of chat.", @@ -62,7 +62,7 @@ }, "dependencies": { "@dotlottie/react-player": "^1.6.3", - "@expensify/react-native-live-markdown": "0.1.5", + "@expensify/react-native-live-markdown": "0.1.33", "@expo/metro-runtime": "~3.1.1", "@formatjs/intl-datetimeformat": "^6.10.0", "@formatjs/intl-listformat": "^7.2.2", diff --git a/src/App.tsx b/src/App.tsx index 76f9198e97b8..a3a9f7a3f3b6 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -22,6 +22,7 @@ import ScrollOffsetContextProvider from './components/ScrollOffsetContextProvide import ThemeIllustrationsProvider from './components/ThemeIllustrationsProvider'; import ThemeProvider from './components/ThemeProvider'; import ThemeStylesProvider from './components/ThemeStylesProvider'; +import {FullScreenContextProvider} from './components/VideoPlayerContexts/FullScreenContext'; import {PlaybackContextProvider} from './components/VideoPlayerContexts/PlaybackContext'; import {VideoPopoverMenuContextProvider} from './components/VideoPlayerContexts/VideoPopoverMenuContext'; import {VolumeContextProvider} from './components/VideoPlayerContexts/VolumeContext'; @@ -78,6 +79,7 @@ function App({url}: AppProps) { ActiveElementRoleProvider, ActiveWorkspaceContextProvider, PlaybackContextProvider, + FullScreenContextProvider, VolumeContextProvider, VideoPopoverMenuContextProvider, ]} diff --git a/src/CONST.ts b/src/CONST.ts index 29da04b2f471..0fa1c64be44d 100755 --- a/src/CONST.ts +++ b/src/CONST.ts @@ -337,7 +337,7 @@ const CONST = { TRACK_EXPENSE: 'trackExpense', P2P_DISTANCE_REQUESTS: 'p2pDistanceRequests', WORKFLOWS_DELAYED_SUBMISSION: 'workflowsDelayedSubmission', - ACCOUNTING: 'accounting', + ACCOUNTING_ON_NEW_EXPENSIFY: 'accountingOnNewExpensify', }, BUTTON_STATES: { DEFAULT: 'default', @@ -4159,6 +4159,7 @@ const CONST = { }, }, + MAX_TAX_RATE_INTEGER_PLACES: 4, MAX_TAX_RATE_DECIMAL_PLACES: 4, } as const; diff --git a/src/components/AmountTextInput.tsx b/src/components/AmountTextInput.tsx index 6842a3e1d335..abdef6707327 100644 --- a/src/components/AmountTextInput.tsx +++ b/src/components/AmountTextInput.tsx @@ -57,6 +57,10 @@ function AmountTextInput( role={CONST.ROLE.PRESENTATION} onKeyPress={onKeyPress as (event: NativeSyntheticEvent) => void} touchableInputWrapperStyle={touchableInputWrapperStyle} + // On iPad, even if the soft keyboard is hidden, the keyboard suggestion is still shown. + // Setting both autoCorrect and spellCheck to false will hide the suggestion. + autoCorrect={false} + spellCheck={false} // eslint-disable-next-line react/jsx-props-no-spreading {...rest} /> diff --git a/src/components/Attachments/AttachmentCarousel/CarouselItem.tsx b/src/components/Attachments/AttachmentCarousel/CarouselItem.tsx index 4988110538fe..ec2687d634bb 100644 --- a/src/components/Attachments/AttachmentCarousel/CarouselItem.tsx +++ b/src/components/Attachments/AttachmentCarousel/CarouselItem.tsx @@ -82,6 +82,7 @@ function CarouselItem({item, onPress, isFocused, isModalHovered}: CarouselItemPr isHovered={isModalHovered} isFocused={isFocused} duration={item.duration} + isUsedInCarousel /> diff --git a/src/components/Attachments/AttachmentCarousel/index.tsx b/src/components/Attachments/AttachmentCarousel/index.tsx index f05abfd6a0de..3a7e0f19c4cd 100644 --- a/src/components/Attachments/AttachmentCarousel/index.tsx +++ b/src/components/Attachments/AttachmentCarousel/index.tsx @@ -6,6 +6,7 @@ import {withOnyx} from 'react-native-onyx'; import type {Attachment, AttachmentSource} from '@components/Attachments/types'; import BlockingView from '@components/BlockingViews/BlockingView'; import * as Illustrations from '@components/Icon/Illustrations'; +import {useFullScreenContext} from '@components/VideoPlayerContexts/FullScreenContext'; import useLocalize from '@hooks/useLocalize'; import useTheme from '@hooks/useTheme'; import useThemeStyles from '@hooks/useThemeStyles'; @@ -32,6 +33,7 @@ function AttachmentCarousel({report, reportActions, parentReportActions, source, const theme = useTheme(); const {translate} = useLocalize(); const styles = useThemeStyles(); + const {isFullScreenRef} = useFullScreenContext(); const scrollRef = useRef(null); const canUseTouchScreen = DeviceCapabilities.canUseTouchScreen(); @@ -76,6 +78,10 @@ function AttachmentCarousel({report, reportActions, parentReportActions, source, /** Updates the page state when the user navigates between attachments */ const updatePage = useCallback( ({viewableItems}: UpdatePageProps) => { + if (isFullScreenRef.current) { + return; + } + Keyboard.dismiss(); // Since we can have only one item in view at a time, we can use the first item in the array @@ -95,12 +101,16 @@ function AttachmentCarousel({report, reportActions, parentReportActions, source, onNavigate(entry.item); } }, - [onNavigate], + [isFullScreenRef, onNavigate], ); /** Increments or decrements the index to get another selected item */ const cycleThroughAttachments = useCallback( (deltaSlide: number) => { + if (isFullScreenRef.current) { + return; + } + const nextIndex = page + deltaSlide; const nextItem = attachments[nextIndex]; @@ -110,7 +120,7 @@ function AttachmentCarousel({report, reportActions, parentReportActions, source, scrollRef.current.scrollToIndex({index: nextIndex, animated: canUseTouchScreen}); }, - [attachments, canUseTouchScreen, page], + [attachments, canUseTouchScreen, isFullScreenRef, page], ); const extractItemKey = useCallback( @@ -145,7 +155,12 @@ function AttachmentCarousel({report, reportActions, parentReportActions, source, return ( setContainerWidth(PixelRatio.roundToNearestPixel(nativeEvent.layout.width))} + onLayout={({nativeEvent}) => { + if (isFullScreenRef.current) { + return; + } + setContainerWidth(PixelRatio.roundToNearestPixel(nativeEvent.layout.width)); + }} onMouseEnter={() => !canUseTouchScreen && setShouldShowArrows(true)} onMouseLeave={() => !canUseTouchScreen && setShouldShowArrows(false)} > diff --git a/src/components/Attachments/AttachmentView/AttachmentViewVideo/index.tsx b/src/components/Attachments/AttachmentView/AttachmentViewVideo/index.tsx index 03e0c0252a66..9e91bfd64fed 100644 --- a/src/components/Attachments/AttachmentView/AttachmentViewVideo/index.tsx +++ b/src/components/Attachments/AttachmentView/AttachmentViewVideo/index.tsx @@ -12,13 +12,13 @@ type AttachmentViewVideoProps = Pick; + + /** Additional styles from OfflineWithFeedback applied to the row */ + style?: StyleProp; }; function Badge({ @@ -54,6 +57,7 @@ function Badge({ onPress = () => {}, icon, iconStyles = [], + style, }: BadgeProps) { const styles = useThemeStyles(); const StyleUtils = useStyleUtils(); @@ -61,6 +65,8 @@ function Badge({ const textColorStyles = success || error ? styles.textWhite : undefined; const Wrapper = pressable ? PressableWithoutFeedback : View; + const isDeleted = style && Array.isArray(style) ? style.includes(styles.offlineFeedback.deleted) : false; + const wrapperStyles: (state: PressableStateCallbackType) => StyleProp = useCallback( ({pressed}) => [styles.badge, styles.ml2, StyleUtils.getBadgeColorStyle(success, error, pressed, environment === CONST.ENVIRONMENT.ADHOC), badgeStyles], [styles.badge, styles.ml2, StyleUtils, success, error, environment, badgeStyles], @@ -86,7 +92,7 @@ function Badge({ )} {text} diff --git a/src/components/ButtonWithDropdownMenu/index.tsx b/src/components/ButtonWithDropdownMenu/index.tsx index e89026137b67..896330f5e77e 100644 --- a/src/components/ButtonWithDropdownMenu/index.tsx +++ b/src/components/ButtonWithDropdownMenu/index.tsx @@ -76,7 +76,7 @@ function ButtonWithDropdownMenu({ ref={buttonRef} onPress={(event) => onPress(event, selectedItem.value)} text={customText ?? selectedItem.text} - isDisabled={isDisabled} + isDisabled={isDisabled || !!selectedItem.disabled} isLoading={isLoading} shouldRemoveRightBorderRadius style={[styles.flex1, styles.pr0]} diff --git a/src/components/Composer/index.tsx b/src/components/Composer/index.tsx index b6443f3ca385..82f67382c44b 100755 --- a/src/components/Composer/index.tsx +++ b/src/components/Composer/index.tsx @@ -1,14 +1,16 @@ +import lodashDebounce from 'lodash/debounce'; import type {BaseSyntheticEvent, ForwardedRef} from 'react'; import React, {useCallback, useEffect, useMemo, useRef, useState} from 'react'; import {flushSync} from 'react-dom'; // eslint-disable-next-line no-restricted-imports -import type {DimensionValue, NativeSyntheticEvent, Text as RNText, TextInput, TextInputKeyPressEventData, TextInputSelectionChangeEventData} from 'react-native'; +import type {DimensionValue, NativeSyntheticEvent, Text as RNText, TextInput, TextInputKeyPressEventData, TextInputSelectionChangeEventData, TextStyle} from 'react-native'; import {StyleSheet, View} from 'react-native'; -import type {AnimatedTextInputRef} from '@components/RNTextInput'; -import RNTextInput from '@components/RNTextInput'; +import type {AnimatedMarkdownTextInputRef} from '@components/RNMarkdownTextInput'; +import RNMarkdownTextInput from '@components/RNMarkdownTextInput'; import Text from '@components/Text'; import useHtmlPaste from '@hooks/useHtmlPaste'; import useIsScrollBarVisible from '@hooks/useIsScrollBarVisible'; +import useMarkdownStyle from '@hooks/useMarkdownStyle'; import useStyleUtils from '@hooks/useStyleUtils'; import useTheme from '@hooks/useTheme'; import useThemeStyles from '@hooks/useThemeStyles'; @@ -79,10 +81,11 @@ function Composer( ) { const theme = useTheme(); const styles = useThemeStyles(); + const markdownStyle = useMarkdownStyle(); const StyleUtils = useStyleUtils(); const {windowWidth} = useWindowDimensions(); const textRef = useRef(null); - const textInput = useRef(null); + const textInput = useRef(null); const [numberOfLines, setNumberOfLines] = useState(numberOfLinesProp); const [selection, setSelection] = useState< | { @@ -97,7 +100,9 @@ function Composer( const [caretContent, setCaretContent] = useState(''); const [valueBeforeCaret, setValueBeforeCaret] = useState(''); const [textInputWidth, setTextInputWidth] = useState(''); + const [isRendered, setIsRendered] = useState(false); const isScrollBarVisible = useIsScrollBarVisible(textInput, value ?? ''); + const [prevScroll, setPrevScroll] = useState(); useEffect(() => { if (!shouldClear) { @@ -123,7 +128,7 @@ function Composer( const addCursorPositionToSelectionChange = (event: NativeSyntheticEvent) => { const webEvent = event as BaseSyntheticEvent; - if (shouldCalculateCaretPosition) { + if (shouldCalculateCaretPosition && isRendered) { // we do flushSync to make sure that the valueBeforeCaret is updated before we calculate the caret position to receive a proper position otherwise we will calculate position for the previous state flushSync(() => { setValueBeforeCaret(webEvent.target.value.slice(0, webEvent.nativeEvent.selection.start)); @@ -158,18 +163,19 @@ function Composer( (event: ClipboardEvent) => { const isVisible = checkComposerVisibility(); const isFocused = textInput.current?.isFocused(); + const isContenteditableDivFocused = document.activeElement?.nodeName === 'DIV' && document.activeElement?.hasAttribute('contenteditable'); if (!(isVisible || isFocused)) { return true; } - if (textInput.current !== event.target) { + if (textInput.current !== event.target && !(isContenteditableDivFocused && !event.clipboardData?.files.length)) { const eventTarget = event.target as HTMLInputElement | HTMLTextAreaElement | null; // To make sure the composer does not capture paste events from other inputs, we check where the event originated // If it did originate in another input, we return early to prevent the composer from handling the paste const isTargetInput = eventTarget?.nodeName === 'INPUT' || eventTarget?.nodeName === 'TEXTAREA' || eventTarget?.contentEditable === 'true'; - if (isTargetInput) { + if (isTargetInput || (!isFocused && isContenteditableDivFocused && event.clipboardData?.files.length)) { return true; } @@ -256,12 +262,44 @@ function Composer( updateNumberOfLines(); }, [updateNumberOfLines]); + const currentNumberOfLines = useMemo( + () => (isComposerFullSize ? undefined : numberOfLines), + + [isComposerFullSize, numberOfLines], + ); + + useEffect(() => { + if (!textInput.current) { + return; + } + const debouncedSetPrevScroll = lodashDebounce(() => { + if (!textInput.current) { + return; + } + setPrevScroll(textInput.current.scrollTop); + }, 100); + + textInput.current.addEventListener('scroll', debouncedSetPrevScroll); + return () => { + textInput.current?.removeEventListener('scroll', debouncedSetPrevScroll); + }; + }, []); + + useEffect(() => { + if (!textInput.current || prevScroll === undefined) { + return; + } + textInput.current.scrollTop = prevScroll; + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [isComposerFullSize]); + useHtmlPaste(textInput, handlePaste, true); useEffect(() => { if (typeof ref === 'function') { ref(textInput.current); } + setIsRendered(true); return () => { if (isReportActionCompose) { @@ -321,6 +359,7 @@ function Composer( StyleUtils.getComposeTextAreaPadding(numberOfLines, isComposerFullSize), Browser.isMobileSafari() || Browser.isSafari() ? styles.rtlTextRenderForSafari : {}, scrollStyleMemo, + isComposerFullSize ? ({height: '100%', maxHeight: 'none' as DimensionValue} as TextStyle) : undefined, ], [numberOfLines, scrollStyleMemo, styles.rtlTextRenderForSafari, style, StyleUtils, isComposerFullSize], @@ -328,20 +367,21 @@ function Composer( return ( <> - (textInput.current = el)} selection={selection} style={inputStyleMemo} + markdownStyle={markdownStyle} value={value} defaultValue={defaultValue} autoFocus={autoFocus} /* eslint-disable-next-line react/jsx-props-no-spreading */ {...props} onSelectionChange={addCursorPositionToSelectionChange} - numberOfLines={numberOfLines} + numberOfLines={currentNumberOfLines} disabled={isDisabled} onKeyPress={handleKeyPress} onFocus={(e) => { diff --git a/src/components/DistanceEReceipt.tsx b/src/components/DistanceEReceipt.tsx index fda0c5441734..20b927913bfb 100644 --- a/src/components/DistanceEReceipt.tsx +++ b/src/components/DistanceEReceipt.tsx @@ -15,9 +15,9 @@ import Icon from './Icon'; import * as Expensicons from './Icon/Expensicons'; import ImageSVG from './ImageSVG'; import PendingMapView from './MapView/PendingMapView'; +import ReceiptImage from './ReceiptImage'; import ScrollView from './ScrollView'; import Text from './Text'; -import ThumbnailImage from './ThumbnailImage'; type DistanceEReceiptProps = { /** The transaction for the distance request */ @@ -30,7 +30,7 @@ function DistanceEReceipt({transaction}: DistanceEReceiptProps) { const thumbnail = TransactionUtils.hasReceipt(transaction) ? ReceiptUtils.getThumbnailAndImageURIs(transaction).thumbnail : null; const {amount: transactionAmount, currency: transactionCurrency, merchant: transactionMerchant, created: transactionDate} = ReportUtils.getTransactionDetails(transaction) ?? {}; const formattedTransactionAmount = CurrencyUtils.convertToDisplayString(transactionAmount, transactionCurrency); - const thumbnailSource = tryResolveUrlFromApiRoot((thumbnail as string) || ''); + const thumbnailSource = tryResolveUrlFromApiRoot(thumbnail ?? ''); const waypoints = useMemo(() => transaction?.comment?.waypoints ?? {}, [transaction?.comment?.waypoints]); const sortedWaypoints = useMemo( () => @@ -58,11 +58,9 @@ function DistanceEReceipt({transaction}: DistanceEReceiptProps) { {TransactionUtils.isFetchingWaypointsFromServer(transaction) || !thumbnailSource ? ( ) : ( - )} diff --git a/src/components/EReceiptThumbnail.tsx b/src/components/EReceiptThumbnail.tsx index 023dcc16e696..63889f76e67c 100644 --- a/src/components/EReceiptThumbnail.tsx +++ b/src/components/EReceiptThumbnail.tsx @@ -5,6 +5,7 @@ import {withOnyx} from 'react-native-onyx'; import useStyleUtils from '@hooks/useStyleUtils'; import useThemeStyles from '@hooks/useThemeStyles'; import * as ReportUtils from '@libs/ReportUtils'; +import colors from '@styles/theme/colors'; import variables from '@styles/variables'; import CONST from '@src/CONST'; import ONYXKEYS from '@src/ONYXKEYS'; @@ -14,6 +15,7 @@ import * as eReceiptBGs from './Icon/EReceiptBGs'; import * as Expensicons from './Icon/Expensicons'; import * as MCCIcons from './Icon/MCCIcons'; import Image from './Image'; +import Text from './Text'; type EReceiptThumbnailOnyxProps = { transaction: OnyxEntry; @@ -26,6 +28,15 @@ type EReceiptThumbnailProps = EReceiptThumbnailOnyxProps & { // eslint-disable-next-line react/no-unused-prop-types transactionID: string; + /** Border radius to be applied on the parent view. */ + borderRadius?: number; + + /** The file extension of the receipt that the preview thumbnail is being displayed for. */ + fileExtension?: string; + + /** Whether it is a receipt thumbnail we are displaying. */ + isReceiptThumbnail?: boolean; + /** Center the eReceipt Icon vertically */ centerIconV?: boolean; @@ -42,13 +53,14 @@ const backgroundImages = { [CONST.ERECEIPT_COLORS.PINK]: eReceiptBGs.EReceiptBG_Pink, }; -function EReceiptThumbnail({transaction, centerIconV = true, iconSize = 'large'}: EReceiptThumbnailProps) { +function EReceiptThumbnail({transaction, borderRadius, fileExtension, isReceiptThumbnail = false, centerIconV = true, iconSize = 'large'}: EReceiptThumbnailProps) { const styles = useThemeStyles(); const StyleUtils = useStyleUtils(); + const colorCode = isReceiptThumbnail ? StyleUtils.getFileExtensionColorCode(fileExtension) : StyleUtils.getEReceiptColorCode(transaction); - const backgroundImage = useMemo(() => backgroundImages[StyleUtils.getEReceiptColorCode(transaction)], [StyleUtils, transaction]); + const backgroundImage = useMemo(() => backgroundImages[colorCode], [colorCode]); - const colorStyles = StyleUtils.getEReceiptColorStyles(StyleUtils.getEReceiptColorCode(transaction)); + const colorStyles = StyleUtils.getEReceiptColorStyles(colorCode); const primaryColor = colorStyles?.backgroundColor; const secondaryColor = colorStyles?.color; const transactionDetails = ReportUtils.getTransactionDetails(transaction); @@ -58,15 +70,21 @@ function EReceiptThumbnail({transaction, centerIconV = true, iconSize = 'large'} let receiptIconWidth: number = variables.eReceiptIconWidth; let receiptIconHeight: number = variables.eReceiptIconHeight; let receiptMCCSize: number = variables.eReceiptMCCHeightWidth; + let labelFontSize: number = variables.fontSizeNormal; + let labelLineHeight: number = variables.lineHeightLarge; if (iconSize === 'small') { receiptIconWidth = variables.eReceiptIconWidthSmall; receiptIconHeight = variables.eReceiptIconHeightSmall; receiptMCCSize = variables.eReceiptMCCHeightWidthSmall; + labelFontSize = variables.fontSizeExtraSmall; + labelLineHeight = variables.lineHeightXSmall; } else if (iconSize === 'medium') { receiptIconWidth = variables.eReceiptIconWidthMedium; receiptIconHeight = variables.eReceiptIconHeightMedium; receiptMCCSize = variables.eReceiptMCCHeightWidthMedium; + labelFontSize = variables.fontSizeLabel; + labelLineHeight = variables.lineHeightNormal; } return ( @@ -77,6 +95,7 @@ function EReceiptThumbnail({transaction, centerIconV = true, iconSize = 'large'} styles.overflowHidden, styles.alignItemsCenter, centerIconV ? styles.justifyContentCenter : {}, + borderRadius ? {borderRadius} : {}, ]} > - {MCCIcon ? ( + {isReceiptThumbnail && fileExtension && ( + + {fileExtension.toUpperCase()} + + )} + {MCCIcon && !isReceiptThumbnail ? ( ({ transaction: { key: ({transactionID}) => `${ONYXKEYS.COLLECTION.TRANSACTION}${transactionID}`, }, })(EReceiptThumbnail); -export type {EReceiptThumbnailProps, EReceiptThumbnailOnyxProps}; +export type {IconSize, EReceiptThumbnailProps, EReceiptThumbnailOnyxProps}; diff --git a/src/components/EmojiPicker/EmojiPickerMenu/useEmojiPickerMenu.js b/src/components/EmojiPicker/EmojiPickerMenu/useEmojiPickerMenu.js index 7caab5e6fb55..c6f9f601f4df 100644 --- a/src/components/EmojiPicker/EmojiPickerMenu/useEmojiPickerMenu.js +++ b/src/components/EmojiPicker/EmojiPickerMenu/useEmojiPickerMenu.js @@ -24,7 +24,12 @@ const useEmojiPickerMenu = () => { const [preferredSkinTone] = usePreferredEmojiSkinTone(); const {windowHeight} = useWindowDimensions(); const StyleUtils = useStyleUtils(); - const listStyle = StyleUtils.getEmojiPickerListHeight(isListFiltered, windowHeight); + /** + * At EmojiPicker has set innerContainerStyle with maxHeight: '95%' by styles.popoverInnerContainer + * to avoid the list style to be cut off due to the list height being larger than the container height + * so we need to calculate listStyle based on the height of the window and innerContainerStyle at the EmojiPicker + */ + const listStyle = StyleUtils.getEmojiPickerListHeight(isListFiltered, windowHeight * 0.95); useEffect(() => { setFilteredEmojis(allEmojis); diff --git a/src/components/HTMLEngineProvider/BaseHTMLEngineProvider.tsx b/src/components/HTMLEngineProvider/BaseHTMLEngineProvider.tsx index af04c11de41e..a06e2dbbf421 100755 --- a/src/components/HTMLEngineProvider/BaseHTMLEngineProvider.tsx +++ b/src/components/HTMLEngineProvider/BaseHTMLEngineProvider.tsx @@ -71,8 +71,13 @@ function BaseHTMLEngineProvider({textSelectable = false, children, enableExperim contentModel: HTMLContentModel.block, }), emoji: HTMLElementModel.fromCustomModel({tagName: 'emoji', contentModel: HTMLContentModel.textual}), + 'completed-task': HTMLElementModel.fromCustomModel({ + tagName: 'completed-task', + mixedUAStyles: {...styles.textSupporting, ...styles.textLineThrough}, + contentModel: HTMLContentModel.textual, + }), }), - [styles.colorMuted, styles.formError, styles.mb0, styles.textLabelSupporting, styles.lh16], + [styles.formError, styles.mb0, styles.colorMuted, styles.textLabelSupporting, styles.lh16, styles.textSupporting, styles.textLineThrough], ); /* eslint-enable @typescript-eslint/naming-convention */ diff --git a/src/components/MoneyRequestConfirmationList.tsx b/src/components/MoneyRequestConfirmationList.tsx index 4550a7aef5d2..1c72aa37b73f 100755 --- a/src/components/MoneyRequestConfirmationList.tsx +++ b/src/components/MoneyRequestConfirmationList.tsx @@ -35,10 +35,10 @@ import ButtonWithDropdownMenu from './ButtonWithDropdownMenu'; import type {DropdownOption} from './ButtonWithDropdownMenu/types'; import ConfirmedRoute from './ConfirmedRoute'; import FormHelpMessage from './FormHelpMessage'; -import Image from './Image'; import MenuItemWithTopDescription from './MenuItemWithTopDescription'; import OptionsSelector from './OptionsSelector'; import ReceiptEmptyState from './ReceiptEmptyState'; +import ReceiptImage from './ReceiptImage'; import SettlementButton from './SettlementButton'; import ShowMoreButton from './ShowMoreButton'; import Switch from './Switch'; @@ -536,7 +536,6 @@ function MoneyRequestConfirmationList({ onPress={confirm} enablePaymentsRoute={ROUTES.IOU_SEND_ENABLE_PAYMENTS} addBankAccountRoute={bankAccountRoute} - addDebitCardRoute={ROUTES.IOU_SEND_ADD_DEBIT_CARD} currency={iouCurrencyCode} policyID={policyID} buttonSize={CONST.DROPDOWN_BUTTON_SIZE.LARGE} @@ -577,8 +576,12 @@ function MoneyRequestConfirmationList({ ); }, [isReadOnly, iouType, bankAccountRoute, iouCurrencyCode, policyID, selectedParticipants.length, confirm, splitOrRequestOptions, formError, styles.ph1, styles.mb2]); - const {image: receiptImage, thumbnail: receiptThumbnail} = - receiptPath && receiptFilename ? ReceiptUtils.getThumbnailAndImageURIs(transaction, receiptPath, receiptFilename) : ({} as ReceiptUtils.ThumbnailAndImageURI); + const { + image: receiptImage, + thumbnail: receiptThumbnail, + isThumbnail, + fileExtension, + } = receiptPath && receiptFilename ? ReceiptUtils.getThumbnailAndImageURIs(transaction, receiptPath, receiptFilename) : ({} as ReceiptUtils.ThumbnailAndImageURI); return ( // @ts-expect-error This component is deprecated and will not be migrated to TypeScript (context: https://expensify.slack.com/archives/C01GTK53T8Q/p1709232289899589?thread_ts=1709156803.359359&cid=C01GTK53T8Q) )} - + {/* eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing */} {receiptImage || receiptThumbnail ? ( - ) : ( // The empty receipt component should only show for IOU Requests of a paid policy ("Team" or "Corporate") diff --git a/src/components/MoneyTemporaryForRefactorRequestConfirmationList.js b/src/components/MoneyTemporaryForRefactorRequestConfirmationList.js index f27cd507d668..1907bc132c6b 100755 --- a/src/components/MoneyTemporaryForRefactorRequestConfirmationList.js +++ b/src/components/MoneyTemporaryForRefactorRequestConfirmationList.js @@ -37,12 +37,12 @@ import ConfirmedRoute from './ConfirmedRoute'; import ConfirmModal from './ConfirmModal'; import FormHelpMessage from './FormHelpMessage'; import * as Expensicons from './Icon/Expensicons'; -import Image from './Image'; import MenuItemWithTopDescription from './MenuItemWithTopDescription'; import optionPropTypes from './optionPropTypes'; import OptionsSelector from './OptionsSelector'; import PDFThumbnail from './PDFThumbnail'; import ReceiptEmptyState from './ReceiptEmptyState'; +import ReceiptImage from './ReceiptImage'; import SettlementButton from './SettlementButton'; import Switch from './Switch'; import tagPropTypes from './tagPropTypes'; @@ -626,7 +626,6 @@ function MoneyTemporaryForRefactorRequestConfirmationList({ onPress={confirm} enablePaymentsRoute={ROUTES.IOU_SEND_ENABLE_PAYMENTS} addBankAccountRoute={bankAccountRoute} - addDebitCardRoute={ROUTES.IOU_SEND_ADD_DEBIT_CARD} currency={iouCurrencyCode} policyID={policyID} buttonSize={CONST.DROPDOWN_BUTTON_SIZE.LARGE} @@ -897,6 +896,8 @@ function MoneyTemporaryForRefactorRequestConfirmationList({ const { image: receiptImage, thumbnail: receiptThumbnail, + isThumbnail, + fileExtension, isLocalFile, } = receiptPath && receiptFilename ? ReceiptUtils.getThumbnailAndImageURIs(transaction, receiptPath, receiptFilename) : {}; @@ -911,16 +912,18 @@ function MoneyTemporaryForRefactorRequestConfirmationList({ onPassword={() => setIsAttachmentInvalid(true)} /> ) : ( - ), - [receiptFilename, receiptImage, styles, receiptThumbnail, isLocalFile, isAttachmentInvalid], + [isLocalFile, receiptFilename, receiptImage, styles.moneyRequestImage, isAttachmentInvalid, isThumbnail, receiptThumbnail, fileExtension], ); return ( diff --git a/src/components/ReceiptImage.tsx b/src/components/ReceiptImage.tsx new file mode 100644 index 000000000000..08892f11b021 --- /dev/null +++ b/src/components/ReceiptImage.tsx @@ -0,0 +1,136 @@ +import React from 'react'; +import {View} from 'react-native'; +import useThemeStyles from '@hooks/useThemeStyles'; +import type IconAsset from '@src/types/utils/IconAsset'; +import EReceiptThumbnail from './EReceiptThumbnail'; +import type {IconSize} from './EReceiptThumbnail'; +import Image from './Image'; +import PDFThumbnail from './PDFThumbnail'; +import ThumbnailImage from './ThumbnailImage'; + +type Style = {height: number; borderRadius: number; margin: number}; + +type ReceiptImageProps = ( + | { + /** Transaction ID of the transaction the receipt belongs to */ + transactionID: string; + + /** Whether it is EReceipt */ + isEReceipt: boolean; + + /** Whether it is receipt preview thumbnail we are displaying */ + isThumbnail?: boolean; + + /** Url of the receipt image */ + source?: string; + + /** Whether it is a pdf thumbnail we are displaying */ + isPDFThumbnail?: boolean; + } + | { + transactionID?: string; + isEReceipt?: boolean; + isThumbnail: boolean; + source?: string; + isPDFThumbnail?: boolean; + } + | { + transactionID?: string; + isEReceipt?: boolean; + isThumbnail?: boolean; + source: string; + isPDFThumbnail?: boolean; + } + | { + transactionID?: string; + isEReceipt?: boolean; + isThumbnail?: boolean; + source: string; + isPDFThumbnail: string; + } +) & { + /** Whether we should display the receipt with ThumbnailImage component */ + shouldUseThumbnailImage?: boolean; + + /** Whether the receipt image requires an authToken */ + isAuthTokenRequired?: boolean; + + /** Any additional styles to apply */ + style?: Style; + + /** The file extension of the receipt file */ + fileExtension?: string; + + /** number of images displayed in the same parent container */ + iconSize?: IconSize; + + /** If the image fails to load – show the provided fallback icon */ + fallbackIcon?: IconAsset; + + /** The size of the fallback icon */ + fallbackIconSize?: number; +}; + +function ReceiptImage({ + transactionID, + isPDFThumbnail = false, + isThumbnail = false, + shouldUseThumbnailImage = false, + isEReceipt = false, + source, + isAuthTokenRequired, + style, + fileExtension, + iconSize, + fallbackIcon, + fallbackIconSize, +}: ReceiptImageProps) { + const styles = useThemeStyles(); + + if (isPDFThumbnail) { + return ( + + ); + } + + if (isEReceipt || isThumbnail) { + const props = isThumbnail && {borderRadius: style?.borderRadius, fileExtension, isReceiptThumbnail: true}; + return ( + + + + ); + } + + if (shouldUseThumbnailImage) { + return ( + + ); + } + + return ( + + ); +} + +export type {ReceiptImageProps}; +export default ReceiptImage; diff --git a/src/components/ReportActionItem/MoneyRequestView.tsx b/src/components/ReportActionItem/MoneyRequestView.tsx index bb0308ee4509..5c382ca8ee33 100644 --- a/src/components/ReportActionItem/MoneyRequestView.tsx +++ b/src/components/ReportActionItem/MoneyRequestView.tsx @@ -259,6 +259,8 @@ function MoneyRequestView({ ) : ( { - if (thumbnail) { - return typeof thumbnail === 'string' ? {uri: thumbnail} : thumbnail; - } - - return typeof image === 'string' ? {uri: image} : image; - }, [image, thumbnail]); + let propsObj: ReceiptImageProps; if (isEReceipt) { - receiptImageComponent = ( - - - - ); + propsObj = {isEReceipt: true, transactionID: transaction.transactionID, iconSize: isSingleImage ? 'medium' : ('small' as IconSize)}; } else if (thumbnail && !isLocalFile) { - receiptImageComponent = ( - - ); + propsObj = { + shouldUseThumbnailImage: true, + source: thumbnailSource, + fallbackIcon: Expensicons.Receipt, + fallbackIconSize: isSingleImage ? variables.iconSizeSuperLarge : variables.iconSizeExtraLarge, + }; } else if (isLocalFile && filename && Str.isPDF(filename) && typeof attachmentModalSource === 'string') { - receiptImageComponent = ( - - ); + propsObj = {isPDFThumbnail: true, source: attachmentModalSource}; } else { - receiptImageComponent = ( - - ); + propsObj = { + isThumbnail, + ...(isThumbnail && {iconSize: (isSingleImage ? 'medium' : 'small') as IconSize, fileExtension}), + source: thumbnail ?? image ?? '', + }; } if (enablePreviewModal) { @@ -113,14 +102,14 @@ function ReportActionItemImage({thumbnail, image, enablePreviewModal = false, tr accessibilityLabel={translate('accessibilityHints.viewAttachment')} accessibilityRole={CONST.ROLE.BUTTON} > - {receiptImageComponent} + )} ); } - return receiptImageComponent; + return ; } ReportActionItemImage.displayName = 'ReportActionItemImage'; diff --git a/src/components/ReportActionItem/ReportActionItemImages.tsx b/src/components/ReportActionItem/ReportActionItemImages.tsx index c66dc36d1ed5..ee8cb0849ca0 100644 --- a/src/components/ReportActionItem/ReportActionItemImages.tsx +++ b/src/components/ReportActionItem/ReportActionItemImages.tsx @@ -65,21 +65,23 @@ function ReportActionItemImages({images, size, total, isHovered = false}: Report return ( - {shownImages.map(({thumbnail, image, transaction, isLocalFile, filename}, index) => { + {shownImages.map(({thumbnail, isThumbnail, image, transaction, isLocalFile, fileExtension, filename}, index) => { // Show a border to separate multiple images. Shown to the right for each except the last. const shouldShowBorder = shownImages.length > 1 && index < shownImages.length - 1; const borderStyle = shouldShowBorder ? styles.reportActionItemImageBorder : {}; return ( diff --git a/src/components/ReportActionItem/TaskPreview.tsx b/src/components/ReportActionItem/TaskPreview.tsx index f0d9ad88868c..8e8b3b930be7 100644 --- a/src/components/ReportActionItem/TaskPreview.tsx +++ b/src/components/ReportActionItem/TaskPreview.tsx @@ -108,7 +108,7 @@ function TaskPreview({taskReport, taskReportID, action, contextMenuAnchor, chatR })} accessibilityLabel={translate('task.task')} /> - + ${htmlForTaskPreview}` : htmlForTaskPreview} /> ( // If `initiallyFocusedOptionKey` is not passed, we fall back to `-1`, to avoid showing the highlight on the first member const [focusedIndex, setFocusedIndex] = useState(() => flattenedSections.allOptions.findIndex((option) => option.keyForList === initiallyFocusedOptionKey)); - const [slicedSections, ShowMoreButtonInstance] = useMemo( - () => [ - sections.map((section) => { - if (isEmpty(section.data)) { - return section; - } + const [slicedSections, ShowMoreButtonInstance] = useMemo(() => { + let remainingOptionsLimit = CONST.MAX_OPTIONS_SELECTOR_PAGE_LENGTH * currentPage; + const processedSections = sections.map((section) => { + const data = !isEmpty(section.data) && remainingOptionsLimit > 0 ? section.data.slice(0, remainingOptionsLimit) : []; + remainingOptionsLimit -= data.length; - return { - ...section, - data: section.data.slice(0, CONST.MAX_OPTIONS_SELECTOR_PAGE_LENGTH * currentPage), - }; - }), - flattenedSections.allOptions.length > CONST.MAX_OPTIONS_SELECTOR_PAGE_LENGTH * currentPage ? ( - - ) : null, - ], + return { + ...section, + data, + }; + }); + + const shouldShowMoreButton = flattenedSections.allOptions.length > CONST.MAX_OPTIONS_SELECTOR_PAGE_LENGTH * currentPage; + const showMoreButton = shouldShowMoreButton ? ( + + ) : null; + return [processedSections, showMoreButton]; // we don't need to add styles here as they change // we don't need to add flattendedSections here as they will change along with sections // eslint-disable-next-line react-hooks/exhaustive-deps - [sections, currentPage], - ); + }, [sections, currentPage]); // Disable `Enter` shortcut if the active element is a button or checkbox const disableEnterShortcut = activeElementRole && [CONST.ROLE.BUTTON, CONST.ROLE.CHECKBOX].includes(activeElementRole as ButtonOrCheckBoxRoles); @@ -476,7 +476,7 @@ function BaseSelectionList( section.data).length - 1} onFocusedIndexChanged={updateAndScrollToFocusedIndex} > diff --git a/src/components/SettlementButton.tsx b/src/components/SettlementButton.tsx index 690a9485f099..ead43bd9fe73 100644 --- a/src/components/SettlementButton.tsx +++ b/src/components/SettlementButton.tsx @@ -11,8 +11,8 @@ import * as IOU from '@userActions/IOU'; import * as PaymentMethods from '@userActions/PaymentMethods'; import CONST from '@src/CONST'; import ONYXKEYS from '@src/ONYXKEYS'; -import ROUTES from '@src/ROUTES'; import type {Route} from '@src/ROUTES'; +import ROUTES from '@src/ROUTES'; import type {ButtonSizeValue} from '@src/styles/utils/types'; import type {LastPaymentMethod, Report} from '@src/types/onyx'; import type {PaymentMethodType} from '@src/types/onyx/OriginalMessage'; @@ -101,7 +101,7 @@ type SettlementButtonProps = SettlementButtonOnyxProps & { }; function SettlementButton({ - addDebitCardRoute = '', + addDebitCardRoute = ROUTES.IOU_SEND_ADD_DEBIT_CARD, addBankAccountRoute = '', kycWallAnchorAlignment = { horizontal: CONST.MODAL.ANCHOR_ORIGIN_HORIZONTAL.LEFT, // button is at left, so horizontal anchor is at LEFT @@ -203,7 +203,7 @@ function SettlementButton({ return buttonOptions; // We don't want to reorder the options when the preferred payment method changes while the button is still visible // eslint-disable-next-line react-hooks/exhaustive-deps - }, [currency, formattedAmount, iouReport, policyID, translate, shouldHidePaymentOptions, shouldShowApproveButton]); + }, [currency, formattedAmount, iouReport, policyID, translate, shouldHidePaymentOptions, shouldShowApproveButton, shouldDisableApproveButton]); const selectPaymentType = (event: KYCFlowEvent, iouPaymentType: PaymentMethodType, triggerKYCFlow: TriggerKYCFlow) => { if (iouPaymentType === CONST.IOU.PAYMENT_TYPE.EXPENSIFY || iouPaymentType === CONST.IOU.PAYMENT_TYPE.VBBA) { triggerKYCFlow(event, iouPaymentType); diff --git a/src/components/TagPicker/index.js b/src/components/TagPicker/index.tsx similarity index 53% rename from src/components/TagPicker/index.js rename to src/components/TagPicker/index.tsx index 341ea9cddae9..af8acd19e8c4 100644 --- a/src/components/TagPicker/index.js +++ b/src/components/TagPicker/index.tsx @@ -1,7 +1,7 @@ -import lodashGet from 'lodash/get'; import React, {useMemo, useState} from 'react'; +import type {OnyxEntry} from 'react-native-onyx'; import {withOnyx} from 'react-native-onyx'; -import _ from 'underscore'; +import type {EdgeInsets} from 'react-native-safe-area-context'; import OptionsSelector from '@components/OptionsSelector'; import useLocalize from '@hooks/useLocalize'; import useStyleUtils from '@hooks/useStyleUtils'; @@ -10,22 +10,64 @@ import * as OptionsListUtils from '@libs/OptionsListUtils'; import * as PolicyUtils from '@libs/PolicyUtils'; import CONST from '@src/CONST'; import ONYXKEYS from '@src/ONYXKEYS'; -import {defaultProps, propTypes} from './tagPickerPropTypes'; +import type {PolicyTag, PolicyTagList, PolicyTags, RecentlyUsedTags} from '@src/types/onyx'; -function TagPicker({selectedTag, tag, tagIndex, policyTags, policyRecentlyUsedTags, shouldShowDisabledAndSelectedOption, insets, onSubmit}) { +type SelectedTagOption = { + name: string; + enabled: boolean; + accountID: number | null; +}; + +type TagPickerOnyxProps = { + /** Collection of tag list on a policy */ + policyTags: OnyxEntry; + + /** List of recently used tags */ + policyRecentlyUsedTags: OnyxEntry; +}; + +type TagPickerProps = TagPickerOnyxProps & { + /** The policyID we are getting tags for */ + // It's used in withOnyx HOC. + // eslint-disable-next-line react/no-unused-prop-types + policyID: string; + + /** The selected tag of the money request */ + selectedTag: string; + + /** The name of tag list we are getting tags for */ + tagListName: string; + + /** Callback to submit the selected tag */ + onSubmit: () => void; + + /** + * Safe area insets required for reflecting the portion of the view, + * that is not covered by navigation bars, tab bars, toolbars, and other ancestor views. + */ + insets: EdgeInsets; + + /** Should show the selected option that is disabled? */ + shouldShowDisabledAndSelectedOption?: boolean; + + /** Indicates which tag list index was selected */ + tagListIndex: number; +}; + +function TagPicker({selectedTag, tagListName, policyTags, tagListIndex, policyRecentlyUsedTags, shouldShowDisabledAndSelectedOption = false, insets, onSubmit}: TagPickerProps) { const styles = useThemeStyles(); const StyleUtils = useStyleUtils(); const {translate} = useLocalize(); const [searchValue, setSearchValue] = useState(''); - const policyRecentlyUsedTagsList = lodashGet(policyRecentlyUsedTags, tag, []); - const policyTagList = PolicyUtils.getTagList(policyTags, tagIndex); + const policyRecentlyUsedTagsList = useMemo(() => policyRecentlyUsedTags?.[tagListName] ?? [], [policyRecentlyUsedTags, tagListName]); + const policyTagList = PolicyUtils.getTagList(policyTags, tagListIndex); const policyTagsCount = PolicyUtils.getCountOfEnabledTagsOfList(policyTagList.tags); const isTagsCountBelowThreshold = policyTagsCount < CONST.TAG_LIST_THRESHOLD; const shouldShowTextInput = !isTagsCountBelowThreshold; - const selectedOptions = useMemo(() => { + const selectedOptions: SelectedTagOption[] = useMemo(() => { if (!selectedTag) { return []; } @@ -39,13 +81,13 @@ function TagPicker({selectedTag, tag, tagIndex, policyTags, policyRecentlyUsedTa ]; }, [selectedTag]); - const enabledTags = useMemo(() => { + const enabledTags: PolicyTags | Array = useMemo(() => { if (!shouldShowDisabledAndSelectedOption) { return policyTagList.tags; } - const selectedNames = _.map(selectedOptions, (s) => s.name); - const tags = [...selectedOptions, ..._.filter(policyTagList.tags, (policyTag) => policyTag.enabled && !selectedNames.includes(policyTag.name))]; - return tags; + const selectedNames = selectedOptions.map((s) => s.name); + + return [...selectedOptions, ...Object.values(policyTagList.tags).filter((policyTag) => policyTag.enabled && !selectedNames.includes(policyTag.name))]; }, [selectedOptions, policyTagList, shouldShowDisabledAndSelectedOption]); const sections = useMemo( @@ -53,12 +95,13 @@ function TagPicker({selectedTag, tag, tagIndex, policyTags, policyRecentlyUsedTa [searchValue, enabledTags, selectedOptions, policyRecentlyUsedTagsList], ); - const headerMessage = OptionsListUtils.getHeaderMessageForNonUserList(lodashGet(sections, '[0].data.length', 0) > 0, searchValue); + const headerMessage = OptionsListUtils.getHeaderMessageForNonUserList((sections?.[0]?.data?.length ?? 0) > 0, searchValue); - const selectedOptionKey = lodashGet(_.filter(lodashGet(sections, '[0].data', []), (policyTag) => policyTag.searchText === selectedTag)[0], 'keyForList'); + const selectedOptionKey = sections[0]?.data?.filter((policyTag) => policyTag.searchText === selectedTag)?.[0]?.keyForList; return ( ({ policyTags: { key: ({policyID}) => `${ONYXKEYS.COLLECTION.POLICY_TAGS}${policyID}`, }, @@ -92,3 +133,5 @@ export default withOnyx({ key: ({policyID}) => `${ONYXKEYS.COLLECTION.POLICY_RECENTLY_USED_TAGS}${policyID}`, }, })(TagPicker); + +export type {SelectedTagOption}; diff --git a/src/components/TagPicker/tagPickerPropTypes.js b/src/components/TagPicker/tagPickerPropTypes.js deleted file mode 100644 index cbdc73f5d056..000000000000 --- a/src/components/TagPicker/tagPickerPropTypes.js +++ /dev/null @@ -1,44 +0,0 @@ -import PropTypes from 'prop-types'; -import tagPropTypes from '@components/tagPropTypes'; -import safeAreaInsetPropTypes from '@pages/safeAreaInsetPropTypes'; - -const propTypes = { - /** The policyID we are getting tags for */ - policyID: PropTypes.string.isRequired, - - /** The selected tag of the money request */ - selectedTag: PropTypes.string.isRequired, - - /** The name of tag list we are getting tags for */ - tag: PropTypes.string.isRequired, - - /** The index of a tag list */ - tagIndex: PropTypes.number.isRequired, - - /** Callback to submit the selected tag */ - onSubmit: PropTypes.func.isRequired, - - /** - * Safe area insets required for reflecting the portion of the view, - * that is not covered by navigation bars, tab bars, toolbars, and other ancestor views. - */ - insets: safeAreaInsetPropTypes.isRequired, - - /* Onyx Props */ - /** Collection of tags attached to a policy */ - policyTags: tagPropTypes, - - /** List of recently used tags */ - policyRecentlyUsedTags: PropTypes.objectOf(PropTypes.arrayOf(PropTypes.string)), - - /** Should show the selected option that is disabled? */ - shouldShowDisabledAndSelectedOption: PropTypes.bool, -}; - -const defaultProps = { - policyTags: {}, - policyRecentlyUsedTags: {}, - shouldShowDisabledAndSelectedOption: false, -}; - -export {propTypes, defaultProps}; diff --git a/src/components/VideoPlayer/BaseVideoPlayer.js b/src/components/VideoPlayer/BaseVideoPlayer.js index 1e9c4711f13a..91737ad3938a 100644 --- a/src/components/VideoPlayer/BaseVideoPlayer.js +++ b/src/components/VideoPlayer/BaseVideoPlayer.js @@ -6,11 +6,12 @@ import _ from 'underscore'; import FullScreenLoadingIndicator from '@components/FullscreenLoadingIndicator'; import Hoverable from '@components/Hoverable'; import PressableWithoutFeedback from '@components/Pressable/PressableWithoutFeedback'; +import {useFullScreenContext} from '@components/VideoPlayerContexts/FullScreenContext'; import {usePlaybackContext} from '@components/VideoPlayerContexts/PlaybackContext'; import VideoPopoverMenu from '@components/VideoPopoverMenu'; +import useNetwork from '@hooks/useNetwork'; import useThemeStyles from '@hooks/useThemeStyles'; import addEncryptedAuthTokenToURL from '@libs/addEncryptedAuthTokenToURL'; -import * as Browser from '@libs/Browser'; import * as DeviceCapabilities from '@libs/DeviceCapabilities'; import CONST from '@src/CONST'; import {videoPlayerDefaultProps, videoPlayerPropTypes} from './propTypes'; @@ -18,8 +19,6 @@ import shouldReplayVideo from './shouldReplayVideo'; import * as VideoUtils from './utils'; import VideoPlayerControls from './VideoPlayerControls'; -const isMobileSafari = Browser.isMobileSafari(); - function BaseVideoPlayer({ url, resizeMode, @@ -43,8 +42,20 @@ function BaseVideoPlayer({ isVideoHovered, }) { const styles = useThemeStyles(); - const {pauseVideo, playVideo, currentlyPlayingURL, updateSharedElements, sharedElement, originalParent, shareVideoPlayerElements, currentVideoPlayerRef, updateCurrentlyPlayingURL} = - usePlaybackContext(); + const { + pauseVideo, + playVideo, + currentlyPlayingURL, + updateSharedElements, + sharedElement, + originalParent, + shareVideoPlayerElements, + currentVideoPlayerRef, + updateCurrentlyPlayingURL, + videoResumeTryNumber, + } = usePlaybackContext(); + const {isFullScreenRef} = useFullScreenContext(); + const {isOffline} = useNetwork(); const [duration, setDuration] = useState(videoDuration * 1000); const [position, setPosition] = useState(0); const [isPlaying, setIsPlaying] = useState(false); @@ -58,24 +69,21 @@ function BaseVideoPlayer({ const videoPlayerElementParentRef = useRef(null); const videoPlayerElementRef = useRef(null); const sharedVideoPlayerParentRef = useRef(null); - const videoResumeTryNumber = useRef(0); const canUseTouchScreen = DeviceCapabilities.canUseTouchScreen(); const isCurrentlyURLSet = currentlyPlayingURL === url; const isUploading = _.some(CONST.ATTACHMENT_LOCAL_URL_PREFIX, (prefix) => url.startsWith(prefix)); - const shouldUseSharedVideoElementRef = useRef(shouldUseSharedVideoElement); - - const [isFullscreen, setIsFullscreen] = useState(false); + const videoStateRef = useRef(null); const togglePlayCurrentVideo = useCallback(() => { videoResumeTryNumber.current = 0; if (!isCurrentlyURLSet) { updateCurrentlyPlayingURL(url); - } else if (isPlaying && !isFullscreen) { + } else if (isPlaying) { pauseVideo(); - } else if (!isFullscreen) { + } else { playVideo(); } - }, [isCurrentlyURLSet, isPlaying, pauseVideo, playVideo, updateCurrentlyPlayingURL, url, isFullscreen]); + }, [isCurrentlyURLSet, isPlaying, pauseVideo, playVideo, updateCurrentlyPlayingURL, url, videoResumeTryNumber]); const showPopoverMenu = (e) => { setPopoverAnchorPosition({horizontal: e.nativeEvent.pageX, vertical: e.nativeEvent.pageY}); @@ -97,7 +105,7 @@ function BaseVideoPlayer({ } videoResumeTryNumber.current -= 1; }, - [playVideo], + [playVideo, videoResumeTryNumber], ); const handlePlaybackStatusUpdate = useCallback( @@ -116,7 +124,7 @@ function BaseVideoPlayer({ setIsBuffering(e.isBuffering || false); setDuration(currentDuration); setPosition(currentPositon); - + videoStateRef.current = e; onPlaybackStatusUpdate(e); }, [onPlaybackStatusUpdate, preventPausingWhenExitingFullscreen, videoDuration], @@ -125,22 +133,20 @@ function BaseVideoPlayer({ const handleFullscreenUpdate = useCallback( (e) => { onFullscreenUpdate(e); - - setIsFullscreen(e.fullscreenUpdate === VideoFullscreenUpdate.PLAYER_DID_PRESENT); - // fix for iOS native and mWeb: when switching to fullscreen and then exiting // the fullscreen mode while playing, the video pauses - if (!isPlaying || e.fullscreenUpdate !== VideoFullscreenUpdate.PLAYER_DID_DISMISS) { - return; + if (e.fullscreenUpdate === VideoFullscreenUpdate.PLAYER_DID_DISMISS) { + isFullScreenRef.current = false; + // we need to use video state ref to check if video is playing, to catch proper state after exiting fullscreen + // and also fix a bug with fullscreen mode dismissing when handleFullscreenUpdate function changes + if (videoStateRef.current && videoStateRef.current.isPlaying) { + pauseVideo(); + playVideo(); + videoResumeTryNumber.current = 3; + } } - - if (isMobileSafari) { - pauseVideo(); - } - playVideo(); - videoResumeTryNumber.current = 3; }, - [isPlaying, onFullscreenUpdate, pauseVideo, playVideo], + [isFullScreenRef, onFullscreenUpdate, pauseVideo, playVideo, videoResumeTryNumber], ); const bindFunctions = useCallback(() => { @@ -154,7 +160,7 @@ function BaseVideoPlayer({ }, [currentVideoPlayerRef, handleFullscreenUpdate, handlePlaybackStatusUpdate]); useEffect(() => { - if (!isUploading) { + if (!isUploading || !videoPlayerRef.current) { return; } @@ -162,37 +168,29 @@ function BaseVideoPlayer({ currentVideoPlayerRef.current = videoPlayerRef.current; }, [url, currentVideoPlayerRef, isUploading]); - useEffect(() => { - shouldUseSharedVideoElementRef.current = shouldUseSharedVideoElement; - }, [shouldUseSharedVideoElement]); - - useEffect( - () => () => { - if (shouldUseSharedVideoElementRef.current) { - return; - } - - // If it's not a shared video player, clear the video player ref. - currentVideoPlayerRef.current = null; - }, - [currentVideoPlayerRef], - ); - // update shared video elements useEffect(() => { - if (shouldUseSharedVideoElement || url !== currentlyPlayingURL) { + if (shouldUseSharedVideoElement || url !== currentlyPlayingURL || isFullScreenRef.current) { return; } shareVideoPlayerElements(videoPlayerRef.current, videoPlayerElementParentRef.current, videoPlayerElementRef.current, isUploading); - }, [currentlyPlayingURL, shouldUseSharedVideoElement, shareVideoPlayerElements, updateSharedElements, url, isUploading]); + }, [currentlyPlayingURL, shouldUseSharedVideoElement, shareVideoPlayerElements, updateSharedElements, url, isUploading, isFullScreenRef]); // append shared video element to new parent (used for example in attachment modal) useEffect(() => { - if (url !== currentlyPlayingURL || !sharedElement || !shouldUseSharedVideoElement) { + if (url !== currentlyPlayingURL || !sharedElement || isFullScreenRef.current) { return; } const newParentRef = sharedVideoPlayerParentRef.current; + + if (!shouldUseSharedVideoElement) { + if (newParentRef && newParentRef.childNodes[0] && newParentRef.childNodes[0].remove) { + newParentRef.childNodes[0].remove(); + } + return; + } + videoPlayerRef.current = currentVideoPlayerRef.current; if (currentlyPlayingURL === url) { newParentRef.appendChild(sharedElement); @@ -202,9 +200,10 @@ function BaseVideoPlayer({ if (!originalParent && !newParentRef.childNodes[0]) { return; } + newParentRef.childNodes[0].remove(); originalParent.appendChild(sharedElement); }; - }, [bindFunctions, currentVideoPlayerRef, currentlyPlayingURL, originalParent, sharedElement, shouldUseSharedVideoElement, url]); + }, [bindFunctions, currentVideoPlayerRef, currentlyPlayingURL, isFullScreenRef, originalParent, sharedElement, shouldUseSharedVideoElement, url]); return ( <> @@ -220,6 +219,9 @@ function BaseVideoPlayer({ { + if (isFullScreenRef.current) { + return; + } togglePlayCurrentVideo(); }} style={styles.flex1} @@ -253,13 +255,20 @@ function BaseVideoPlayer({ style={[styles.w100, styles.h100, videoPlayerStyle]} videoStyle={[styles.w100, styles.h100, videoStyle]} source={{ - uri: sourceURL, + // if video is loading and is offline, we want to change uri to null to + // reset the video player after connection is back + uri: !isLoading || (isLoading && !isOffline) ? sourceURL : null, }} shouldPlay={false} useNativeControls={false} resizeMode={resizeMode} isLooping={isLooping} - onReadyForDisplay={onVideoLoaded} + onReadyForDisplay={(e) => { + if (isCurrentlyURLSet && !isUploading) { + playVideo(); + } + onVideoLoaded(e); + }} onPlaybackStatusUpdate={handlePlaybackStatusUpdate} onFullscreenUpdate={handleFullscreenUpdate} /> diff --git a/src/components/VideoPlayer/VideoPlayerControls/index.tsx b/src/components/VideoPlayer/VideoPlayerControls/index.tsx index 7c61721b67b7..1ac07fd1eaaf 100644 --- a/src/components/VideoPlayer/VideoPlayerControls/index.tsx +++ b/src/components/VideoPlayer/VideoPlayerControls/index.tsx @@ -8,6 +8,7 @@ import * as Expensicons from '@components/Icon/Expensicons'; import Text from '@components/Text'; import IconButton from '@components/VideoPlayer/IconButton'; import {convertMillisecondsToTime} from '@components/VideoPlayer/utils'; +import {useFullScreenContext} from '@components/VideoPlayerContexts/FullScreenContext'; import {usePlaybackContext} from '@components/VideoPlayerContexts/PlaybackContext'; import useLocalize from '@hooks/useLocalize'; import useThemeStyles from '@hooks/useThemeStyles'; @@ -48,6 +49,7 @@ function VideoPlayerControls({duration, position, url, videoPlayerRef, isPlaying const styles = useThemeStyles(); const {translate} = useLocalize(); const {updateCurrentlyPlayingURL} = usePlaybackContext(); + const {isFullScreenRef} = useFullScreenContext(); const [shouldShowTime, setShouldShowTime] = useState(false); const iconSpacing = small ? styles.mr3 : styles.mr4; @@ -56,9 +58,10 @@ function VideoPlayerControls({duration, position, url, videoPlayerRef, isPlaying }; const enterFullScreenMode = useCallback(() => { + isFullScreenRef.current = true; updateCurrentlyPlayingURL(url); videoPlayerRef.current.presentFullscreenPlayer(); - }, [updateCurrentlyPlayingURL, url, videoPlayerRef]); + }, [isFullScreenRef, updateCurrentlyPlayingURL, url, videoPlayerRef]); const seekPosition = useCallback( (newPosition: number) => { diff --git a/src/components/VideoPlayerContexts/FullScreenContext.tsx b/src/components/VideoPlayerContexts/FullScreenContext.tsx new file mode 100644 index 000000000000..8634e27b9d1e --- /dev/null +++ b/src/components/VideoPlayerContexts/FullScreenContext.tsx @@ -0,0 +1,34 @@ +import React, {useCallback, useContext, useMemo, useRef} from 'react'; +import type WindowDimensions from '@hooks/useWindowDimensions/types'; +import type ChildrenProps from '@src/types/utils/ChildrenProps'; +import type {FullScreenContext} from './types'; + +const Context = React.createContext(null); + +function FullScreenContextProvider({children}: ChildrenProps) { + const isFullScreenRef = useRef(false); + const lockedWindowDimensionsRef = useRef(null); + + const lockWindowDimensions = useCallback((newWindowDimensions: WindowDimensions) => { + lockedWindowDimensionsRef.current = newWindowDimensions; + }, []); + + const unlockWindowDimensions = useCallback(() => { + lockedWindowDimensionsRef.current = null; + }, []); + + const contextValue = useMemo(() => ({isFullScreenRef, lockedWindowDimensionsRef, lockWindowDimensions, unlockWindowDimensions}), [lockWindowDimensions, unlockWindowDimensions]); + return {children}; +} + +function useFullScreenContext() { + const fullscreenContext = useContext(Context); + if (!fullscreenContext) { + throw new Error('useFullScreenContext must be used within a FullScreenContextProvider'); + } + return fullscreenContext; +} + +FullScreenContextProvider.displayName = 'FullScreenContextProvider'; + +export {Context as FullScreenContext, FullScreenContextProvider, useFullScreenContext}; diff --git a/src/components/VideoPlayerContexts/PlaybackContext.tsx b/src/components/VideoPlayerContexts/PlaybackContext.tsx index fc07f3d20ea0..71d999da6aec 100644 --- a/src/components/VideoPlayerContexts/PlaybackContext.tsx +++ b/src/components/VideoPlayerContexts/PlaybackContext.tsx @@ -13,6 +13,7 @@ function PlaybackContextProvider({children}: ChildrenProps) { const [originalParent, setOriginalParent] = useState(null); const currentVideoPlayerRef = useRef