dom.js 38 KB

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