| 4 | const THEME_EXTENSION_SCOPE = 'shoutem.theme'; |
| 5 | |
| 6 | export class ThemeVariableResolver { |
| 7 | constructor(variables) { |
| 8 | this.variables = { ...variables }; |
| 9 | |
| 10 | autoBind(this); |
| 11 | } |
| 12 | |
| 13 | setVariables(variables) { |
| 14 | this.variables = { ...variables }; |
| 15 | } |
| 16 | |
| 17 | getScopedVariable(scope, variable) { |
| 18 | if (!this.variables || _.isEmpty(this.variables)) { |
| 19 | throw new Error( |
| 20 | 'Theme variable resolver not yet initialised. Please call `setVariables` prior to this function call', |
| 21 | ); |
| 22 | } |
| 23 | |
| 24 | const scopePath = _.split(scope, '.'); |
| 25 | const variablePath = _.split(variable, '.'); |
| 26 | |
| 27 | return _.get( |
| 28 | this.variables, |
| 29 | [...scopePath, ...variablePath], |
| 30 | _.get(this.variables, variablePath) |
| 31 | ); |
| 32 | } |
| 33 | |
| 34 | // Currently supports 2 function signatures |
| 35 | // resolveVariable(variableName) -> Tries to get the variable under the root scope ( generic theme values ) |
| 36 | // resolveVariable(scope, variableName) -> Tries to get the variable under specific scope |
| 37 | // Variable name can be stringified object path or a regular string, i.e -> text.color |
| 38 | resolveVariable(...params) { |
| 39 | if (arguments.length === 1) { |
| 40 | const variablePath = _.split(params[0], '.'); |
| 41 | |
| 42 | return _.get(this.variables, variablePath); |
| 43 | } |
| 44 | |
| 45 | if (arguments.length === 2) { |
| 46 | return this.getScopedVariable(params[0], params[1]); |
| 47 | } |
| 48 | |
| 49 | throw new Error( |
| 50 | "Invalid theme variable resolution call. Please use full signature \n-> resolveVariable(scope, variableName),\n or the shorthand if you're getting a variable from shoutem.theme extension \n->resolveVariable(variableName)", |
| 51 | ); |
| 52 | } |
| 53 | |
| 54 | createScopedResolver(scope) { |
| 55 | return (...params) => { |
| 56 | if (params.length === 1) { |
| 57 | return this.getScopedVariable(scope, params[0]); |
| 58 | } |
| 59 | if (params.length === 2) { |
| 60 | return this.getScopedVariable(params[0], params[1]); |
| 61 | } |
| 62 | |
| 63 | return undefined; |
nothing calls this directly
no outgoing calls
no test coverage detected