|
| 1 | +/** |
| 2 | + * Copyright (c) Meta Platforms, Inc. and affiliates. |
| 3 | + * |
| 4 | + * This source code is licensed under the MIT license found in the |
| 5 | + * LICENSE file in the root directory of this source tree. |
| 6 | + * |
| 7 | + * @flow strict-local |
| 8 | + * @format |
| 9 | + */ |
| 10 | + |
| 11 | +/** |
| 12 | + * Splits the variadic `PlatformColor(...)` arguments into the leading color |
| 13 | + * token names and the optional trailing `{fallback}` options object. The |
| 14 | + * per-platform `PlatformColor` implementations differ only in the native object |
| 15 | + * they build from this result, so the argument parsing is shared here. |
| 16 | + */ |
| 17 | +export default function parsePlatformColorArgs( |
| 18 | + args: Array<string | {fallback: string}>, |
| 19 | +): {names: Array<string>, fallback: ?string} { |
| 20 | + const lastArg = args[args.length - 1]; |
| 21 | + if (__DEV__) { |
| 22 | + args.forEach((arg, index) => { |
| 23 | + if (typeof arg !== 'object' || arg == null) { |
| 24 | + return; |
| 25 | + } |
| 26 | + if (index !== args.length - 1) { |
| 27 | + console.error( |
| 28 | + 'PlatformColor: an options object is only honored as the final argument; one in any other position is ignored.', |
| 29 | + ); |
| 30 | + } else if (typeof arg.fallback !== 'string') { |
| 31 | + console.error( |
| 32 | + 'PlatformColor: the trailing options object must be of the form {fallback: string}; it is ignored.', |
| 33 | + ); |
| 34 | + } |
| 35 | + }); |
| 36 | + } |
| 37 | + // The {fallback} options object is only honored as the trailing argument. |
| 38 | + const fallback = |
| 39 | + lastArg != null && |
| 40 | + typeof lastArg === 'object' && |
| 41 | + typeof lastArg.fallback === 'string' |
| 42 | + ? lastArg.fallback |
| 43 | + : null; |
| 44 | + // Collect the leading string tokens; a non-string non-trailing arg (a lint |
| 45 | + // error) is dropped. |
| 46 | + const names: Array<string> = []; |
| 47 | + const nameCount = fallback == null ? args.length : args.length - 1; |
| 48 | + for (let i = 0; i < nameCount; i++) { |
| 49 | + const arg = args[i]; |
| 50 | + if (typeof arg === 'string') { |
| 51 | + names.push(arg); |
| 52 | + } |
| 53 | + } |
| 54 | + return {names, fallback}; |
| 55 | +} |
0 commit comments