style_builders.mjs 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. /**
  2. * @license
  3. * SPDX-License-Identifier: Apache-2.0
  4. */
  5. import '../environment/dev';
  6. import { assertIsTemplateObject } from '../internals/string_literal';
  7. import { createStyle, unwrapStyle } from '../internals/style_impl';
  8. /**
  9. * Creates a SafeStyle object from a template literal (without any embedded
  10. * expressions).
  11. *
  12. * ` style` should be in the format
  13. * ` name: value; [name: value; ...]` and must not have any < or >
  14. * characters in it. This is so that SafeStyle's contract is preserved,
  15. * allowing the SafeStyle to correctly be interpreted as a sequence of CSS
  16. * declarations and without affecting the syntactic structure of any
  17. * surrounding CSS and HTML.
  18. *
  19. * This function is a template literal tag function. It should be called with
  20. * a template literal that does not contain any expressions. For example,
  21. * safeStyle`foo`;
  22. * This function first checks if it is called with a literal template, and
  23. * then performs basic sanity checks on the format of ` style`
  24. * but does not constrain the format of ` name} and {@code value`, except
  25. * for disallowing tag characters.
  26. *
  27. * @param templateObj This contains the literal part of the template literal.
  28. */
  29. export function safeStyle(templateObj) {
  30. if (process.env.NODE_ENV !== 'production') {
  31. assertIsTemplateObject(templateObj, false, 'safeStyle is a template literal tag function ' +
  32. 'that only accepts template literals without expressions. ' +
  33. 'For example, safeStyle`foo`;');
  34. }
  35. const style = templateObj[0];
  36. if (process.env.NODE_ENV !== 'production') {
  37. if (/[<>]/.test(style)) {
  38. throw new Error('Forbidden characters in style string: ' + style);
  39. }
  40. if (!/;$/.test(style)) {
  41. throw new Error('Style string does not end with ";": ' + style);
  42. }
  43. if (!/:/.test(style)) {
  44. throw new Error('Style string should contain one or more ":": ' + style);
  45. }
  46. }
  47. return createStyle(style);
  48. }
  49. /** Creates a `SafeStyle` value by concatenating multiple `SafeStyle`s. */
  50. export function concatStyles(styles) {
  51. return createStyle(styles.map(unwrapStyle).join(''));
  52. }