font-face-proxy.js 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. /* global window, addEventListener, dispatchEvent, CustomEvent, document */
  2. this.fontFaceProxy = this.fontFaceProxy || (() => {
  3. const scriptElement = document.createElement("script");
  4. scriptElement.textContent = `(${hook.toString()})()`;
  5. document.documentElement.appendChild(scriptElement);
  6. const fontFaces = [];
  7. addEventListener("single-file-font-face", event => fontFaces.push(event.detail));
  8. return {
  9. getFontsData: () => fontFaces
  10. };
  11. function hook() {
  12. const FONT_STYLE_PROPERTIES = {
  13. family: "font-family",
  14. style: "font-style",
  15. weight: "font-weight",
  16. stretch: "font-stretch",
  17. unicodeRange: "unicode-range",
  18. variant: "font-variant",
  19. featureSettings: "font-feature-settings"
  20. };
  21. Array.from(document.fonts).forEach(fontFace => document.fonts.delete(fontFace));
  22. const FontFace = window.FontFace;
  23. window.__defineGetter__("FontFace", () => new Proxy(FontFace, {
  24. construct(FontFace, argumentsList) {
  25. const detail = {};
  26. detail["font-family"] = argumentsList[0];
  27. detail.src = argumentsList[1];
  28. const descriptors = argumentsList[2];
  29. if (descriptors) {
  30. Object.keys(descriptors).forEach(descriptor => {
  31. detail[FONT_STYLE_PROPERTIES[descriptor]] = descriptors[descriptor];
  32. });
  33. }
  34. dispatchEvent(new CustomEvent("single-file-font-face", { detail }));
  35. return new FontFace(...argumentsList);
  36. }
  37. }));
  38. }
  39. })();