dom.js 34 KB

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