All files / react-native-web/src/exports/StyleSheet compile.js

97.96% Statements 96/98
82.61% Branches 38/46
100% Functions 17/17
97.94% Lines 95/97

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278                                                      21x   213x         31x       182x 152x   182x               78x     213x 213x 213x 213x 213x 31x 31x   182x 182x 182x           182x     213x                 77x 77x   77x 77x   77x 1x 1x 1x   77x 77x   77x               109x                 2219x 2219x                   182x 182x       182x   4x 4x 4x 4x         1x 1x           1x           5x 5x 3x 3x 3x 3x   2x 2x 2x 2x 2x     5x 5x 5x           1x 1x   1x 1x 1x       171x 171x 171x       182x             280x 280x   1170x 1170x         1170x 78x   1152x               280x             266x 266x                 7x 7x     7x     16x 16x 16x         7x 14x   7x             5x       5x 5x 5x   5x 7x         7x 7x 7x       5x    
/**
 * Copyright (c) Nicolas Gallagher.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * @flow strict-local
 */
 
import createReactDOMStyle from './createReactDOMStyle';
import hash from '../../vendor/hash';
import hyphenateStyleName from 'hyphenate-style-name';
import normalizeValueWithProperty from './normalizeValueWithProperty';
import prefixStyles, { prefixInlineStyles } from '../../modules/prefixStyles';
 
type Value = Object | Array<any> | string | number;
type Style = { [key: string]: Value };
type Rule = string;
type Rules = Array<Rule>;
type RulesData = {|
  property?: string,
  value?: string,
  identifier: string,
  rules: Rules
|};
type CompilerOutput = { [key: string]: RulesData };
 
const cache = {
  get(property, value) {
    if (
      cache[property] != null &&
      cache[property].hasOwnProperty(value) &&
      cache[property][value] != null
    ) {
      return cache[property][value];
    }
  },
  set(property, value, object) {
    if (cache[property] == null) {
      cache[property] = {};
    }
    return (cache[property][value] = object);
  }
};
 
/**
 * Compile style to atomic CSS rules.
 */
export function atomic(style: Style): CompilerOutput {
  return Object.keys(style)
    .sort()
    .reduce((acc, property) => {
      const value = style[property];
      Eif (value != null) {
        const valueString = stringifyValueWithProperty(value, property);
        const cachedResult = cache.get(property, valueString);
        if (cachedResult != null) {
          const { identifier } = cachedResult;
          acc[identifier] = cachedResult;
        } else {
          const identifier = createIdentifier('r', property, value);
          const rules = createAtomicRules(identifier, property, value);
          const cachedResult = cache.set(property, valueString, {
            property,
            value: stringifyValueWithProperty(value, property),
            identifier,
            rules
          });
          acc[identifier] = cachedResult;
        }
      }
      return acc;
    }, {});
}
 
/**
 * Compile simple style object to classic CSS rules.
 * No support for 'placeholderTextColor', 'scrollbarWidth', or 'pointerEvents'.
 */
export function classic(style: Style, name: string): CompilerOutput {
  const identifier = createIdentifier('css', name, style);
  const { animationKeyframes, ...rest } = style;
 
  const rules = [];
  const selector = `.${identifier}`;
  let animationName;
  if (animationKeyframes != null) {
    const { animationNames, rules: keyframesRules } = processKeyframesValue(animationKeyframes);
    animationName = animationNames.join(',');
    rules.push(...keyframesRules);
  }
  const block = createDeclarationBlock({ ...rest, animationName });
  rules.push(`${selector}${block}`);
 
  return { [identifier]: { identifier, rules } };
}
 
/**
 * Compile simple style object to inline DOM styles.
 * No support for 'animationKeyframes', 'placeholderTextColor', 'scrollbarWidth', or 'pointerEvents'.
 */
export function inline(style: Style): Object {
  return prefixInlineStyles(createReactDOMStyle(style));
}
 
/**
 * Create a value string that normalizes different input values with a common
 * output.
 */
export function stringifyValueWithProperty(value: Value, property: ?string): string {
  // e.g., 0 => '0px', 'black' => 'rgba(0,0,0,1)'
  const normalizedValue = normalizeValueWithProperty(value, property);
  return typeof normalizedValue !== 'string'
    ? JSON.stringify(normalizedValue || '')
    : normalizedValue;
}
 
/**
 * Create the Atomic CSS rules needed for a given StyleSheet rule.
 * Translates StyleSheet declarations to CSS.
 */
