|
| 1 | +/** |
| 2 | + * Copyright (c) Nicolas Gallagher. |
| 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 |
| 8 | + */ |
| 9 | + |
| 10 | +const cache = new WeakMap(); |
| 11 | +const markerProp = '$$css$localize'; |
| 12 | + |
| 13 | +/** |
| 14 | + * The compiler polyfills logical properties and values, generating a class |
| 15 | + * name for both writing directions. The style objects are annotated by |
| 16 | + * the compiler as needing this runtime transform. The results are memoized. |
| 17 | + * |
| 18 | + * { '$$css$localize': true, float: [ 'float-left', 'float-right' ] } |
| 19 | + * => { float: 'float-left' } |
| 20 | + */ |
| 21 | + |
| 22 | +function compileStyle(style, isRTL) { |
| 23 | + // Create a new compiled style for styleq |
| 24 | + const compiledStyle = {}; |
| 25 | + for (const prop in style) { |
| 26 | + if (prop !== markerProp) { |
| 27 | + const value = style[prop]; |
| 28 | + if (Array.isArray(value)) { |
| 29 | + compiledStyle[prop] = isRTL ? value[1] : value[0]; |
| 30 | + } else { |
| 31 | + compiledStyle[prop] = value; |
| 32 | + } |
| 33 | + } |
| 34 | + } |
| 35 | + return compiledStyle; |
| 36 | +} |
| 37 | + |
| 38 | +export function localizeStyle(style, isRTL) { |
| 39 | + if (style[markerProp] != null) { |
| 40 | + const compiledStyleIndex = isRTL ? 1 : 0; |
| 41 | + // Check the cache in case we've already seen this object |
| 42 | + if (cache.has(style)) { |
| 43 | + const cachedStyles = cache.get(style); |
| 44 | + let compiledStyle = cachedStyles[compiledStyleIndex]; |
| 45 | + if (compiledStyle == null) { |
| 46 | + // Update the missing cache entry |
| 47 | + compiledStyle = compileStyle(style, isRTL); |
| 48 | + cachedStyles[compiledStyleIndex] = compiledStyle; |
| 49 | + cache.set(style, cachedStyles); |
| 50 | + } |
| 51 | + return compiledStyle; |
| 52 | + } |
| 53 | + |
| 54 | + // Create a new compiled style for styleq |
| 55 | + const compiledStyle = compileStyle(style, isRTL); |
| 56 | + const cachedStyles = new Array(2); |
| 57 | + cachedStyles[compiledStyleIndex] = compiledStyle; |
| 58 | + cache.set(style, cachedStyles); |
| 59 | + return compiledStyle; |
| 60 | + } |
| 61 | + return style; |
| 62 | +} |
0 commit comments