You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

70 lines
1.9 KiB

4 years ago
  1. import listToStyles from './listToStyles'
  2. export default function addStylesToShadowDOM (parentId, list, shadowRoot) {
  3. var styles = listToStyles(parentId, list)
  4. addStyles(styles, shadowRoot)
  5. }
  6. /*
  7. type StyleObject = {
  8. id: number;
  9. parts: Array<StyleObjectPart>
  10. }
  11. type StyleObjectPart = {
  12. css: string;
  13. media: string;
  14. sourceMap: ?string
  15. }
  16. */
  17. function addStyles (styles /* Array<StyleObject> */, shadowRoot) {
  18. const injectedStyles =
  19. shadowRoot._injectedStyles ||
  20. (shadowRoot._injectedStyles = {})
  21. for (var i = 0; i < styles.length; i++) {
  22. var item = styles[i]
  23. var style = injectedStyles[item.id]
  24. if (!style) {
  25. for (var j = 0; j < item.parts.length; j++) {
  26. addStyle(item.parts[j], shadowRoot)
  27. }
  28. injectedStyles[item.id] = true
  29. }
  30. }
  31. }
  32. function createStyleElement (shadowRoot) {
  33. var styleElement = document.createElement('style')
  34. styleElement.type = 'text/css'
  35. shadowRoot.appendChild(styleElement)
  36. return styleElement
  37. }
  38. function addStyle (obj /* StyleObjectPart */, shadowRoot) {
  39. var styleElement = createStyleElement(shadowRoot)
  40. var css = obj.css
  41. var media = obj.media
  42. var sourceMap = obj.sourceMap
  43. if (media) {
  44. styleElement.setAttribute('media', media)
  45. }
  46. if (sourceMap) {
  47. // https://developer.chrome.com/devtools/docs/javascript-debugging
  48. // this makes source maps inside style tags work properly in Chrome
  49. css += '\n/*# sourceURL=' + sourceMap.sources[0] + ' */'
  50. // http://stackoverflow.com/a/26603875
  51. css += '\n/*# sourceMappingURL=data:application/json;base64,' + btoa(unescape(encodeURIComponent(JSON.stringify(sourceMap)))) + ' */'
  52. }
  53. if (styleElement.styleSheet) {
  54. styleElement.styleSheet.cssText = css
  55. } else {
  56. while (styleElement.firstChild) {
  57. styleElement.removeChild(styleElement.firstChild)
  58. }
  59. styleElement.appendChild(document.createTextNode(css))
  60. }
  61. }