function createAtomicRules(identifier: string, property, value): Rules {
  const rules = [];
  const selector = `.${identifier}`;
 
  // Handle non-standard properties and object values that require multiple
  // CSS rules to be created.
  switch (property) {
    case 'animationKeyframes': {
      const { animationNames, rules: keyframesRules } = processKeyframesValue(value);
      const block = createDeclarationBlock({ animationName: animationNames.join(',') });
      rules.push(`${selector}${block}`, ...keyframesRules);
      break;
    }
 
    // Equivalent to using '::placeholder'
    case 'placeholderTextColor': {
      const block = createDeclarationBlock({ color: value, opacity: 1 });
      rules.push(
        `${selector}::-webkit-input-placeholder${block}`,
        `${selector}::-moz-placeholder${block}`,
        `${selector}:-ms-input-placeholder${block}`,
        `${selector}::placeholder${block}`
      );
      break;
    }
 
    // Polyfill for additional 'pointer-events' values
    // See d13f78622b233a0afc0c7a200c0a0792c8ca9e58
    case 'pointerEvents': {
      let finalValue = value;
      if (value === 'auto' || value === 'box-only') {
        finalValue = 'auto!important';
        Eif (value === 'box-only') {
          const block = createDeclarationBlock({ pointerEvents: 'none' });
          rules.push(`${selector}>*${block}`);
        }
      } else Eif (value === 'none' || value === 'box-none') {
        finalValue = 'none!important';
        Eif (value === 'box-none') {
          const block = createDeclarationBlock({ pointerEvents: 'auto' });
          rules.push(`${selector}>*${block}`);
        }
      }
      const block = createDeclarationBlock({ pointerEvents: finalValue });
      rules.push(`${selector}${block}`);
      break;
    }
 
    // Polyfill for draft spec
    // https://drafts.csswg.org/css-scrollbars-1/
    case 'scrollbarWidth': {
      Eif (value === 'none') {
        rules.push(`${selector}::-webkit-scrollbar{display:none}`);
      }
      const block = createDeclarationBlock({ scrollbarWidth: value });
      rules.push(`${selector}${block}`);
      break;
    }
 
    default: {
      const block = createDeclarationBlock({ [property]: value });
      rules.push(`${selector}${block}`);
      break;
    }
  }
 
  return rules;
}
 
/**
 * Creates a CSS declaration block from a StyleSheet object.
 */
function createDeclarationBlock(style: Style) {
  const domStyle = prefixStyles(createReactDOMStyle(style));
  const declarationsString = Object.keys(domStyle)
    .map((property) => {
      const value = domStyle[property];
      const prop = hyphenateStyleName(property);
      // The prefixer may return an array of values:
      // { display: [ '-webkit-flex', 'flex' ] }
      // to represent "fallback" declarations
      // { display: -webkit-flex; display: flex; }
      if (Array.isArray(value)) {
        return value.map((v) => `${prop}:${v}`).join(';');
      } else {
        return `${prop}:${value}`;
      }
    })
    // Once properties are hyphenated, this will put the vendor
    // prefixed and short-form properties first in the list.
    .sort()
    .join(';');
 
  return `{${declarationsString};}`;
}
 
/**
 * An identifier is associated with a unique set of styles.
 */
function createIdentifier(prefix: string, name: string, value): string {
  const hashedString = hash(name + stringifyValueWithProperty(value, name));
  return process.env.NODE_ENV !== 'production'
    ? `${prefix}-${name}-${hashedString}`
    : `${prefix}-${hashedString}`;
}
 
/**
 * Create individual CSS keyframes rules.
 */
function createKeyframes(keyframes) {
  const prefixes = ['-webkit-', ''];
  const identifier = createIdentifier('r', 'animation', keyframes);
 
  const steps =
    '{' +
    Object.keys(keyframes)
      .map((stepName) => {
        const rule = keyframes[stepName];
        const block = createDeclarationBlock(rule);
        return `${stepName}${block}`;
      })
      .join('') +
    '}';
 
  const rules = prefixes.map((prefix) => {
    return `@${prefix}keyframes ${identifier}${steps}`;
  });
  return { identifier, rules };
}
 
/**
 * Create CSS keyframes rules and names from a StyleSheet keyframes object.
 */
function processKeyframesValue(keyframesValue) {
  Iif (typeof keyframesValue === 'number') {
    throw new Error(`Invalid CSS keyframes type: ${typeof keyframesValue}`);
  }
 
  const animationNames = [];
  const rules = [];
  const value = Array.isArray(keyframesValue) ? keyframesValue : [keyframesValue];
 
  value.forEach((keyframes) => {
    Iif (typeof keyframes === 'string') {
      // Support external animation libraries (identifiers only)
      animationNames.push(keyframes);
    } else {
      // Create rules for each of the keyframes
      const { identifier, rules: keyframesRules } = createKeyframes(keyframes);
      animationNames.push(identifier);
      rules.push(...keyframesRules);
    }
  });
 
  return { animationNames, rules };
}