webapis-media-query.ts 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. /**
  2. * @license
  3. * Copyright Google Inc. All Rights Reserved.
  4. *
  5. * Use of this source code is governed by an MIT-style license that can be
  6. * found in the LICENSE file at https://angular.io/license
  7. */
  8. Zone.__load_patch('mediaQuery', (global: any, Zone: ZoneType, api: _ZonePrivate) => {
  9. function patchAddListener(proto: any) {
  10. api.patchMethod(proto, 'addListener', (delegate: Function) => (self: any, args: any[]) => {
  11. const callback = args.length > 0 ? args[0] : null;
  12. if (typeof callback === 'function') {
  13. const wrapperedCallback = Zone.current.wrap(callback, 'MediaQuery');
  14. callback[api.symbol('mediaQueryCallback')] = wrapperedCallback;
  15. return delegate.call(self, wrapperedCallback);
  16. } else {
  17. return delegate.apply(self, args);
  18. }
  19. });
  20. }
  21. function patchRemoveListener(proto: any) {
  22. api.patchMethod(proto, 'removeListener', (delegate: Function) => (self: any, args: any[]) => {
  23. const callback = args.length > 0 ? args[0] : null;
  24. if (typeof callback === 'function') {
  25. const wrapperedCallback = callback[api.symbol('mediaQueryCallback')];
  26. if (wrapperedCallback) {
  27. return delegate.call(self, wrapperedCallback);
  28. } else {
  29. return delegate.apply(self, args);
  30. }
  31. } else {
  32. return delegate.apply(self, args);
  33. }
  34. });
  35. }
  36. if (global['MediaQueryList']) {
  37. const proto = global['MediaQueryList'].prototype;
  38. patchAddListener(proto);
  39. patchRemoveListener(proto);
  40. } else if (global['matchMedia']) {
  41. api.patchMethod(global, 'matchMedia', (delegate: Function) => (self: any, args: any[]) => {
  42. const mql = delegate.apply(self, args);
  43. if (mql) {
  44. // try to patch MediaQueryList.prototype
  45. const proto = Object.getPrototypeOf(mql);
  46. if (proto && proto['addListener']) {
  47. // try to patch proto, don't need to worry about patch
  48. // multiple times, because, api.patchEventTarget will check it
  49. patchAddListener(proto);
  50. patchRemoveListener(proto);
  51. patchAddListener(mql);
  52. patchRemoveListener(mql);
  53. } else if (mql['addListener']) {
  54. // proto not exists, or proto has no addListener method
  55. // try to patch mql instance
  56. patchAddListener(mql);
  57. patchRemoveListener(mql);
  58. }
  59. }
  60. return mql;
  61. });
  62. }
  63. });