dom.js 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995
  1. /*---------------------------------------------------------------------------------------------
  2. * Copyright (c) Microsoft Corporation. All rights reserved.
  3. * Licensed under the MIT License. See License.txt in the project root for license information.
  4. *--------------------------------------------------------------------------------------------*/
  5. import * as browser from './browser.js';
  6. import { BrowserFeatures } from './canIUse.js';
  7. import { StandardKeyboardEvent } from './keyboardEvent.js';
  8. import { StandardMouseEvent } from './mouseEvent.js';
  9. import { TimeoutTimer } from '../common/async.js';
  10. import { onUnexpectedError } from '../common/errors.js';
  11. import { Emitter } from '../common/event.js';
  12. import { Disposable, DisposableStore, toDisposable } from '../common/lifecycle.js';
  13. import { FileAccess, RemoteAuthorities } from '../common/network.js';
  14. import * as platform from '../common/platform.js';
  15. export function clearNode(node) {
  16. while (node.firstChild) {
  17. node.firstChild.remove();
  18. }
  19. }
  20. /**
  21. * @deprecated Use node.isConnected directly
  22. */
  23. export function isInDOM(node) {
  24. var _a;
  25. return (_a = node === null || node === void 0 ? void 0 : node.isConnected) !== null && _a !== void 0 ? _a : false;
  26. }
  27. class DomListener {
  28. constructor(node, type, handler, options) {
  29. this._node = node;
  30. this._type = type;
  31. this._handler = handler;
  32. this._options = (options || false);
  33. this._node.addEventListener(this._type, this._handler, this._options);
  34. }
  35. dispose() {
  36. if (!this._handler) {
  37. // Already disposed
  38. return;
  39. }
  40. this._node.removeEventListener(this._type, this._handler, this._options);
  41. // Prevent leakers from holding on to the dom or handler func
  42. this._node = null;
  43. this._handler = null;
  44. }
  45. }
  46. export function addDisposableListener(node, type, handler, useCaptureOrOptions) {
  47. return new DomListener(node, type, handler, useCaptureOrOptions);
  48. }
  49. function _wrapAsStandardMouseEvent(handler) {
  50. return function (e) {
  51. return handler(new StandardMouseEvent(e));
  52. };
  53. }
  54. function _wrapAsStandardKeyboardEvent(handler) {
  55. return function (e) {
  56. return handler(new StandardKeyboardEvent(e));
  57. };
  58. }
  59. export let addStandardDisposableListener = function addStandardDisposableListener(node, type, handler, useCapture) {
  60. let wrapHandler = handler;
  61. if (type === 'click' || type === 'mousedown') {
  62. wrapHandler = _wrapAsStandardMouseEvent(handler);
  63. }
  64. else if (type === 'keydown' || type === 'keypress' || type === 'keyup') {
  65. wrapHandler = _wrapAsStandardKeyboardEvent(handler);
  66. }
  67. return addDisposableListener(node, type, wrapHandler, useCapture);
  68. };
  69. export let addStandardDisposableGenericMouseDownListner = function addStandardDisposableListener(node, handler, useCapture) {
  70. let wrapHandler = _wrapAsStandardMouseEvent(handler);
  71. return addDisposableGenericMouseDownListner(node, wrapHandler, useCapture);
  72. };
  73. export let addStandardDisposableGenericMouseUpListner = function addStandardDisposableListener(node, handler, useCapture) {
  74. let wrapHandler = _wrapAsStandardMouseEvent(handler);
  75. return addDisposableGenericMouseUpListner(node, wrapHandler, useCapture);
  76. };
  77. export function addDisposableGenericMouseDownListner(node, handler, useCapture) {
  78. return addDisposableListener(node, platform.isIOS && BrowserFeatures.pointerEvents ? EventType.POINTER_DOWN : EventType.MOUSE_DOWN, handler, useCapture);
  79. }
  80. export function addDisposableGenericMouseUpListner(node, handler, useCapture) {
  81. return addDisposableListener(node, platform.isIOS && BrowserFeatures.pointerEvents ? EventType.POINTER_UP : EventType.MOUSE_UP, handler, useCapture);
  82. }
  83. export function addDisposableNonBubblingMouseOutListener(node, handler) {
  84. return addDisposableListener(node, 'mouseout', (e) => {
  85. // Mouse out bubbles, so this is an attempt to ignore faux mouse outs coming from children elements
  86. let toElement = (e.relatedTarget);
  87. while (toElement && toElement !== node) {
  88. toElement = toElement.parentNode;
  89. }
  90. if (toElement === node) {
  91. return;
  92. }
  93. handler(e);
  94. });
  95. }
  96. export function addDisposableNonBubblingPointerOutListener(node, handler) {
  97. return addDisposableListener(node, 'pointerout', (e) => {
  98. // Mouse out bubbles, so this is an attempt to ignore faux mouse outs coming from children elements
  99. let toElement = (e.relatedTarget);
  100. while (toElement && toElement !== node) {
  101. toElement = toElement.parentNode;
  102. }
  103. if (toElement === node) {
  104. return;
  105. }
  106. handler(e);
  107. });
  108. }
  109. export function createEventEmitter(target, type, options) {
  110. let domListener = null;
  111. const handler = (e) => result.fire(e);
  112. const onFirstListenerAdd = () => {
  113. if (!domListener) {
  114. domListener = new DomListener(target, type, handler, options);
  115. }
  116. };
  117. const onLastListenerRemove = () => {
  118. if (domListener) {
  119. domListener.dispose();
  120. domListener = null;
  121. }
  122. };
  123. const result = new Emitter({ onFirstListenerAdd, onLastListenerRemove });
  124. return result;
  125. }
  126. let _animationFrame = null;
  127. function doRequestAnimationFrame(callback) {
  128. if (!_animationFrame) {
  129. const emulatedRequestAnimationFrame = (callback) => {
  130. return setTimeout(() => callback(new Date().getTime()), 0);
  131. };
  132. _animationFrame = (self.requestAnimationFrame
  133. || self.msRequestAnimationFrame
  134. || self.webkitRequestAnimationFrame
  135. || self.mozRequestAnimationFrame
  136. || self.oRequestAnimationFrame
  137. || emulatedRequestAnimationFrame);
  138. }
  139. return _animationFrame.call(self, callback);
  140. }
  141. /**
  142. * Schedule a callback to be run at the next animation frame.
  143. * This allows multiple parties to register callbacks that should run at the next animation frame.
  144. * If currently in an animation frame, `runner` will be executed immediately.
  145. * @return token that can be used to cancel the scheduled runner (only if `runner` was not executed immediately).
  146. */
  147. export let runAtThisOrScheduleAtNextAnimationFrame;
  148. /**
  149. * Schedule a callback to be run at the next animation frame.
  150. * This allows multiple parties to register callbacks that should run at the next animation frame.
  151. * If currently in an animation frame, `runner` will be executed at the next animation frame.
  152. * @return token that can be used to cancel the scheduled runner.
  153. */
  154. export let scheduleAtNextAnimationFrame;
  155. class AnimationFrameQueueItem {
  156. constructor(runner, priority = 0) {
  157. this._runner = runner;
  158. this.priority = priority;
  159. this._canceled = false;
  160. }
  161. dispose() {
  162. this._canceled = true;
  163. }
  164. execute() {
  165. if (this._canceled) {
  166. return;
  167. }
  168. try {
  169. this._runner();
  170. }
  171. catch (e) {
  172. onUnexpectedError(e);
  173. }
  174. }
  175. // Sort by priority (largest to lowest)
  176. static sort(a, b) {
  177. return b.priority - a.priority;
  178. }
  179. }
  180. (function () {
  181. /**
  182. * The runners scheduled at the next animation frame
  183. */
  184. let NEXT_QUEUE = [];
  185. /**
  186. * The runners scheduled at the current animation frame
  187. */
  188. let CURRENT_QUEUE = null;
  189. /**
  190. * A flag to keep track if the native requestAnimationFrame was already called
  191. */
  192. let animFrameRequested = false;
  193. /**
  194. * A flag to indicate if currently handling a native requestAnimationFrame callback
  195. */
  196. let inAnimationFrameRunner = false;
  197. let animationFrameRunner = () => {
  198. animFrameRequested = false;
  199. CURRENT_QUEUE = NEXT_QUEUE;
  200. NEXT_QUEUE = [];
  201. inAnimationFrameRunner = true;
  202. while (CURRENT_QUEUE.length > 0) {
  203. CURRENT_QUEUE.sort(AnimationFrameQueueItem.sort);
  204. let top = CURRENT_QUEUE.shift();
  205. top.execute();
  206. }
  207. inAnimationFrameRunner = false;
  208. };
  209. scheduleAtNextAnimationFrame = (runner, priority = 0) => {
  210. let item = new AnimationFrameQueueItem(runner, priority);
  211. NEXT_QUEUE.push(item);
  212. if (!animFrameRequested) {
  213. animFrameRequested = true;
  214. doRequestAnimationFrame(animationFrameRunner);
  215. }
  216. return item;
  217. };
  218. runAtThisOrScheduleAtNextAnimationFrame = (runner, priority) => {
  219. if (inAnimationFrameRunner) {
  220. let item = new AnimationFrameQueueItem(runner, priority);
  221. CURRENT_QUEUE.push(item);
  222. return item;
  223. }
  224. else {
  225. return scheduleAtNextAnimationFrame(runner, priority);
  226. }
  227. };
  228. })();
  229. const MINIMUM_TIME_MS = 8;
  230. const DEFAULT_EVENT_MERGER = function (lastEvent, currentEvent) {
  231. return currentEvent;
  232. };
  233. class TimeoutThrottledDomListener extends Disposable {
  234. constructor(node, type, handler, eventMerger = DEFAULT_EVENT_MERGER, minimumTimeMs = MINIMUM_TIME_MS) {
  235. super();
  236. let lastEvent = null;
  237. let lastHandlerTime = 0;
  238. let timeout = this._register(new TimeoutTimer());
  239. let invokeHandler = () => {
  240. lastHandlerTime = (new Date()).getTime();
  241. handler(lastEvent);
  242. lastEvent = null;
  243. };
  244. this._register(addDisposableListener(node, type, (e) => {
  245. lastEvent = eventMerger(lastEvent, e);
  246. let elapsedTime = (new Date()).getTime() - lastHandlerTime;
  247. if (elapsedTime >= minimumTimeMs) {
  248. timeout.cancel();
  249. invokeHandler();
  250. }
  251. else {
  252. timeout.setIfNotSet(invokeHandler, minimumTimeMs - elapsedTime);
  253. }
  254. }));
  255. }
  256. }
  257. export function addDisposableThrottledListener(node, type, handler, eventMerger, minimumTimeMs) {
  258. return new TimeoutThrottledDomListener(node, type, handler, eventMerger, minimumTimeMs);
  259. }
  260. export function getComputedStyle(el) {
  261. return document.defaultView.getComputedStyle(el, null);
  262. }
  263. export function getClientArea(element) {
  264. // Try with DOM clientWidth / clientHeight
  265. if (element !== document.body) {
  266. return new Dimension(element.clientWidth, element.clientHeight);
  267. }
  268. // If visual view port exits and it's on mobile, it should be used instead of window innerWidth / innerHeight, or document.body.clientWidth / document.body.clientHeight
  269. if (platform.isIOS && window.visualViewport) {
  270. return new Dimension(window.visualViewport.width, window.visualViewport.height);
  271. }
  272. // Try innerWidth / innerHeight
  273. if (window.innerWidth && window.innerHeight) {
  274. return new Dimension(window.innerWidth, window.innerHeight);
  275. }
  276. // Try with document.body.clientWidth / document.body.clientHeight
  277. if (document.body && document.body.clientWidth && document.body.clientHeight) {
  278. return new Dimension(document.body.clientWidth, document.body.clientHeight);
  279. }
  280. // Try with document.documentElement.clientWidth / document.documentElement.clientHeight
  281. if (document.documentElement && document.documentElement.clientWidth && document.documentElement.clientHeight) {
  282. return new Dimension(document.documentElement.clientWidth, document.documentElement.clientHeight);
  283. }
  284. throw new Error('Unable to figure out browser width and height');
  285. }
  286. class SizeUtils {
  287. // Adapted from WinJS
  288. // Converts a CSS positioning string for the specified element to pixels.
  289. static convertToPixels(element, value) {
  290. return parseFloat(value) || 0;
  291. }
  292. static getDimension(element, cssPropertyName, jsPropertyName) {
  293. let computedStyle = getComputedStyle(element);
  294. let value = '0';
  295. if (computedStyle) {
  296. if (computedStyle.getPropertyValue) {
  297. value = computedStyle.getPropertyValue(cssPropertyName);
  298. }
  299. else {
  300. // IE8
  301. value = computedStyle.getAttribute(jsPropertyName);
  302. }
  303. }
  304. return SizeUtils.convertToPixels(element, value);
  305. }
  306. static getBorderLeftWidth(element) {
  307. return SizeUtils.getDimension(element, 'border-left-width', 'borderLeftWidth');
  308. }
  309. static getBorderRightWidth(element) {
  310. return SizeUtils.getDimension(element, 'border-right-width', 'borderRightWidth');
  311. }
  312. static getBorderTopWidth(element) {
  313. return SizeUtils.getDimension(element, 'border-top-width', 'borderTopWidth');
  314. }
  315. static getBorderBottomWidth(element) {
  316. return SizeUtils.getDimension(element, 'border-bottom-width', 'borderBottomWidth');
  317. }
  318. static getPaddingLeft(element) {
  319. return SizeUtils.getDimension(element, 'padding-left', 'paddingLeft');
  320. }
  321. static getPaddingRight(element) {
  322. return SizeUtils.getDimension(element, 'padding-right', 'paddingRight');
  323. }
  324. static getPaddingTop(element) {
  325. return SizeUtils.getDimension(element, 'padding-top', 'paddingTop');
  326. }
  327. static getPaddingBottom(element) {
  328. return SizeUtils.getDimension(element, 'padding-bottom', 'paddingBottom');
  329. }
  330. static getMarginLeft(element) {
  331. return SizeUtils.getDimension(element, 'margin-left', 'marginLeft');
  332. }
  333. static getMarginTop(element) {
  334. return SizeUtils.getDimension(element, 'margin-top', 'marginTop');
  335. }
  336. static getMarginRight(element) {
  337. return SizeUtils.getDimension(element, 'margin-right', 'marginRight');
  338. }
  339. static getMarginBottom(element) {
  340. return SizeUtils.getDimension(element, 'margin-bottom', 'marginBottom');
  341. }
  342. }
  343. export class Dimension {
  344. constructor(width, height) {
  345. this.width = width;
  346. this.height = height;
  347. }
  348. with(width = this.width, height = this.height) {
  349. if (width !== this.width || height !== this.height) {
  350. return new Dimension(width, height);
  351. }
  352. else {
  353. return this;
  354. }
  355. }
  356. static is(obj) {
  357. return typeof obj === 'object' && typeof obj.height === 'number' && typeof obj.width === 'number';
  358. }
  359. static lift(obj) {
  360. if (obj instanceof Dimension) {
  361. return obj;
  362. }
  363. else {
  364. return new Dimension(obj.width, obj.height);
  365. }
  366. }
  367. static equals(a, b) {
  368. if (a === b) {
  369. return true;
  370. }
  371. if (!a || !b) {
  372. return false;
  373. }
  374. return a.width === b.width && a.height === b.height;
  375. }
  376. }
  377. export function getTopLeftOffset(element) {
  378. // Adapted from WinJS.Utilities.getPosition
  379. // and added borders to the mix
  380. let offsetParent = element.offsetParent;
  381. let top = element.offsetTop;
  382. let left = element.offsetLeft;
  383. while ((element = element.parentNode) !== null
  384. && element !== document.body
  385. && element !== document.documentElement) {
  386. top -= element.scrollTop;
  387. const c = isShadowRoot(element) ? null : getComputedStyle(element);
  388. if (c) {
  389. left -= c.direction !== 'rtl' ? element.scrollLeft : -element.scrollLeft;
  390. }
  391. if (element === offsetParent) {
  392. left += SizeUtils.getBorderLeftWidth(element);
  393. top += SizeUtils.getBorderTopWidth(element);
  394. top += element.offsetTop;
  395. left += element.offsetLeft;
  396. offsetParent = element.offsetParent;
  397. }
  398. }
  399. return {
  400. left: left,
  401. top: top
  402. };
  403. }
  404. export function size(element, width, height) {
  405. if (typeof width === 'number') {
  406. element.style.width = `${width}px`;
  407. }
  408. if (typeof height === 'number') {
  409. element.style.height = `${height}px`;
  410. }
  411. }
  412. /**
  413. * Returns the position of a dom node relative to the entire page.
  414. */
  415. export function getDomNodePagePosition(domNode) {
  416. let bb = domNode.getBoundingClientRect();
  417. return {
  418. left: bb.left + StandardWindow.scrollX,
  419. top: bb.top + StandardWindow.scrollY,
  420. width: bb.width,
  421. height: bb.height
  422. };
  423. }
  424. export const StandardWindow = new class {
  425. get scrollX() {
  426. if (typeof window.scrollX === 'number') {
  427. // modern browsers
  428. return window.scrollX;
  429. }
  430. else {
  431. return document.body.scrollLeft + document.documentElement.scrollLeft;
  432. }
  433. }
  434. get scrollY() {
  435. if (typeof window.scrollY === 'number') {
  436. // modern browsers
  437. return window.scrollY;
  438. }
  439. else {
  440. return document.body.scrollTop + document.documentElement.scrollTop;
  441. }
  442. }
  443. };
  444. // Adapted from WinJS
  445. // Gets the width of the element, including margins.
  446. export function getTotalWidth(element) {
  447. let margin = SizeUtils.getMarginLeft(element) + SizeUtils.getMarginRight(element);
  448. return element.offsetWidth + margin;
  449. }
  450. export function getContentWidth(element) {
  451. let border = SizeUtils.getBorderLeftWidth(element) + SizeUtils.getBorderRightWidth(element);
  452. let padding = SizeUtils.getPaddingLeft(element) + SizeUtils.getPaddingRight(element);
  453. return element.offsetWidth - border - padding;
  454. }
  455. // Adapted from WinJS
  456. // Gets the height of the content of the specified element. The content height does not include borders or padding.
  457. export function getContentHeight(element) {
  458. let border = SizeUtils.getBorderTopWidth(element) + SizeUtils.getBorderBottomWidth(element);
  459. let padding = SizeUtils.getPaddingTop(element) + SizeUtils.getPaddingBottom(element);
  460. return element.offsetHeight - border - padding;
  461. }
  462. // Adapted from WinJS
  463. // Gets the height of the element, including its margins.
  464. export function getTotalHeight(element) {
  465. let margin = SizeUtils.getMarginTop(element) + SizeUtils.getMarginBottom(element);
  466. return element.offsetHeight + margin;
  467. }
  468. // ----------------------------------------------------------------------------------------
  469. export function isAncestor(testChild, testAncestor) {
  470. while (testChild) {
  471. if (testChild === testAncestor) {
  472. return true;
  473. }
  474. testChild = testChild.parentNode;
  475. }
  476. return false;
  477. }
  478. export function findParentWithClass(node, clazz, stopAtClazzOrNode) {
  479. while (node && node.nodeType === node.ELEMENT_NODE) {
  480. if (node.classList.contains(clazz)) {
  481. return node;
  482. }
  483. if (stopAtClazzOrNode) {
  484. if (typeof stopAtClazzOrNode === 'string') {
  485. if (node.classList.contains(stopAtClazzOrNode)) {
  486. return null;
  487. }
  488. }
  489. else {
  490. if (node === stopAtClazzOrNode) {
  491. return null;
  492. }
  493. }
  494. }
  495. node = node.parentNode;
  496. }
  497. return null;
  498. }
  499. export function hasParentWithClass(node, clazz, stopAtClazzOrNode) {
  500. return !!findParentWithClass(node, clazz, stopAtClazzOrNode);
  501. }
  502. export function isShadowRoot(node) {
  503. return (node && !!node.host && !!node.mode);
  504. }
  505. export function isInShadowDOM(domNode) {
  506. return !!getShadowRoot(domNode);
  507. }
  508. export function getShadowRoot(domNode) {
  509. while (domNode.parentNode) {
  510. if (domNode === document.body) {
  511. // reached the body
  512. return null;
  513. }
  514. domNode = domNode.parentNode;
  515. }
  516. return isShadowRoot(domNode) ? domNode : null;
  517. }
  518. export function getActiveElement() {
  519. let result = document.activeElement;
  520. while (result === null || result === void 0 ? void 0 : result.shadowRoot) {
  521. result = result.shadowRoot.activeElement;
  522. }
  523. return result;
  524. }
  525. export function createStyleSheet(container = document.getElementsByTagName('head')[0]) {
  526. let style = document.createElement('style');
  527. style.type = 'text/css';
  528. style.media = 'screen';
  529. container.appendChild(style);
  530. return style;
  531. }
  532. let _sharedStyleSheet = null;
  533. function getSharedStyleSheet() {
  534. if (!_sharedStyleSheet) {
  535. _sharedStyleSheet = createStyleSheet();
  536. }
  537. return _sharedStyleSheet;
  538. }
  539. function getDynamicStyleSheetRules(style) {
  540. var _a, _b;
  541. if ((_a = style === null || style === void 0 ? void 0 : style.sheet) === null || _a === void 0 ? void 0 : _a.rules) {
  542. // Chrome, IE
  543. return style.sheet.rules;
  544. }
  545. if ((_b = style === null || style === void 0 ? void 0 : style.sheet) === null || _b === void 0 ? void 0 : _b.cssRules) {
  546. // FF
  547. return style.sheet.cssRules;
  548. }
  549. return [];
  550. }
  551. export function createCSSRule(selector, cssText, style = getSharedStyleSheet()) {
  552. if (!style || !cssText) {
  553. return;
  554. }
  555. style.sheet.insertRule(selector + '{' + cssText + '}', 0);
  556. }
  557. export function removeCSSRulesContainingSelector(ruleName, style = getSharedStyleSheet()) {
  558. if (!style) {
  559. return;
  560. }
  561. let rules = getDynamicStyleSheetRules(style);
  562. let toDelete = [];
  563. for (let i = 0; i < rules.length; i++) {
  564. let rule = rules[i];
  565. if (rule.selectorText.indexOf(ruleName) !== -1) {
  566. toDelete.push(i);
  567. }
  568. }
  569. for (let i = toDelete.length - 1; i >= 0; i--) {
  570. style.sheet.deleteRule(toDelete[i]);
  571. }
  572. }
  573. export function isHTMLElement(o) {
  574. if (typeof HTMLElement === 'object') {
  575. return o instanceof HTMLElement;
  576. }
  577. return o && typeof o === 'object' && o.nodeType === 1 && typeof o.nodeName === 'string';
  578. }
  579. export const EventType = {
  580. // Mouse
  581. CLICK: 'click',
  582. AUXCLICK: 'auxclick',
  583. DBLCLICK: 'dblclick',
  584. MOUSE_UP: 'mouseup',
  585. MOUSE_DOWN: 'mousedown',
  586. MOUSE_OVER: 'mouseover',
  587. MOUSE_MOVE: 'mousemove',
  588. MOUSE_OUT: 'mouseout',
  589. MOUSE_ENTER: 'mouseenter',
  590. MOUSE_LEAVE: 'mouseleave',
  591. MOUSE_WHEEL: 'wheel',
  592. POINTER_UP: 'pointerup',
  593. POINTER_DOWN: 'pointerdown',
  594. POINTER_MOVE: 'pointermove',
  595. CONTEXT_MENU: 'contextmenu',
  596. WHEEL: 'wheel',
  597. // Keyboard
  598. KEY_DOWN: 'keydown',
  599. KEY_PRESS: 'keypress',
  600. KEY_UP: 'keyup',
  601. // HTML Document
  602. LOAD: 'load',
  603. BEFORE_UNLOAD: 'beforeunload',
  604. UNLOAD: 'unload',
  605. PAGE_SHOW: 'pageshow',
  606. PAGE_HIDE: 'pagehide',
  607. ABORT: 'abort',
  608. ERROR: 'error',
  609. RESIZE: 'resize',
  610. SCROLL: 'scroll',
  611. FULLSCREEN_CHANGE: 'fullscreenchange',
  612. WK_FULLSCREEN_CHANGE: 'webkitfullscreenchange',
  613. // Form
  614. SELECT: 'select',
  615. CHANGE: 'change',
  616. SUBMIT: 'submit',
  617. RESET: 'reset',
  618. FOCUS: 'focus',
  619. FOCUS_IN: 'focusin',
  620. FOCUS_OUT: 'focusout',
  621. BLUR: 'blur',
  622. INPUT: 'input',
  623. // Local Storage
  624. STORAGE: 'storage',
  625. // Drag
  626. DRAG_START: 'dragstart',
  627. DRAG: 'drag',
  628. DRAG_ENTER: 'dragenter',
  629. DRAG_LEAVE: 'dragleave',
  630. DRAG_OVER: 'dragover',
  631. DROP: 'drop',
  632. DRAG_END: 'dragend',
  633. // Animation
  634. ANIMATION_START: browser.isWebKit ? 'webkitAnimationStart' : 'animationstart',
  635. ANIMATION_END: browser.isWebKit ? 'webkitAnimationEnd' : 'animationend',
  636. ANIMATION_ITERATION: browser.isWebKit ? 'webkitAnimationIteration' : 'animationiteration'
  637. };
  638. export const EventHelper = {
  639. stop: function (e, cancelBubble) {
  640. if (e.preventDefault) {
  641. e.preventDefault();
  642. }
  643. else {
  644. // IE8
  645. e.returnValue = false;
  646. }
  647. if (cancelBubble) {
  648. if (e.stopPropagation) {
  649. e.stopPropagation();
  650. }
  651. else {
  652. // IE8
  653. e.cancelBubble = true;
  654. }
  655. }
  656. }
  657. };
  658. export function saveParentsScrollTop(node) {
  659. let r = [];
  660. for (let i = 0; node && node.nodeType === node.ELEMENT_NODE; i++) {
  661. r[i] = node.scrollTop;
  662. node = node.parentNode;
  663. }
  664. return r;
  665. }
  666. export function restoreParentsScrollTop(node, state) {
  667. for (let i = 0; node && node.nodeType === node.ELEMENT_NODE; i++) {
  668. if (node.scrollTop !== state[i]) {
  669. node.scrollTop = state[i];
  670. }
  671. node = node.parentNode;
  672. }
  673. }
  674. class FocusTracker extends Disposable {
  675. constructor(element) {
  676. super();
  677. this._onDidFocus = this._register(new Emitter());
  678. this.onDidFocus = this._onDidFocus.event;
  679. this._onDidBlur = this._register(new Emitter());
  680. this.onDidBlur = this._onDidBlur.event;
  681. let hasFocus = FocusTracker.hasFocusWithin(element);
  682. let loosingFocus = false;
  683. const onFocus = () => {
  684. loosingFocus = false;
  685. if (!hasFocus) {
  686. hasFocus = true;
  687. this._onDidFocus.fire();
  688. }
  689. };
  690. const onBlur = () => {
  691. if (hasFocus) {
  692. loosingFocus = true;
  693. window.setTimeout(() => {
  694. if (loosingFocus) {
  695. loosingFocus = false;
  696. hasFocus = false;
  697. this._onDidBlur.fire();
  698. }
  699. }, 0);
  700. }
  701. };
  702. this._refreshStateHandler = () => {
  703. let currentNodeHasFocus = FocusTracker.hasFocusWithin(element);
  704. if (currentNodeHasFocus !== hasFocus) {
  705. if (hasFocus) {
  706. onBlur();
  707. }
  708. else {
  709. onFocus();
  710. }
  711. }
  712. };
  713. this._register(addDisposableListener(element, EventType.FOCUS, onFocus, true));
  714. this._register(addDisposableListener(element, EventType.BLUR, onBlur, true));
  715. this._register(addDisposableListener(element, EventType.FOCUS_IN, () => this._refreshStateHandler()));
  716. this._register(addDisposableListener(element, EventType.FOCUS_OUT, () => this._refreshStateHandler()));
  717. }
  718. static hasFocusWithin(element) {
  719. const shadowRoot = getShadowRoot(element);
  720. const activeElement = (shadowRoot ? shadowRoot.activeElement : document.activeElement);
  721. return isAncestor(activeElement, element);
  722. }
  723. }
  724. export function trackFocus(element) {
  725. return new FocusTracker(element);
  726. }
  727. export function append(parent, ...children) {
  728. parent.append(...children);
  729. if (children.length === 1 && typeof children[0] !== 'string') {
  730. return children[0];
  731. }
  732. }
  733. export function prepend(parent, child) {
  734. parent.insertBefore(child, parent.firstChild);
  735. return child;
  736. }
  737. /**
  738. * Removes all children from `parent` and appends `children`
  739. */
  740. export function reset(parent, ...children) {
  741. parent.innerText = '';
  742. append(parent, ...children);
  743. }
  744. const SELECTOR_REGEX = /([\w\-]+)?(#([\w\-]+))?((\.([\w\-]+))*)/;
  745. export var Namespace;
  746. (function (Namespace) {
  747. Namespace["HTML"] = "http://www.w3.org/1999/xhtml";
  748. Namespace["SVG"] = "http://www.w3.org/2000/svg";
  749. })(Namespace || (Namespace = {}));
  750. function _$(namespace, description, attrs, ...children) {
  751. let match = SELECTOR_REGEX.exec(description);
  752. if (!match) {
  753. throw new Error('Bad use of emmet');
  754. }
  755. attrs = Object.assign({}, (attrs || {}));
  756. let tagName = match[1] || 'div';
  757. let result;
  758. if (namespace !== Namespace.HTML) {
  759. result = document.createElementNS(namespace, tagName);
  760. }
  761. else {
  762. result = document.createElement(tagName);
  763. }
  764. if (match[3]) {
  765. result.id = match[3];
  766. }
  767. if (match[4]) {
  768. result.className = match[4].replace(/\./g, ' ').trim();
  769. }
  770. Object.keys(attrs).forEach(name => {
  771. const value = attrs[name];
  772. if (typeof value === 'undefined') {
  773. return;
  774. }
  775. if (/^on\w+$/.test(name)) {
  776. result[name] = value;
  777. }
  778. else if (name === 'selected') {
  779. if (value) {
  780. result.setAttribute(name, 'true');
  781. }
  782. }
  783. else {
  784. result.setAttribute(name, value);
  785. }
  786. });
  787. result.append(...children);
  788. return result;
  789. }
  790. export function $(description, attrs, ...children) {
  791. return _$(Namespace.HTML, description, attrs, ...children);
  792. }
  793. $.SVG = function (description, attrs, ...children) {
  794. return _$(Namespace.SVG, description, attrs, ...children);
  795. };
  796. export function show(...elements) {
  797. for (let element of elements) {
  798. element.style.display = '';
  799. element.removeAttribute('aria-hidden');
  800. }
  801. }
  802. export function hide(...elements) {
  803. for (let element of elements) {
  804. element.style.display = 'none';
  805. element.setAttribute('aria-hidden', 'true');
  806. }
  807. }
  808. export function getElementsByTagName(tag) {
  809. return Array.prototype.slice.call(document.getElementsByTagName(tag), 0);
  810. }
  811. /**
  812. * Find a value usable for a dom node size such that the likelihood that it would be
  813. * displayed with constant screen pixels size is as high as possible.
  814. *
  815. * e.g. We would desire for the cursors to be 2px (CSS px) wide. Under a devicePixelRatio
  816. * of 1.25, the cursor will be 2.5 screen pixels wide. Depending on how the dom node aligns/"snaps"
  817. * with the screen pixels, it will sometimes be rendered with 2 screen pixels, and sometimes with 3 screen pixels.
  818. */
  819. export function computeScreenAwareSize(cssPx) {
  820. const screenPx = window.devicePixelRatio * cssPx;
  821. return Math.max(1, Math.floor(screenPx)) / window.devicePixelRatio;
  822. }
  823. /**
  824. * Open safely a new window. This is the best way to do so, but you cannot tell
  825. * if the window was opened or if it was blocked by the browser's popup blocker.
  826. * If you want to tell if the browser blocked the new window, use {@link windowOpenWithSuccess}.
  827. *
  828. * See https://github.com/microsoft/monaco-editor/issues/601
  829. * To protect against malicious code in the linked site, particularly phishing attempts,
  830. * the window.opener should be set to null to prevent the linked site from having access
  831. * to change the location of the current page.
  832. * See https://mathiasbynens.github.io/rel-noopener/
  833. */
  834. export function windowOpenNoOpener(url) {
  835. // By using 'noopener' in the `windowFeatures` argument, the newly created window will
  836. // not be able to use `window.opener` to reach back to the current page.
  837. // See https://stackoverflow.com/a/46958731
  838. // See https://developer.mozilla.org/en-US/docs/Web/API/Window/open#noopener
  839. // However, this also doesn't allow us to realize if the browser blocked
  840. // the creation of the window.
  841. window.open(url, '_blank', 'noopener');
  842. }
  843. export function animate(fn) {
  844. const step = () => {
  845. fn();
  846. stepDisposable = scheduleAtNextAnimationFrame(step);
  847. };
  848. let stepDisposable = scheduleAtNextAnimationFrame(step);
  849. return toDisposable(() => stepDisposable.dispose());
  850. }
  851. RemoteAuthorities.setPreferredWebSchema(/^https:/.test(window.location.href) ? 'https' : 'http');
  852. /**
  853. * returns url('...')
  854. */
  855. export function asCSSUrl(uri) {
  856. if (!uri) {
  857. return `url('')`;
  858. }
  859. return `url('${FileAccess.asBrowserUri(uri).toString(true).replace(/'/g, '%27')}')`;
  860. }
  861. export function asCSSPropertyValue(value) {
  862. return `'${value.replace(/'/g, '%27')}'`;
  863. }
  864. export class ModifierKeyEmitter extends Emitter {
  865. constructor() {
  866. super();
  867. this._subscriptions = new DisposableStore();
  868. this._keyStatus = {
  869. altKey: false,
  870. shiftKey: false,
  871. ctrlKey: false,
  872. metaKey: false
  873. };
  874. this._subscriptions.add(addDisposableListener(window, 'keydown', e => {
  875. if (e.defaultPrevented) {
  876. return;
  877. }
  878. const event = new StandardKeyboardEvent(e);
  879. // If Alt-key keydown event is repeated, ignore it #112347
  880. // Only known to be necessary for Alt-Key at the moment #115810
  881. if (event.keyCode === 6 /* Alt */ && e.repeat) {
  882. return;
  883. }
  884. if (e.altKey && !this._keyStatus.altKey) {
  885. this._keyStatus.lastKeyPressed = 'alt';
  886. }
  887. else if (e.ctrlKey && !this._keyStatus.ctrlKey) {
  888. this._keyStatus.lastKeyPressed = 'ctrl';
  889. }
  890. else if (e.metaKey && !this._keyStatus.metaKey) {
  891. this._keyStatus.lastKeyPressed = 'meta';
  892. }
  893. else if (e.shiftKey && !this._keyStatus.shiftKey) {
  894. this._keyStatus.lastKeyPressed = 'shift';
  895. }
  896. else if (event.keyCode !== 6 /* Alt */) {
  897. this._keyStatus.lastKeyPressed = undefined;
  898. }
  899. else {
  900. return;
  901. }
  902. this._keyStatus.altKey = e.altKey;
  903. this._keyStatus.ctrlKey = e.ctrlKey;
  904. this._keyStatus.metaKey = e.metaKey;
  905. this._keyStatus.shiftKey = e.shiftKey;
  906. if (this._keyStatus.lastKeyPressed) {
  907. this._keyStatus.event = e;
  908. this.fire(this._keyStatus);
  909. }
  910. }, true));
  911. this._subscriptions.add(addDisposableListener(window, 'keyup', e => {
  912. if (e.defaultPrevented) {
  913. return;
  914. }
  915. if (!e.altKey && this._keyStatus.altKey) {
  916. this._keyStatus.lastKeyReleased = 'alt';
  917. }
  918. else if (!e.ctrlKey && this._keyStatus.ctrlKey) {
  919. this._keyStatus.lastKeyReleased = 'ctrl';
  920. }
  921. else if (!e.metaKey && this._keyStatus.metaKey) {
  922. this._keyStatus.lastKeyReleased = 'meta';
  923. }
  924. else if (!e.shiftKey && this._keyStatus.shiftKey) {
  925. this._keyStatus.lastKeyReleased = 'shift';
  926. }
  927. else {
  928. this._keyStatus.lastKeyReleased = undefined;
  929. }
  930. if (this._keyStatus.lastKeyPressed !== this._keyStatus.lastKeyReleased) {
  931. this._keyStatus.lastKeyPressed = undefined;
  932. }
  933. this._keyStatus.altKey = e.altKey;
  934. this._keyStatus.ctrlKey = e.ctrlKey;
  935. this._keyStatus.metaKey = e.metaKey;
  936. this._keyStatus.shiftKey = e.shiftKey;
  937. if (this._keyStatus.lastKeyReleased) {
  938. this._keyStatus.event = e;
  939. this.fire(this._keyStatus);
  940. }
  941. }, true));
  942. this._subscriptions.add(addDisposableListener(document.body, 'mousedown', () => {
  943. this._keyStatus.lastKeyPressed = undefined;
  944. }, true));
  945. this._subscriptions.add(addDisposableListener(document.body, 'mouseup', () => {
  946. this._keyStatus.lastKeyPressed = undefined;
  947. }, true));
  948. this._subscriptions.add(addDisposableListener(document.body, 'mousemove', e => {
  949. if (e.buttons) {
  950. this._keyStatus.lastKeyPressed = undefined;
  951. }
  952. }, true));
  953. this._subscriptions.add(addDisposableListener(window, 'blur', () => {
  954. this.resetKeyStatus();
  955. }));
  956. }
  957. get keyStatus() {
  958. return this._keyStatus;
  959. }
  960. /**
  961. * Allows to explicitly reset the key status based on more knowledge (#109062)
  962. */
  963. resetKeyStatus() {
  964. this.doResetKeyStatus();
  965. this.fire(this._keyStatus);
  966. }
  967. doResetKeyStatus() {
  968. this._keyStatus = {
  969. altKey: false,
  970. shiftKey: false,
  971. ctrlKey: false,
  972. metaKey: false
  973. };
  974. }
  975. static getInstance() {
  976. if (!ModifierKeyEmitter.instance) {
  977. ModifierKeyEmitter.instance = new ModifierKeyEmitter();
  978. }
  979. return ModifierKeyEmitter.instance;
  980. }
  981. dispose() {
  982. super.dispose();
  983. this._subscriptions.dispose();
  984. }
  985. }
  986. export function addMatchMediaChangeListener(query, callback) {
  987. const mediaQueryList = window.matchMedia(query);
  988. if (typeof mediaQueryList.addEventListener === 'function') {
  989. mediaQueryList.addEventListener('change', callback);
  990. }
  991. else {
  992. // Safari 13.x
  993. mediaQueryList.addListener(callback);
  994. }
  995. }