UI for Zipcoin Blue

utils.ts 15KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455
  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. /**
  9. * Suppress closure compiler errors about unknown 'Zone' variable
  10. * @fileoverview
  11. * @suppress {undefinedVars,globalThis,missingRequire}
  12. */
  13. // issue #989, to reduce bundle size, use short name
  14. /** Object.getOwnPropertyDescriptor */
  15. export const ObjectGetOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
  16. /** Object.defineProperty */
  17. export const ObjectDefineProperty = Object.defineProperty;
  18. /** Object.getPrototypeOf */
  19. export const ObjectGetPrototypeOf = Object.getPrototypeOf;
  20. /** Object.create */
  21. export const ObjectCreate = Object.create;
  22. /** Array.prototype.slice */
  23. export const ArraySlice = Array.prototype.slice;
  24. /** addEventListener string const */
  25. export const ADD_EVENT_LISTENER_STR = 'addEventListener';
  26. /** removeEventListener string const */
  27. export const REMOVE_EVENT_LISTENER_STR = 'removeEventListener';
  28. /** zoneSymbol addEventListener */
  29. export const ZONE_SYMBOL_ADD_EVENT_LISTENER = Zone.__symbol__(ADD_EVENT_LISTENER_STR);
  30. /** zoneSymbol removeEventListener */
  31. export const ZONE_SYMBOL_REMOVE_EVENT_LISTENER = Zone.__symbol__(REMOVE_EVENT_LISTENER_STR);
  32. /** true string const */
  33. export const TRUE_STR = 'true';
  34. /** false string const */
  35. export const FALSE_STR = 'false';
  36. /** __zone_symbol__ string const */
  37. export const ZONE_SYMBOL_PREFIX = '__zone_symbol__';
  38. export function wrapWithCurrentZone<T extends Function>(callback: T, source: string): T {
  39. return Zone.current.wrap(callback, source);
  40. }
  41. export function scheduleMacroTaskWithCurrentZone(
  42. source: string, callback: Function, data: TaskData, customSchedule: (task: Task) => void,
  43. customCancel: (task: Task) => void): MacroTask {
  44. return Zone.current.scheduleMacroTask(source, callback, data, customSchedule, customCancel);
  45. }
  46. // Hack since TypeScript isn't compiling this for a worker.
  47. declare const WorkerGlobalScope: any;
  48. export const zoneSymbol = Zone.__symbol__;
  49. const isWindowExists = typeof window !== 'undefined';
  50. const internalWindow: any = isWindowExists ? window : undefined;
  51. const _global: any = isWindowExists && internalWindow || typeof self === 'object' && self || global;
  52. const REMOVE_ATTRIBUTE = 'removeAttribute';
  53. const NULL_ON_PROP_VALUE: any[] = [null];
  54. export function bindArguments(args: any[], source: string): any[] {
  55. for (let i = args.length - 1; i >= 0; i--) {
  56. if (typeof args[i] === 'function') {
  57. args[i] = wrapWithCurrentZone(args[i], source + '_' + i);
  58. }
  59. }
  60. return args;
  61. }
  62. export function patchPrototype(prototype: any, fnNames: string[]) {
  63. const source = prototype.constructor['name'];
  64. for (let i = 0; i < fnNames.length; i++) {
  65. const name = fnNames[i];
  66. const delegate = prototype[name];
  67. if (delegate) {
  68. const prototypeDesc = ObjectGetOwnPropertyDescriptor(prototype, name);
  69. if (!isPropertyWritable(prototypeDesc)) {
  70. continue;
  71. }
  72. prototype[name] = ((delegate: Function) => {
  73. const patched: any = function() {
  74. return delegate.apply(this, bindArguments(<any>arguments, source + '.' + name));
  75. };
  76. attachOriginToPatched(patched, delegate);
  77. return patched;
  78. })(delegate);
  79. }
  80. }
  81. }
  82. export function isPropertyWritable(propertyDesc: any) {
  83. if (!propertyDesc) {
  84. return true;
  85. }
  86. if (propertyDesc.writable === false) {
  87. return false;
  88. }
  89. return !(typeof propertyDesc.get === 'function' && typeof propertyDesc.set === 'undefined');
  90. }
  91. export const isWebWorker: boolean =
  92. (typeof WorkerGlobalScope !== 'undefined' && self instanceof WorkerGlobalScope);
  93. // Make sure to access `process` through `_global` so that WebPack does not accidentally browserify
  94. // this code.
  95. export const isNode: boolean =
  96. (!('nw' in _global) && typeof _global.process !== 'undefined' &&
  97. {}.toString.call(_global.process) === '[object process]');
  98. export const isBrowser: boolean =
  99. !isNode && !isWebWorker && !!(isWindowExists && internalWindow['HTMLElement']);
  100. // we are in electron of nw, so we are both browser and nodejs
  101. // Make sure to access `process` through `_global` so that WebPack does not accidentally browserify
  102. // this code.
  103. export const isMix: boolean = typeof _global.process !== 'undefined' &&
  104. {}.toString.call(_global.process) === '[object process]' && !isWebWorker &&
  105. !!(isWindowExists && internalWindow['HTMLElement']);
  106. const zoneSymbolEventNames: {[eventName: string]: string} = {};
  107. const wrapFn = function(event: Event) {
  108. // https://github.com/angular/zone.js/issues/911, in IE, sometimes
  109. // event will be undefined, so we need to use window.event
  110. event = event || _global.event;
  111. if (!event) {
  112. return;
  113. }
  114. let eventNameSymbol = zoneSymbolEventNames[event.type];
  115. if (!eventNameSymbol) {
  116. eventNameSymbol = zoneSymbolEventNames[event.type] = zoneSymbol('ON_PROPERTY' + event.type);
  117. }
  118. const target = this || event.target || _global;
  119. const listener = target[eventNameSymbol];
  120. let result = listener && listener.apply(this, arguments);
  121. if (result != undefined && !result) {
  122. event.preventDefault();
  123. }
  124. return result;
  125. };
  126. export function patchProperty(obj: any, prop: string, prototype?: any) {
  127. let desc = ObjectGetOwnPropertyDescriptor(obj, prop);
  128. if (!desc && prototype) {
  129. // when patch window object, use prototype to check prop exist or not
  130. const prototypeDesc = ObjectGetOwnPropertyDescriptor(prototype, prop);
  131. if (prototypeDesc) {
  132. desc = {enumerable: true, configurable: true};
  133. }
  134. }
  135. // if the descriptor not exists or is not configurable
  136. // just return
  137. if (!desc || !desc.configurable) {
  138. return;
  139. }
  140. // A property descriptor cannot have getter/setter and be writable
  141. // deleting the writable and value properties avoids this error:
  142. //
  143. // TypeError: property descriptors must not specify a value or be writable when a
  144. // getter or setter has been specified
  145. delete desc.writable;
  146. delete desc.value;
  147. const originalDescGet = desc.get;
  148. const originalDescSet = desc.set;
  149. // substr(2) cuz 'onclick' -> 'click', etc
  150. const eventName = prop.substr(2);
  151. let eventNameSymbol = zoneSymbolEventNames[eventName];
  152. if (!eventNameSymbol) {
  153. eventNameSymbol = zoneSymbolEventNames[eventName] = zoneSymbol('ON_PROPERTY' + eventName);
  154. }
  155. desc.set = function(newValue) {
  156. // in some of windows's onproperty callback, this is undefined
  157. // so we need to check it
  158. let target = this;
  159. if (!target && obj === _global) {
  160. target = _global;
  161. }
  162. if (!target) {
  163. return;
  164. }
  165. let previousValue = target[eventNameSymbol];
  166. if (previousValue) {
  167. target.removeEventListener(eventName, wrapFn);
  168. }
  169. // issue #978, when onload handler was added before loading zone.js
  170. // we should remove it with originalDescSet
  171. if (originalDescSet) {
  172. originalDescSet.apply(target, NULL_ON_PROP_VALUE);
  173. }
  174. if (typeof newValue === 'function') {
  175. target[eventNameSymbol] = newValue;
  176. target.addEventListener(eventName, wrapFn, false);
  177. } else {
  178. target[eventNameSymbol] = null;
  179. }
  180. };
  181. // The getter would return undefined for unassigned properties but the default value of an
  182. // unassigned property is null
  183. desc.get = function() {
  184. // in some of windows's onproperty callback, this is undefined
  185. // so we need to check it
  186. let target = this;
  187. if (!target && obj === _global) {
  188. target = _global;
  189. }
  190. if (!target) {
  191. return null;
  192. }
  193. const listener = target[eventNameSymbol];
  194. if (listener) {
  195. return listener;
  196. } else if (originalDescGet) {
  197. // result will be null when use inline event attribute,
  198. // such as <button onclick="func();">OK</button>
  199. // because the onclick function is internal raw uncompiled handler
  200. // the onclick will be evaluated when first time event was triggered or
  201. // the property is accessed, https://github.com/angular/zone.js/issues/525
  202. // so we should use original native get to retrieve the handler
  203. let value = originalDescGet && originalDescGet.call(this);
  204. if (value) {
  205. desc.set.call(this, value);
  206. if (typeof target[REMOVE_ATTRIBUTE] === 'function') {
  207. target.removeAttribute(prop);
  208. }
  209. return value;
  210. }
  211. }
  212. return null;
  213. };
  214. ObjectDefineProperty(obj, prop, desc);
  215. }
  216. export function patchOnProperties(obj: any, properties: string[], prototype?: any) {
  217. if (properties) {
  218. for (let i = 0; i < properties.length; i++) {
  219. patchProperty(obj, 'on' + properties[i], prototype);
  220. }
  221. } else {
  222. const onProperties = [];
  223. for (const prop in obj) {
  224. if (prop.substr(0, 2) == 'on') {
  225. onProperties.push(prop);
  226. }
  227. }
  228. for (let j = 0; j < onProperties.length; j++) {
  229. patchProperty(obj, onProperties[j], prototype);
  230. }
  231. }
  232. }
  233. const originalInstanceKey = zoneSymbol('originalInstance');
  234. // wrap some native API on `window`
  235. export function patchClass(className: string) {
  236. const OriginalClass = _global[className];
  237. if (!OriginalClass) return;
  238. // keep original class in global
  239. _global[zoneSymbol(className)] = OriginalClass;
  240. _global[className] = function() {
  241. const a = bindArguments(<any>arguments, className);
  242. switch (a.length) {
  243. case 0:
  244. this[originalInstanceKey] = new OriginalClass();
  245. break;
  246. case 1:
  247. this[originalInstanceKey] = new OriginalClass(a[0]);
  248. break;
  249. case 2:
  250. this[originalInstanceKey] = new OriginalClass(a[0], a[1]);
  251. break;
  252. case 3:
  253. this[originalInstanceKey] = new OriginalClass(a[0], a[1], a[2]);
  254. break;
  255. case 4:
  256. this[originalInstanceKey] = new OriginalClass(a[0], a[1], a[2], a[3]);
  257. break;
  258. default:
  259. throw new Error('Arg list too long.');
  260. }
  261. };
  262. // attach original delegate to patched function
  263. attachOriginToPatched(_global[className], OriginalClass);
  264. const instance = new OriginalClass(function() {});
  265. let prop;
  266. for (prop in instance) {
  267. // https://bugs.webkit.org/show_bug.cgi?id=44721
  268. if (className === 'XMLHttpRequest' && prop === 'responseBlob') continue;
  269. (function(prop) {
  270. if (typeof instance[prop] === 'function') {
  271. _global[className].prototype[prop] = function() {
  272. return this[originalInstanceKey][prop].apply(this[originalInstanceKey], arguments);
  273. };
  274. } else {
  275. ObjectDefineProperty(_global[className].prototype, prop, {
  276. set: function(fn) {
  277. if (typeof fn === 'function') {
  278. this[originalInstanceKey][prop] = wrapWithCurrentZone(fn, className + '.' + prop);
  279. // keep callback in wrapped function so we can
  280. // use it in Function.prototype.toString to return
  281. // the native one.
  282. attachOriginToPatched(this[originalInstanceKey][prop], fn);
  283. } else {
  284. this[originalInstanceKey][prop] = fn;
  285. }
  286. },
  287. get: function() {
  288. return this[originalInstanceKey][prop];
  289. }
  290. });
  291. }
  292. }(prop));
  293. }
  294. for (prop in OriginalClass) {
  295. if (prop !== 'prototype' && OriginalClass.hasOwnProperty(prop)) {
  296. _global[className][prop] = OriginalClass[prop];
  297. }
  298. }
  299. }
  300. export function patchMethod(
  301. target: any, name: string,
  302. patchFn: (delegate: Function, delegateName: string, name: string) => (self: any, args: any[]) =>
  303. any): Function {
  304. let proto = target;
  305. while (proto && !proto.hasOwnProperty(name)) {
  306. proto = ObjectGetPrototypeOf(proto);
  307. }
  308. if (!proto && target[name]) {
  309. // somehow we did not find it, but we can see it. This happens on IE for Window properties.
  310. proto = target;
  311. }
  312. const delegateName = zoneSymbol(name);
  313. let delegate: Function;
  314. if (proto && !(delegate = proto[delegateName])) {
  315. delegate = proto[delegateName] = proto[name];
  316. // check whether proto[name] is writable
  317. // some property is readonly in safari, such as HtmlCanvasElement.prototype.toBlob
  318. const desc = proto && ObjectGetOwnPropertyDescriptor(proto, name);
  319. if (isPropertyWritable(desc)) {
  320. const patchDelegate = patchFn(delegate, delegateName, name);
  321. proto[name] = function() {
  322. return patchDelegate(this, arguments as any);
  323. };
  324. attachOriginToPatched(proto[name], delegate);
  325. }
  326. }
  327. return delegate;
  328. }
  329. export interface MacroTaskMeta extends TaskData {
  330. name: string;
  331. target: any;
  332. cbIdx: number;
  333. args: any[];
  334. }
  335. // TODO: @JiaLiPassion, support cancel task later if necessary
  336. export function patchMacroTask(
  337. obj: any, funcName: string, metaCreator: (self: any, args: any[]) => MacroTaskMeta) {
  338. let setNative: Function = null;
  339. function scheduleTask(task: Task) {
  340. const data = <MacroTaskMeta>task.data;
  341. data.args[data.cbIdx] = function() {
  342. task.invoke.apply(this, arguments);
  343. };
  344. setNative.apply(data.target, data.args);
  345. return task;
  346. }
  347. setNative = patchMethod(obj, funcName, (delegate: Function) => function(self: any, args: any[]) {
  348. const meta = metaCreator(self, args);
  349. if (meta.cbIdx >= 0 && typeof args[meta.cbIdx] === 'function') {
  350. return scheduleMacroTaskWithCurrentZone(
  351. meta.name, args[meta.cbIdx], meta, scheduleTask, null);
  352. } else {
  353. // cause an error by calling it directly.
  354. return delegate.apply(self, args);
  355. }
  356. });
  357. }
  358. export interface MicroTaskMeta extends TaskData {
  359. name: string;
  360. target: any;
  361. cbIdx: number;
  362. args: any[];
  363. }
  364. export function patchMicroTask(
  365. obj: any, funcName: string, metaCreator: (self: any, args: any[]) => MicroTaskMeta) {
  366. let setNative: Function = null;
  367. function scheduleTask(task: Task) {
  368. const data = <MacroTaskMeta>task.data;
  369. data.args[data.cbIdx] = function() {
  370. task.invoke.apply(this, arguments);
  371. };
  372. setNative.apply(data.target, data.args);
  373. return task;
  374. }
  375. setNative = patchMethod(obj, funcName, (delegate: Function) => function(self: any, args: any[]) {
  376. const meta = metaCreator(self, args);
  377. if (meta.cbIdx >= 0 && typeof args[meta.cbIdx] === 'function') {
  378. return Zone.current.scheduleMicroTask(meta.name, args[meta.cbIdx], meta, scheduleTask);
  379. } else {
  380. // cause an error by calling it directly.
  381. return delegate.apply(self, args);
  382. }
  383. });
  384. }
  385. export function attachOriginToPatched(patched: Function, original: any) {
  386. (patched as any)[zoneSymbol('OriginalDelegate')] = original;
  387. }
  388. let isDetectedIEOrEdge = false;
  389. let ieOrEdge = false;
  390. export function isIEOrEdge() {
  391. if (isDetectedIEOrEdge) {
  392. return ieOrEdge;
  393. }
  394. isDetectedIEOrEdge = true;
  395. try {
  396. const ua = internalWindow.navigator.userAgent;
  397. if (ua.indexOf('MSIE ') !== -1 || ua.indexOf('Trident/') !== -1 || ua.indexOf('Edge/') !== -1) {
  398. ieOrEdge = true;
  399. }
  400. return ieOrEdge;
  401. } catch (error) {
  402. }
  403. }