hunk
dict
file
stringlengths
0
11.8M
file_path
stringlengths
2
234
label
int64
0
1
commit_url
stringlengths
74
103
dependency_score
listlengths
5
5
{ "id": 8, "code_window": [ " validTo: responseReceivedPayload?.response.security?.certificate?.validUntil,\n", " });\n", " if (event.metrics?.protocol)\n", " response._setHttpVersion(event.metrics.protocol);\n", " response._requestFinished(helper.secondsToRoundishMillis(event.timestamp - request._timestamp));\n", " }\n", "\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " if (event.metrics?.responseBodyBytesReceived)\n", " request.request.responseSize.encodedBodySize = event.metrics.responseBodyBytesReceived;\n", " if (event.metrics?.responseHeaderBytesReceived)\n", " request.request.responseSize.responseHeadersSize = event.metrics.responseHeaderBytesReceived;\n", "\n" ], "file_path": "src/server/webkit/wkPage.ts", "type": "add", "edit_start_line_idx": 1000 }
/** * Copyright 2017 Google Inc. All rights reserved. * Modifications copyright (c) Microsoft Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import { test as it, expect } from './pageTest'; it('should close page with active dialog', async ({page}) => { await page.setContent(`<button onclick="setTimeout(() => alert(1))">alert</button>`); page.click('button'); await page.waitForEvent('dialog'); await page.close(); }); it('should not accept after close', async ({page}) => { page.evaluate(() => alert()).catch(() => {}); const dialog = await page.waitForEvent('dialog'); await page.close(); const e = await dialog.dismiss().catch(e => e); expect(e.message).toContain('Target page, context or browser has been closed'); });
tests/page/page-close.spec.ts
0
https://github.com/microsoft/playwright/commit/cfe7c1a7e3ca96843b0efce4e74bd87ee6b085ae
[ 0.00017513983766548336, 0.00017399551870767027, 0.00017253568512387574, 0.00017415329057257622, 0.0000010740195648395456 ]
{ "id": 8, "code_window": [ " validTo: responseReceivedPayload?.response.security?.certificate?.validUntil,\n", " });\n", " if (event.metrics?.protocol)\n", " response._setHttpVersion(event.metrics.protocol);\n", " response._requestFinished(helper.secondsToRoundishMillis(event.timestamp - request._timestamp));\n", " }\n", "\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " if (event.metrics?.responseBodyBytesReceived)\n", " request.request.responseSize.encodedBodySize = event.metrics.responseBodyBytesReceived;\n", " if (event.metrics?.responseHeaderBytesReceived)\n", " request.request.responseSize.responseHeadersSize = event.metrics.responseHeaderBytesReceived;\n", "\n" ], "file_path": "src/server/webkit/wkPage.ts", "type": "add", "edit_start_line_idx": 1000 }
/** * Copyright (c) Microsoft Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import * as css from './cssTokenizer'; // Note: '>=' is used internally for text engine to preserve backwards compatibility. type ClauseCombinator = '' | '>' | '+' | '~' | '>='; // TODO: consider // - key=value // - operators like `=`, `|=`, `~=`, `*=`, `/` // - <empty>~=value // - argument modes: "parse all", "parse commas", "just a string" export type CSSFunctionArgument = CSSComplexSelector | number | string; export type CSSFunction = { name: string, args: CSSFunctionArgument[] }; export type CSSSimpleSelector = { css?: string, functions: CSSFunction[] }; export type CSSComplexSelector = { simples: { selector: CSSSimpleSelector, combinator: ClauseCombinator }[] }; export type CSSComplexSelectorList = CSSComplexSelector[]; export function parseCSS(selector: string, customNames: Set<string>): { selector: CSSComplexSelectorList, names: string[] } { let tokens: css.CSSTokenInterface[]; try { tokens = css.tokenize(selector); if (!(tokens[tokens.length - 1] instanceof css.EOFToken)) tokens.push(new css.EOFToken()); } catch (e) { const newMessage = e.message + ` while parsing selector "${selector}"`; const index = (e.stack || '').indexOf(e.message); if (index !== -1) e.stack = e.stack.substring(0, index) + newMessage + e.stack.substring(index + e.message.length); e.message = newMessage; throw e; } const unsupportedToken = tokens.find(token => { return (token instanceof css.AtKeywordToken) || (token instanceof css.BadStringToken) || (token instanceof css.BadURLToken) || (token instanceof css.ColumnToken) || (token instanceof css.CDOToken) || (token instanceof css.CDCToken) || (token instanceof css.SemicolonToken) || // TODO: Consider using these for something, e.g. to escape complex strings. // For example :xpath{ (//div/bar[@attr="foo"])[2]/baz } // Or this way :xpath( {complex-xpath-goes-here("hello")} ) (token instanceof css.OpenCurlyToken) || (token instanceof css.CloseCurlyToken) || // TODO: Consider treating these as strings? (token instanceof css.URLToken) || (token instanceof css.PercentageToken); }); if (unsupportedToken) throw new Error(`Unsupported token "${unsupportedToken.toSource()}" while parsing selector "${selector}"`); let pos = 0; const names = new Set<string>(); function unexpected() { return new Error(`Unexpected token "${tokens[pos].toSource()}" while parsing selector "${selector}"`); } function skipWhitespace() { while (tokens[pos] instanceof css.WhitespaceToken) pos++; } function isIdent(p = pos) { return tokens[p] instanceof css.IdentToken; } function isString(p = pos) { return tokens[p] instanceof css.StringToken; } function isNumber(p = pos) { return tokens[p] instanceof css.NumberToken; } function isComma(p = pos) { return tokens[p] instanceof css.CommaToken; } function isCloseParen(p = pos) { return tokens[p] instanceof css.CloseParenToken; } function isStar(p = pos) { return (tokens[p] instanceof css.DelimToken) && tokens[p].value === '*'; } function isEOF(p = pos) { return tokens[p] instanceof css.EOFToken; } function isClauseCombinator(p = pos) { return (tokens[p] instanceof css.DelimToken) && (['>', '+', '~'].includes(tokens[p].value)); } function isSelectorClauseEnd(p = pos) { return isComma(p) || isCloseParen(p) || isEOF(p) || isClauseCombinator(p) || (tokens[p] instanceof css.WhitespaceToken); } function consumeFunctionArguments(): CSSFunctionArgument[] { const result = [consumeArgument()]; while (true) { skipWhitespace(); if (!isComma()) break; pos++; result.push(consumeArgument()); } return result; } function consumeArgument(): CSSFunctionArgument { skipWhitespace(); if (isNumber()) return tokens[pos++].value; if (isString()) return tokens[pos++].value; return consumeComplexSelector(); } function consumeComplexSelector(): CSSComplexSelector { skipWhitespace(); const result = { simples: [{ selector: consumeSimpleSelector(), combinator: '' as ClauseCombinator }] }; while (true) { skipWhitespace(); if (isClauseCombinator()) { result.simples[result.simples.length - 1].combinator = tokens[pos++].value as ClauseCombinator; skipWhitespace(); } else if (isSelectorClauseEnd()) { break; } result.simples.push({ combinator: '', selector: consumeSimpleSelector() }); } return result; } function consumeSimpleSelector(): CSSSimpleSelector { let rawCSSString = ''; const functions: CSSFunction[] = []; while (!isSelectorClauseEnd()) { if (isIdent() || isStar()) { rawCSSString += tokens[pos++].toSource(); } else if (tokens[pos] instanceof css.HashToken) { rawCSSString += tokens[pos++].toSource(); } else if ((tokens[pos] instanceof css.DelimToken) && tokens[pos].value === '.') { pos++; if (isIdent()) rawCSSString += '.' + tokens[pos++].toSource(); else throw unexpected(); } else if (tokens[pos] instanceof css.ColonToken) { pos++; if (isIdent()) { if (!customNames.has(tokens[pos].value.toLowerCase())) { rawCSSString += ':' + tokens[pos++].toSource(); } else { const name = tokens[pos++].value.toLowerCase(); functions.push({ name, args: [] }); names.add(name); } } else if (tokens[pos] instanceof css.FunctionToken) { const name = tokens[pos++].value.toLowerCase(); if (!customNames.has(name)) { rawCSSString += `:${name}(${consumeBuiltinFunctionArguments()})`; } else { functions.push({ name, args: consumeFunctionArguments() }); names.add(name); } skipWhitespace(); if (!isCloseParen()) throw unexpected(); pos++; } else { throw unexpected(); } } else if (tokens[pos] instanceof css.OpenSquareToken) { rawCSSString += '['; pos++; while (!(tokens[pos] instanceof css.CloseSquareToken) && !isEOF()) rawCSSString += tokens[pos++].toSource(); if (!(tokens[pos] instanceof css.CloseSquareToken)) throw unexpected(); rawCSSString += ']'; pos++; } else { throw unexpected(); } } if (!rawCSSString && !functions.length) throw unexpected(); return { css: rawCSSString || undefined, functions }; } function consumeBuiltinFunctionArguments(): string { let s = ''; while (!isCloseParen() && !isEOF()) s += tokens[pos++].toSource(); return s; } const result = consumeFunctionArguments(); if (!isEOF()) throw new Error(`Error while parsing selector "${selector}"`); if (result.some(arg => typeof arg !== 'object' || !('simples' in arg))) throw new Error(`Error while parsing selector "${selector}"`); return { selector: result as CSSComplexSelector[], names: Array.from(names) }; } export function serializeSelector(args: CSSFunctionArgument[]) { return args.map(arg => { if (typeof arg === 'string') return `"${arg}"`; if (typeof arg === 'number') return String(arg); return arg.simples.map(({ selector, combinator }) => { let s = selector.css || ''; s = s + selector.functions.map(func => `:${func.name}(${serializeSelector(func.args)})`).join(''); if (combinator) s += ' ' + combinator; return s; }).join(' '); }).join(', '); }
src/server/common/cssParser.ts
0
https://github.com/microsoft/playwright/commit/cfe7c1a7e3ca96843b0efce4e74bd87ee6b085ae
[ 0.00017831125296652317, 0.00017350427515339106, 0.0001671604550210759, 0.0001736165431793779, 0.0000026372297270427225 ]
{ "id": 9, "code_window": [ " const sizes = await response.request().sizes();\n", " expect(sizes.responseBodySize).toBe(fs.statSync(asset('simplezip.json')).size);\n", "});\n", "\n", "it('should have the correct responseBodySize for chunked request', async ({ page, server, asset }) => {\n", " it.fixme();\n", " const content = fs.readFileSync(asset('simplezip.json'));\n", " const AMOUNT_OF_CHUNKS = 10;\n", " const CHUNK_SIZE = Math.ceil(content.length / AMOUNT_OF_CHUNKS);\n", " server.setRoute('/chunked-simplezip.json', (req, resp) => {\n", " resp.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8', 'Transfer-Encoding': 'chunked' });\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "it('should have the correct responseBodySize for chunked request', async ({ page, server, asset, browserName, platform }) => {\n", " it.fixme(browserName === 'firefox');\n", " it.fixme(browserName === 'webkit' && platform !== 'darwin');\n" ], "file_path": "tests/page/page-network-sizes.spec.ts", "type": "replace", "edit_start_line_idx": 75 }
/** * Copyright 2017 Google Inc. All rights reserved. * Modifications copyright (c) Microsoft Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import * as jpeg from 'jpeg-js'; import path from 'path'; import * as png from 'pngjs'; import { splitErrorMessage } from '../../utils/stackTrace'; import { assert, createGuid, debugAssert, headersArrayToObject, headersObjectToArray, hostPlatform } from '../../utils/utils'; import * as accessibility from '../accessibility'; import * as dialog from '../dialog'; import * as dom from '../dom'; import * as frames from '../frames'; import { eventsHelper, RegisteredListener } from '../../utils/eventsHelper'; import { helper } from '../helper'; import { JSHandle } from '../javascript'; import * as network from '../network'; import { Page, PageBinding, PageDelegate } from '../page'; import { Progress } from '../progress'; import * as types from '../types'; import { Protocol } from './protocol'; import { getAccessibilityTree } from './wkAccessibility'; import { WKBrowserContext } from './wkBrowser'; import { WKSession } from './wkConnection'; import { WKExecutionContext } from './wkExecutionContext'; import { RawKeyboardImpl, RawMouseImpl, RawTouchscreenImpl } from './wkInput'; import { WKInterceptableRequest, WKRouteImpl } from './wkInterceptableRequest'; import { WKProvisionalPage } from './wkProvisionalPage'; import { WKWorkers } from './wkWorkers'; import { debugLogger } from '../../utils/debugLogger'; import { ManualPromise } from '../../utils/async'; const UTILITY_WORLD_NAME = '__playwright_utility_world__'; const BINDING_CALL_MESSAGE = '__playwright_binding_call__'; export class WKPage implements PageDelegate { readonly rawMouse: RawMouseImpl; readonly rawKeyboard: RawKeyboardImpl; readonly rawTouchscreen: RawTouchscreenImpl; _session: WKSession; private _provisionalPage: WKProvisionalPage | null = null; readonly _page: Page; private readonly _pagePromise = new ManualPromise<Page | Error>(); private readonly _pageProxySession: WKSession; readonly _opener: WKPage | null; private readonly _requestIdToRequest = new Map<string, WKInterceptableRequest>(); private readonly _workers: WKWorkers; private readonly _contextIdToContext: Map<number, dom.FrameExecutionContext>; private _mainFrameContextId?: number; private _sessionListeners: RegisteredListener[] = []; private _eventListeners: RegisteredListener[]; readonly _browserContext: WKBrowserContext; _initializedPage: Page | null = null; private _firstNonInitialNavigationCommittedPromise: Promise<void>; private _firstNonInitialNavigationCommittedFulfill = () => {}; _firstNonInitialNavigationCommittedReject = (e: Error) => {}; private _lastConsoleMessage: { derivedType: string, text: string, handles: JSHandle[]; count: number, location: types.ConsoleMessageLocation; } | null = null; private readonly _requestIdToResponseReceivedPayloadEvent = new Map<string, Protocol.Network.responseReceivedPayload>(); _needsResponseInterception: boolean = false; // Holds window features for the next popup being opened via window.open, // until the popup page proxy arrives. private _nextWindowOpenPopupFeatures?: string[]; private _recordingVideoFile: string | null = null; private _screencastGeneration: number = 0; constructor(browserContext: WKBrowserContext, pageProxySession: WKSession, opener: WKPage | null) { this._pageProxySession = pageProxySession; this._opener = opener; this.rawKeyboard = new RawKeyboardImpl(pageProxySession); this.rawMouse = new RawMouseImpl(pageProxySession); this.rawTouchscreen = new RawTouchscreenImpl(pageProxySession); this._contextIdToContext = new Map(); this._page = new Page(this, browserContext); this._workers = new WKWorkers(this._page); this._session = undefined as any as WKSession; this._browserContext = browserContext; this._page.on(Page.Events.FrameDetached, (frame: frames.Frame) => this._removeContextsForFrame(frame, false)); this._eventListeners = [ eventsHelper.addEventListener(this._pageProxySession, 'Target.targetCreated', this._onTargetCreated.bind(this)), eventsHelper.addEventListener(this._pageProxySession, 'Target.targetDestroyed', this._onTargetDestroyed.bind(this)), eventsHelper.addEventListener(this._pageProxySession, 'Target.dispatchMessageFromTarget', this._onDispatchMessageFromTarget.bind(this)), eventsHelper.addEventListener(this._pageProxySession, 'Target.didCommitProvisionalTarget', this._onDidCommitProvisionalTarget.bind(this)), eventsHelper.addEventListener(this._pageProxySession, 'Screencast.screencastFrame', this._onScreencastFrame.bind(this)), ]; this._firstNonInitialNavigationCommittedPromise = new Promise((f, r) => { this._firstNonInitialNavigationCommittedFulfill = f; this._firstNonInitialNavigationCommittedReject = r; }); if (opener && !browserContext._options.noDefaultViewport && opener._nextWindowOpenPopupFeatures) { const viewportSize = helper.getViewportSizeFromWindowFeatures(opener._nextWindowOpenPopupFeatures); opener._nextWindowOpenPopupFeatures = undefined; if (viewportSize) this._page._state.emulatedSize = { viewport: viewportSize, screen: viewportSize }; } } private async _initializePageProxySession() { const promises: Promise<any>[] = [ this._pageProxySession.send('Dialog.enable'), this._pageProxySession.send('Emulation.setActiveAndFocused', { active: true }), ]; const contextOptions = this._browserContext._options; if (contextOptions.javaScriptEnabled === false) promises.push(this._pageProxySession.send('Emulation.setJavaScriptEnabled', { enabled: false })); promises.push(this._updateViewport()); promises.push(this.updateHttpCredentials()); if (this._browserContext._permissions.size) { for (const [key, value] of this._browserContext._permissions) promises.push(this._grantPermissions(key, value)); } if (this._browserContext._options.recordVideo) { const outputFile = path.join(this._browserContext._options.recordVideo.dir, createGuid() + '.webm'); promises.push(this._browserContext._ensureVideosPath().then(() => { return this._startVideo({ // validateBrowserContextOptions ensures correct video size. ...this._browserContext._options.recordVideo!.size!, outputFile, }); })); } await Promise.all(promises); } private _setSession(session: WKSession) { eventsHelper.removeEventListeners(this._sessionListeners); this._session = session; this.rawKeyboard.setSession(session); this._addSessionListeners(); this._workers.setSession(session); } // This method is called for provisional targets as well. The session passed as the parameter // may be different from the current session and may be destroyed without becoming current. async _initializeSession(session: WKSession, provisional: boolean, resourceTreeHandler: (r: Protocol.Page.getResourceTreeReturnValue) => void) { await this._initializeSessionMayThrow(session, resourceTreeHandler).catch(e => { // Provisional session can be disposed at any time, for example due to new navigation initiating // a new provisional page. if (provisional && session.isDisposed()) return; // Swallow initialization errors due to newer target swap in, // since we will reinitialize again. if (this._session === session) throw e; }); } private async _initializeSessionMayThrow(session: WKSession, resourceTreeHandler: (r: Protocol.Page.getResourceTreeReturnValue) => void) { const [, frameTree] = await Promise.all([ // Page agent must be enabled before Runtime. session.send('Page.enable'), session.send('Page.getResourceTree'), ] as const); resourceTreeHandler(frameTree); const promises: Promise<any>[] = [ // Resource tree should be received before first execution context. session.send('Runtime.enable'), session.send('Page.createUserWorld', { name: UTILITY_WORLD_NAME }).catch(_ => {}), // Worlds are per-process session.send('Console.enable'), session.send('Network.enable'), this._workers.initializeSession(session) ]; if (this._page._needsRequestInterception()) { promises.push(session.send('Network.setInterceptionEnabled', { enabled: true })); promises.push(session.send('Network.addInterception', { url: '.*', stage: 'request', isRegex: true })); if (this._needsResponseInterception) promises.push(session.send('Network.addInterception', { url: '.*', stage: 'response', isRegex: true })); } const contextOptions = this._browserContext._options; if (contextOptions.userAgent) promises.push(session.send('Page.overrideUserAgent', { value: contextOptions.userAgent })); if (this._page._state.mediaType || this._page._state.colorScheme || this._page._state.reducedMotion) promises.push(WKPage._setEmulateMedia(session, this._page._state.mediaType, this._page._state.colorScheme, this._page._state.reducedMotion)); const bootstrapScript = this._calculateBootstrapScript(); if (bootstrapScript.length) promises.push(session.send('Page.setBootstrapScript', { source: bootstrapScript })); this._page.frames().map(frame => frame.evaluateExpression(bootstrapScript, false, undefined).catch(e => {})); if (contextOptions.bypassCSP) promises.push(session.send('Page.setBypassCSP', { enabled: true })); if (this._page._state.emulatedSize) { promises.push(session.send('Page.setScreenSizeOverride', { width: this._page._state.emulatedSize.screen.width, height: this._page._state.emulatedSize.screen.height, })); } promises.push(this.updateEmulateMedia()); promises.push(session.send('Network.setExtraHTTPHeaders', { headers: headersArrayToObject(this._calculateExtraHTTPHeaders(), false /* lowerCase */) })); if (contextOptions.offline) promises.push(session.send('Network.setEmulateOfflineState', { offline: true })); promises.push(session.send('Page.setTouchEmulationEnabled', { enabled: !!contextOptions.hasTouch })); if (contextOptions.timezoneId) { promises.push(session.send('Page.setTimeZone', { timeZone: contextOptions.timezoneId }). catch(e => { throw new Error(`Invalid timezone ID: ${contextOptions.timezoneId}`); })); } promises.push(session.send('Page.overrideSetting', { setting: 'DeviceOrientationEventEnabled' as any, value: contextOptions.isMobile })); promises.push(session.send('Page.overrideSetting', { setting: 'FullScreenEnabled' as any, value: !contextOptions.isMobile })); promises.push(session.send('Page.overrideSetting', { setting: 'NotificationsEnabled' as any, value: !contextOptions.isMobile })); promises.push(session.send('Page.overrideSetting', { setting: 'PointerLockEnabled' as any, value: !contextOptions.isMobile })); promises.push(session.send('Page.overrideSetting', { setting: 'InputTypeMonthEnabled' as any, value: contextOptions.isMobile })); promises.push(session.send('Page.overrideSetting', { setting: 'InputTypeWeekEnabled' as any, value: contextOptions.isMobile })); await Promise.all(promises); } private _onDidCommitProvisionalTarget(event: Protocol.Target.didCommitProvisionalTargetPayload) { const { oldTargetId, newTargetId } = event; assert(this._provisionalPage); assert(this._provisionalPage._session.sessionId === newTargetId, 'Unknown new target: ' + newTargetId); assert(this._session.sessionId === oldTargetId, 'Unknown old target: ' + oldTargetId); const newSession = this._provisionalPage._session; this._provisionalPage.commit(); this._provisionalPage.dispose(); this._provisionalPage = null; this._setSession(newSession); } private _onTargetDestroyed(event: Protocol.Target.targetDestroyedPayload) { const { targetId, crashed } = event; if (this._provisionalPage && this._provisionalPage._session.sessionId === targetId) { this._provisionalPage._session.dispose(false); this._provisionalPage.dispose(); this._provisionalPage = null; } else if (this._session.sessionId === targetId) { this._session.dispose(false); eventsHelper.removeEventListeners(this._sessionListeners); if (crashed) { this._session.markAsCrashed(); this._page._didCrash(); } } } didClose() { this._page._didClose(); } dispose(disconnected: boolean) { this._pageProxySession.dispose(disconnected); eventsHelper.removeEventListeners(this._sessionListeners); eventsHelper.removeEventListeners(this._eventListeners); if (this._session) this._session.dispose(disconnected); if (this._provisionalPage) { this._provisionalPage._session.dispose(disconnected); this._provisionalPage.dispose(); this._provisionalPage = null; } this._page._didDisconnect(); this._firstNonInitialNavigationCommittedReject(new Error('Page closed')); } dispatchMessageToSession(message: any) { this._pageProxySession.dispatchMessage(message); } handleProvisionalLoadFailed(event: Protocol.Playwright.provisionalLoadFailedPayload) { if (!this._initializedPage) { this._firstNonInitialNavigationCommittedReject(new Error('Initial load failed')); return; } if (!this._provisionalPage) return; let errorText = event.error; if (errorText.includes('cancelled')) errorText += '; maybe frame was detached?'; this._page._frameManager.frameAbortedNavigation(this._page.mainFrame()._id, errorText, event.loaderId); } handleWindowOpen(event: Protocol.Playwright.windowOpenPayload) { debugAssert(!this._nextWindowOpenPopupFeatures); this._nextWindowOpenPopupFeatures = event.windowFeatures; } async pageOrError(): Promise<Page | Error> { return this._pagePromise; } private async _onTargetCreated(event: Protocol.Target.targetCreatedPayload) { const { targetInfo } = event; const session = new WKSession(this._pageProxySession.connection, targetInfo.targetId, `Target closed`, (message: any) => { this._pageProxySession.send('Target.sendMessageToTarget', { message: JSON.stringify(message), targetId: targetInfo.targetId }).catch(e => { session.dispatchMessage({ id: message.id, error: { message: e.message } }); }); }); assert(targetInfo.type === 'page', 'Only page targets are expected in WebKit, received: ' + targetInfo.type); if (!targetInfo.isProvisional) { assert(!this._initializedPage); let pageOrError: Page | Error; try { this._setSession(session); await Promise.all([ this._initializePageProxySession(), this._initializeSession(session, false, ({frameTree}) => this._handleFrameTree(frameTree)), ]); pageOrError = this._page; } catch (e) { pageOrError = e; } if (targetInfo.isPaused) this._pageProxySession.sendMayFail('Target.resume', { targetId: targetInfo.targetId }); if ((pageOrError instanceof Page) && this._page.mainFrame().url() === '') { try { // Initial empty page has an empty url. We should wait until the first real url has been loaded, // even if that url is about:blank. This is especially important for popups, where we need the // actual url before interacting with it. await this._firstNonInitialNavigationCommittedPromise; } catch (e) { pageOrError = e; } } else { // Avoid rejection on disconnect. this._firstNonInitialNavigationCommittedPromise.catch(() => {}); } await this._page.initOpener(this._opener); // Note: it is important to call |reportAsNew| before resolving pageOrError promise, // so that anyone who awaits pageOrError got a ready and reported page. this._initializedPage = pageOrError instanceof Page ? pageOrError : null; this._page.reportAsNew(pageOrError instanceof Page ? undefined : pageOrError); this._pagePromise.resolve(pageOrError); } else { assert(targetInfo.isProvisional); assert(!this._provisionalPage); this._provisionalPage = new WKProvisionalPage(session, this); if (targetInfo.isPaused) { this._provisionalPage.initializationPromise.then(() => { this._pageProxySession.sendMayFail('Target.resume', { targetId: targetInfo.targetId }); }); } } } private _onDispatchMessageFromTarget(event: Protocol.Target.dispatchMessageFromTargetPayload) { const { targetId, message } = event; if (this._provisionalPage && this._provisionalPage._session.sessionId === targetId) this._provisionalPage._session.dispatchMessage(JSON.parse(message)); else if (this._session.sessionId === targetId) this._session.dispatchMessage(JSON.parse(message)); else throw new Error('Unknown target: ' + targetId); } private _addSessionListeners() { // TODO: remove Page.willRequestOpenWindow and Page.didRequestOpenWindow from the protocol. this._sessionListeners = [ eventsHelper.addEventListener(this._session, 'Page.frameNavigated', event => this._onFrameNavigated(event.frame, false)), eventsHelper.addEventListener(this._session, 'Page.navigatedWithinDocument', event => this._onFrameNavigatedWithinDocument(event.frameId, event.url)), eventsHelper.addEventListener(this._session, 'Page.frameAttached', event => this._onFrameAttached(event.frameId, event.parentFrameId)), eventsHelper.addEventListener(this._session, 'Page.frameDetached', event => this._onFrameDetached(event.frameId)), eventsHelper.addEventListener(this._session, 'Page.frameScheduledNavigation', event => this._onFrameScheduledNavigation(event.frameId)), eventsHelper.addEventListener(this._session, 'Page.frameStoppedLoading', event => this._onFrameStoppedLoading(event.frameId)), eventsHelper.addEventListener(this._session, 'Page.loadEventFired', event => this._onLifecycleEvent(event.frameId, 'load')), eventsHelper.addEventListener(this._session, 'Page.domContentEventFired', event => this._onLifecycleEvent(event.frameId, 'domcontentloaded')), eventsHelper.addEventListener(this._session, 'Runtime.executionContextCreated', event => this._onExecutionContextCreated(event.context)), eventsHelper.addEventListener(this._session, 'Console.messageAdded', event => this._onConsoleMessage(event)), eventsHelper.addEventListener(this._session, 'Console.messageRepeatCountUpdated', event => this._onConsoleRepeatCountUpdated(event)), eventsHelper.addEventListener(this._pageProxySession, 'Dialog.javascriptDialogOpening', event => this._onDialog(event)), eventsHelper.addEventListener(this._session, 'Page.fileChooserOpened', event => this._onFileChooserOpened(event)), eventsHelper.addEventListener(this._session, 'Network.requestWillBeSent', e => this._onRequestWillBeSent(this._session, e)), eventsHelper.addEventListener(this._session, 'Network.requestIntercepted', e => this._onRequestIntercepted(this._session, e)), eventsHelper.addEventListener(this._session, 'Network.responseIntercepted', e => this._onResponseIntercepted(this._session, e)), eventsHelper.addEventListener(this._session, 'Network.responseReceived', e => this._onResponseReceived(e)), eventsHelper.addEventListener(this._session, 'Network.loadingFinished', e => this._onLoadingFinished(e)), eventsHelper.addEventListener(this._session, 'Network.loadingFailed', e => this._onLoadingFailed(e)), eventsHelper.addEventListener(this._session, 'Network.webSocketCreated', e => this._page._frameManager.onWebSocketCreated(e.requestId, e.url)), eventsHelper.addEventListener(this._session, 'Network.webSocketWillSendHandshakeRequest', e => this._page._frameManager.onWebSocketRequest(e.requestId)), eventsHelper.addEventListener(this._session, 'Network.webSocketHandshakeResponseReceived', e => this._page._frameManager.onWebSocketResponse(e.requestId, e.response.status, e.response.statusText)), eventsHelper.addEventListener(this._session, 'Network.webSocketFrameSent', e => e.response.payloadData && this._page._frameManager.onWebSocketFrameSent(e.requestId, e.response.opcode, e.response.payloadData)), eventsHelper.addEventListener(this._session, 'Network.webSocketFrameReceived', e => e.response.payloadData && this._page._frameManager.webSocketFrameReceived(e.requestId, e.response.opcode, e.response.payloadData)), eventsHelper.addEventListener(this._session, 'Network.webSocketClosed', e => this._page._frameManager.webSocketClosed(e.requestId)), eventsHelper.addEventListener(this._session, 'Network.webSocketFrameError', e => this._page._frameManager.webSocketError(e.requestId, e.errorMessage)), ]; } private async _updateState<T extends keyof Protocol.CommandParameters>( method: T, params?: Protocol.CommandParameters[T] ): Promise<void> { await this._forAllSessions(session => session.send(method, params).then()); } private async _forAllSessions(callback: ((session: WKSession) => Promise<void>)): Promise<void> { const sessions = [ this._session ]; // If the state changes during provisional load, push it to the provisional page // as well to always be in sync with the backend. if (this._provisionalPage) sessions.push(this._provisionalPage._session); await Promise.all(sessions.map(session => callback(session).catch(e => {}))); } private _onFrameScheduledNavigation(frameId: string) { this._page._frameManager.frameRequestedNavigation(frameId); } private _onFrameStoppedLoading(frameId: string) { this._page._frameManager.frameStoppedLoading(frameId); } private _onLifecycleEvent(frameId: string, event: types.LifecycleEvent) { this._page._frameManager.frameLifecycleEvent(frameId, event); } private _handleFrameTree(frameTree: Protocol.Page.FrameResourceTree) { this._onFrameAttached(frameTree.frame.id, frameTree.frame.parentId || null); this._onFrameNavigated(frameTree.frame, true); this._page._frameManager.frameLifecycleEvent(frameTree.frame.id, 'domcontentloaded'); this._page._frameManager.frameLifecycleEvent(frameTree.frame.id, 'load'); if (!frameTree.childFrames) return; for (const child of frameTree.childFrames) this._handleFrameTree(child); } _onFrameAttached(frameId: string, parentFrameId: string | null): frames.Frame { return this._page._frameManager.frameAttached(frameId, parentFrameId); } private _onFrameNavigated(framePayload: Protocol.Page.Frame, initial: boolean) { const frame = this._page._frameManager.frame(framePayload.id); assert(frame); this._removeContextsForFrame(frame, true); if (!framePayload.parentId) this._workers.clear(); this._page._frameManager.frameCommittedNewDocumentNavigation(framePayload.id, framePayload.url, framePayload.name || '', framePayload.loaderId, initial); if (!initial) this._firstNonInitialNavigationCommittedFulfill(); } private _onFrameNavigatedWithinDocument(frameId: string, url: string) { this._page._frameManager.frameCommittedSameDocumentNavigation(frameId, url); } private _onFrameDetached(frameId: string) { this._page._frameManager.frameDetached(frameId); } private _removeContextsForFrame(frame: frames.Frame, notifyFrame: boolean) { for (const [contextId, context] of this._contextIdToContext) { if (context.frame === frame) { (context._delegate as WKExecutionContext)._dispose(); this._contextIdToContext.delete(contextId); if (notifyFrame) frame._contextDestroyed(context); } } } private _onExecutionContextCreated(contextPayload: Protocol.Runtime.ExecutionContextDescription) { if (this._contextIdToContext.has(contextPayload.id)) return; const frame = this._page._frameManager.frame(contextPayload.frameId); if (!frame) return; const delegate = new WKExecutionContext(this._session, contextPayload.id); let worldName: types.World|null = null; if (contextPayload.type === 'normal') worldName = 'main'; else if (contextPayload.type === 'user' && contextPayload.name === UTILITY_WORLD_NAME) worldName = 'utility'; const context = new dom.FrameExecutionContext(delegate, frame, worldName); if (worldName) frame._contextCreated(worldName, context); if (contextPayload.type === 'normal' && frame === this._page.mainFrame()) this._mainFrameContextId = contextPayload.id; this._contextIdToContext.set(contextPayload.id, context); } async navigateFrame(frame: frames.Frame, url: string, referrer: string | undefined): Promise<frames.GotoResult> { if (this._pageProxySession.isDisposed()) throw new Error('Target closed'); const pageProxyId = this._pageProxySession.sessionId; const result = await this._pageProxySession.connection.browserSession.send('Playwright.navigate', { url, pageProxyId, frameId: frame._id, referrer }); return { newDocumentId: result.loaderId }; } private _onConsoleMessage(event: Protocol.Console.messageAddedPayload) { // Note: do no introduce await in this function, otherwise we lose the ordering. // For example, frame.setContent relies on this. const { type, level, text, parameters, url, line: lineNumber, column: columnNumber, source } = event.message; if (level === 'debug' && parameters && parameters[0].value === BINDING_CALL_MESSAGE) { const parsedObjectId = JSON.parse(parameters[1].objectId!); const context = this._contextIdToContext.get(parsedObjectId.injectedScriptId)!; this.pageOrError().then(pageOrError => { if (!(pageOrError instanceof Error)) this._page._onBindingCalled(parameters[2].value, context); }); return; } if (level === 'error' && source === 'javascript') { const { name, message } = splitErrorMessage(text); let stack: string; if (event.message.stackTrace) { stack = text + '\n' + event.message.stackTrace.map(callFrame => { return ` at ${callFrame.functionName || 'unknown'} (${callFrame.url}:${callFrame.lineNumber}:${callFrame.columnNumber})`; }).join('\n'); } else { stack = ''; } const error = new Error(message); error.stack = stack; error.name = name; this._page.firePageError(error); return; } let derivedType: string = type || ''; if (type === 'log') derivedType = level; else if (type === 'timing') derivedType = 'timeEnd'; const handles = (parameters || []).map(p => { let context: dom.FrameExecutionContext | null = null; if (p.objectId) { const objectId = JSON.parse(p.objectId); context = this._contextIdToContext.get(objectId.injectedScriptId)!; } else { context = this._contextIdToContext.get(this._mainFrameContextId!)!; } return context.createHandle(p); }); this._lastConsoleMessage = { derivedType, text, handles, count: 0, location: { url: url || '', lineNumber: (lineNumber || 1) - 1, columnNumber: (columnNumber || 1) - 1, } }; this._onConsoleRepeatCountUpdated({ count: 1}); } _onConsoleRepeatCountUpdated(event: Protocol.Console.messageRepeatCountUpdatedPayload) { if (this._lastConsoleMessage) { const { derivedType, text, handles, count, location } = this._lastConsoleMessage; for (let i = count; i < event.count; ++i) this._page._addConsoleMessage(derivedType, handles, location, handles.length ? undefined : text); this._lastConsoleMessage.count = event.count; } } _onDialog(event: Protocol.Dialog.javascriptDialogOpeningPayload) { this._page.emit(Page.Events.Dialog, new dialog.Dialog( this._page, event.type as dialog.DialogType, event.message, async (accept: boolean, promptText?: string) => { await this._pageProxySession.send('Dialog.handleJavaScriptDialog', { accept, promptText }); }, event.defaultPrompt)); } private async _onFileChooserOpened(event: {frameId: Protocol.Network.FrameId, element: Protocol.Runtime.RemoteObject}) { let handle; try { const context = await this._page._frameManager.frame(event.frameId)!._mainContext(); handle = context.createHandle(event.element).asElement()!; } catch (e) { // During async processing, frame/context may go away. We should not throw. return; } await this._page._onFileChooserOpened(handle); } private static async _setEmulateMedia(session: WKSession, mediaType: types.MediaType | null, colorScheme: types.ColorScheme | null, reducedMotion: types.ReducedMotion | null): Promise<void> { const promises = []; promises.push(session.send('Page.setEmulatedMedia', { media: mediaType || '' })); let appearance: any = undefined; switch (colorScheme) { case 'light': appearance = 'Light'; break; case 'dark': appearance = 'Dark'; break; } promises.push(session.send('Page.setForcedAppearance', { appearance })); let reducedMotionWk: any = undefined; switch (reducedMotion) { case 'reduce': reducedMotionWk = 'Reduce'; break; case 'no-preference': reducedMotionWk = 'NoPreference'; break; } promises.push(session.send('Page.setForcedReducedMotion', { reducedMotion: reducedMotionWk })); await Promise.all(promises); } async updateExtraHTTPHeaders(): Promise<void> { await this._updateState('Network.setExtraHTTPHeaders', { headers: headersArrayToObject(this._calculateExtraHTTPHeaders(), false /* lowerCase */) }); } _calculateExtraHTTPHeaders(): types.HeadersArray { const locale = this._browserContext._options.locale; const headers = network.mergeHeaders([ this._browserContext._options.extraHTTPHeaders, this._page._state.extraHTTPHeaders, locale ? network.singleHeader('Accept-Language', locale) : undefined, ]); return headers; } async updateEmulateMedia(): Promise<void> { const colorScheme = this._page._state.colorScheme; const reducedMotion = this._page._state.reducedMotion; await this._forAllSessions(session => WKPage._setEmulateMedia(session, this._page._state.mediaType, colorScheme, reducedMotion)); } async setEmulatedSize(emulatedSize: types.EmulatedSize): Promise<void> { assert(this._page._state.emulatedSize === emulatedSize); await this._updateViewport(); } async bringToFront(): Promise<void> { this._pageProxySession.send('Target.activate', { targetId: this._session.sessionId }); } async _updateViewport(): Promise<void> { const options = this._browserContext._options; const deviceSize = this._page._state.emulatedSize; if (deviceSize === null) return; const viewportSize = deviceSize.viewport; const screenSize = deviceSize.screen; const promises: Promise<any>[] = [ this._pageProxySession.send('Emulation.setDeviceMetricsOverride', { width: viewportSize.width, height: viewportSize.height, fixedLayout: !!options.isMobile, deviceScaleFactor: options.deviceScaleFactor || 1 }), this._session.send('Page.setScreenSizeOverride', { width: screenSize.width, height: screenSize.height, }), ]; if (options.isMobile) { const angle = viewportSize.width > viewportSize.height ? 90 : 0; promises.push(this._session.send('Page.setOrientationOverride', { angle })); } await Promise.all(promises); } async _ensureResponseInterceptionEnabled() { if (this._needsResponseInterception) return; this._needsResponseInterception = true; await this.updateRequestInterception(); } async updateRequestInterception(): Promise<void> { const enabled = this._page._needsRequestInterception(); const promises = [ this._updateState('Network.setInterceptionEnabled', { enabled }), this._updateState('Network.addInterception', { url: '.*', stage: 'request', isRegex: true }), ]; if (this._needsResponseInterception) this._updateState('Network.addInterception', { url: '.*', stage: 'response', isRegex: true }); await Promise.all(promises); } async updateOffline() { await this._updateState('Network.setEmulateOfflineState', { offline: !!this._browserContext._options.offline }); } async updateHttpCredentials() { const credentials = this._browserContext._options.httpCredentials || { username: '', password: '' }; await this._pageProxySession.send('Emulation.setAuthCredentials', { username: credentials.username, password: credentials.password }); } async setFileChooserIntercepted(enabled: boolean) { await this._session.send('Page.setInterceptFileChooserDialog', { enabled }).catch(e => {}); // target can be closed. } async reload(): Promise<void> { await this._session.send('Page.reload'); } goBack(): Promise<boolean> { return this._session.send('Page.goBack').then(() => true).catch(error => { if (error instanceof Error && error.message.includes(`Protocol error (Page.goBack): Failed to go`)) return false; throw error; }); } goForward(): Promise<boolean> { return this._session.send('Page.goForward').then(() => true).catch(error => { if (error instanceof Error && error.message.includes(`Protocol error (Page.goForward): Failed to go`)) return false; throw error; }); } async exposeBinding(binding: PageBinding): Promise<void> { await this._updateBootstrapScript(); await this._evaluateBindingScript(binding); } private async _evaluateBindingScript(binding: PageBinding): Promise<void> { const script = this._bindingToScript(binding); await Promise.all(this._page.frames().map(frame => frame.evaluateExpression(script, false, {}).catch(e => {}))); } async evaluateOnNewDocument(script: string): Promise<void> { await this._updateBootstrapScript(); } private _bindingToScript(binding: PageBinding): string { return `self.${binding.name} = (param) => console.debug('${BINDING_CALL_MESSAGE}', {}, param); ${binding.source}`; } private _calculateBootstrapScript(): string { const scripts: string[] = []; for (const binding of this._page.allBindings()) scripts.push(this._bindingToScript(binding)); scripts.push(...this._browserContext._evaluateOnNewDocumentSources); scripts.push(...this._page._evaluateOnNewDocumentSources); return scripts.join(';'); } async _updateBootstrapScript(): Promise<void> { await this._updateState('Page.setBootstrapScript', { source: this._calculateBootstrapScript() }); } async closePage(runBeforeUnload: boolean): Promise<void> { await this._stopVideo(); await this._pageProxySession.sendMayFail('Target.close', { targetId: this._session.sessionId, runBeforeUnload }); } canScreenshotOutsideViewport(): boolean { return true; } async setBackgroundColor(color?: { r: number; g: number; b: number; a: number; }): Promise<void> { await this._session.send('Page.setDefaultBackgroundColorOverride', { color }); } private _toolbarHeight(): number { if (this._page._browserContext._browser?.options.headful) return hostPlatform === 'mac10.15' ? 55 : 59; return 0; } private async _startVideo(options: types.PageScreencastOptions): Promise<void> { assert(!this._recordingVideoFile); const { screencastId } = await this._pageProxySession.send('Screencast.startVideo', { file: options.outputFile, width: options.width, height: options.height, toolbarHeight: this._toolbarHeight() }); this._recordingVideoFile = options.outputFile; this._browserContext._browser._videoStarted(this._browserContext, screencastId, options.outputFile, this.pageOrError()); } private async _stopVideo(): Promise<void> { if (!this._recordingVideoFile) return; await this._pageProxySession.sendMayFail('Screencast.stopVideo'); this._recordingVideoFile = null; } async takeScreenshot(progress: Progress, format: string, documentRect: types.Rect | undefined, viewportRect: types.Rect | undefined, quality: number | undefined): Promise<Buffer> { const rect = (documentRect || viewportRect)!; const result = await this._session.send('Page.snapshotRect', { ...rect, coordinateSystem: documentRect ? 'Page' : 'Viewport' }); const prefix = 'data:image/png;base64,'; let buffer = Buffer.from(result.dataURL.substr(prefix.length), 'base64'); if (format === 'jpeg') buffer = jpeg.encode(png.PNG.sync.read(buffer), quality).data; return buffer; } async resetViewport(): Promise<void> { assert(false, 'Should not be called'); } async getContentFrame(handle: dom.ElementHandle): Promise<frames.Frame | null> { const nodeInfo = await this._session.send('DOM.describeNode', { objectId: handle._objectId }); if (!nodeInfo.contentFrameId) return null; return this._page._frameManager.frame(nodeInfo.contentFrameId); } async getOwnerFrame(handle: dom.ElementHandle): Promise<string | null> { if (!handle._objectId) return null; const nodeInfo = await this._session.send('DOM.describeNode', { objectId: handle._objectId }); return nodeInfo.ownerFrameId || null; } isElementHandle(remoteObject: any): boolean { return (remoteObject as Protocol.Runtime.RemoteObject).subtype === 'node'; } async getBoundingBox(handle: dom.ElementHandle): Promise<types.Rect | null> { const quads = await this.getContentQuads(handle); if (!quads || !quads.length) return null; let minX = Infinity; let maxX = -Infinity; let minY = Infinity; let maxY = -Infinity; for (const quad of quads) { for (const point of quad) { minX = Math.min(minX, point.x); maxX = Math.max(maxX, point.x); minY = Math.min(minY, point.y); maxY = Math.max(maxY, point.y); } } return { x: minX, y: minY, width: maxX - minX, height: maxY - minY }; } async scrollRectIntoViewIfNeeded(handle: dom.ElementHandle, rect?: types.Rect): Promise<'error:notvisible' | 'error:notconnected' | 'done'> { return await this._session.send('DOM.scrollIntoViewIfNeeded', { objectId: handle._objectId, rect, }).then(() => 'done' as const).catch(e => { if (e instanceof Error && e.message.includes('Node does not have a layout object')) return 'error:notvisible'; if (e instanceof Error && e.message.includes('Node is detached from document')) return 'error:notconnected'; throw e; }); } async setScreencastOptions(options: { width: number, height: number, quality: number } | null): Promise<void> { if (options) { const so = { ...options, toolbarHeight: this._toolbarHeight() }; const { generation } = await this._pageProxySession.send('Screencast.startScreencast', so); this._screencastGeneration = generation; } else { await this._pageProxySession.send('Screencast.stopScreencast'); } } private _onScreencastFrame(event: Protocol.Screencast.screencastFramePayload) { this._pageProxySession.send('Screencast.screencastFrameAck', { generation: this._screencastGeneration }).catch(e => debugLogger.log('error', e)); const buffer = Buffer.from(event.data, 'base64'); this._page.emit(Page.Events.ScreencastFrame, { buffer, width: event.deviceWidth, height: event.deviceHeight, }); } rafCountForStablePosition(): number { return process.platform === 'win32' ? 5 : 1; } async getContentQuads(handle: dom.ElementHandle): Promise<types.Quad[] | null> { const result = await this._session.sendMayFail('DOM.getContentQuads', { objectId: handle._objectId }); if (!result) return null; return result.quads.map(quad => [ { x: quad[0], y: quad[1] }, { x: quad[2], y: quad[3] }, { x: quad[4], y: quad[5] }, { x: quad[6], y: quad[7] } ]); } async setInputFiles(handle: dom.ElementHandle<HTMLInputElement>, files: types.FilePayload[]): Promise<void> { const objectId = handle._objectId; const protocolFiles = files.map(file => ({ name: file.name, type: file.mimeType, data: file.buffer, })); await this._session.send('DOM.setInputFiles', { objectId, files: protocolFiles }); } async adoptElementHandle<T extends Node>(handle: dom.ElementHandle<T>, to: dom.FrameExecutionContext): Promise<dom.ElementHandle<T>> { const result = await this._session.sendMayFail('DOM.resolveNode', { objectId: handle._objectId, executionContextId: (to._delegate as WKExecutionContext)._contextId }); if (!result || result.object.subtype === 'null') throw new Error(dom.kUnableToAdoptErrorMessage); return to.createHandle(result.object) as dom.ElementHandle<T>; } async getAccessibilityTree(needle?: dom.ElementHandle): Promise<{tree: accessibility.AXNode, needle: accessibility.AXNode | null}> { return getAccessibilityTree(this._session, needle); } async inputActionEpilogue(): Promise<void> { } async getFrameElement(frame: frames.Frame): Promise<dom.ElementHandle> { const parent = frame.parentFrame(); if (!parent) throw new Error('Frame has been detached.'); const handles = await this._page.selectors._queryAll(parent, 'frame,iframe', undefined); const items = await Promise.all(handles.map(async handle => { const frame = await handle.contentFrame().catch(e => null); return { handle, frame }; })); const result = items.find(item => item.frame === frame); items.map(item => item === result ? Promise.resolve() : item.handle.dispose()); if (!result) throw new Error('Frame has been detached.'); return result.handle; } _onRequestWillBeSent(session: WKSession, event: Protocol.Network.requestWillBeSentPayload) { if (event.request.url.startsWith('data:')) return; let redirectedFrom: WKInterceptableRequest | null = null; if (event.redirectResponse) { const request = this._requestIdToRequest.get(event.requestId); // If we connect late to the target, we could have missed the requestWillBeSent event. if (request) { this._handleRequestRedirect(request, event.redirectResponse, event.timestamp); redirectedFrom = request; } } const frame = redirectedFrom ? redirectedFrom.request.frame() : this._page._frameManager.frame(event.frameId); // sometimes we get stray network events for detached frames // TODO(einbinder) why? if (!frame) return; // TODO(einbinder) this will fail if we are an XHR document request const isNavigationRequest = event.type === 'Document'; const documentId = isNavigationRequest ? event.loaderId : undefined; let route = null; // We do not support intercepting redirects. if (this._page._needsRequestInterception() && !redirectedFrom) route = new WKRouteImpl(session, this, event.requestId); const request = new WKInterceptableRequest(session, route, frame, event, redirectedFrom, documentId); this._requestIdToRequest.set(event.requestId, request); this._page._frameManager.requestStarted(request.request, route || undefined); } private _handleRequestRedirect(request: WKInterceptableRequest, responsePayload: Protocol.Network.Response, timestamp: number) { const response = request.createResponse(responsePayload); response._securityDetailsFinished(); response._serverAddrFinished(); response._requestFinished(responsePayload.timing ? helper.secondsToRoundishMillis(timestamp - request._timestamp) : -1); this._requestIdToRequest.delete(request._requestId); this._page._frameManager.requestReceivedResponse(response); this._page._frameManager.reportRequestFinished(request.request, response); } _onRequestIntercepted(session: WKSession, event: Protocol.Network.requestInterceptedPayload) { const request = this._requestIdToRequest.get(event.requestId); if (!request) { session.sendMayFail('Network.interceptRequestWithError', {errorType: 'Cancellation', requestId: event.requestId}); return; } if (!request._route) { // Intercepted, although we do not intend to allow interception. // Just continue. session.sendMayFail('Network.interceptWithRequest', { requestId: request._requestId }); } else { request._route._requestInterceptedPromise.resolve(); } } _onResponseIntercepted(session: WKSession, event: Protocol.Network.responseInterceptedPayload) { const request = this._requestIdToRequest.get(event.requestId); const route = request?._routeForRedirectChain(); if (!route?._responseInterceptedPromise) { session.sendMayFail('Network.interceptContinue', { requestId: event.requestId, stage: 'response' }); return; } route._responseInterceptedPromise.resolve({ response: event.response }); } _onResponseReceived(event: Protocol.Network.responseReceivedPayload) { const request = this._requestIdToRequest.get(event.requestId); // FileUpload sends a response without a matching request. if (!request) return; this._requestIdToResponseReceivedPayloadEvent.set(request._requestId, event); const response = request.createResponse(event.response); if (event.response.requestHeaders && Object.keys(event.response.requestHeaders).length) { const headers = { ...event.response.requestHeaders }; if (!headers['host']) headers['Host'] = new URL(request.request.url()).host; response.setRawRequestHeaders(headersObjectToArray(headers)); } this._page._frameManager.requestReceivedResponse(response); if (response.status() === 204) { this._onLoadingFailed({ requestId: event.requestId, errorText: 'Aborted: 204 No Content', timestamp: event.timestamp }); } } _onLoadingFinished(event: Protocol.Network.loadingFinishedPayload) { const request = this._requestIdToRequest.get(event.requestId); // For certain requestIds we never receive requestWillBeSent event. // @see https://crbug.com/750469 if (!request) return; // Under certain conditions we never get the Network.responseReceived // event from protocol. @see https://crbug.com/883475 const response = request.request._existingResponse(); if (response) { const responseReceivedPayload = this._requestIdToResponseReceivedPayloadEvent.get(request._requestId); response._serverAddrFinished(parseRemoteAddress(event?.metrics?.remoteAddress)); response._securityDetailsFinished({ protocol: isLoadedSecurely(response.url(), response.timing()) ? event.metrics?.securityConnection?.protocol : undefined, subjectName: responseReceivedPayload?.response.security?.certificate?.subject, validFrom: responseReceivedPayload?.response.security?.certificate?.validFrom, validTo: responseReceivedPayload?.response.security?.certificate?.validUntil, }); if (event.metrics?.protocol) response._setHttpVersion(event.metrics.protocol); response._requestFinished(helper.secondsToRoundishMillis(event.timestamp - request._timestamp)); } this._requestIdToResponseReceivedPayloadEvent.delete(request._requestId); this._requestIdToRequest.delete(request._requestId); this._page._frameManager.reportRequestFinished(request.request, response); } _onLoadingFailed(event: Protocol.Network.loadingFailedPayload) { const request = this._requestIdToRequest.get(event.requestId); // For certain requestIds we never receive requestWillBeSent event. // @see https://crbug.com/750469 if (!request) return; const route = request._routeForRedirectChain(); if (route?._responseInterceptedPromise) route._responseInterceptedPromise.resolve({ error: event }); const response = request.request._existingResponse(); if (response) { response._serverAddrFinished(); response._securityDetailsFinished(); response._requestFinished(helper.secondsToRoundishMillis(event.timestamp - request._timestamp)); } this._requestIdToRequest.delete(request._requestId); request.request._setFailureText(event.errorText); this._page._frameManager.requestFailed(request.request, event.errorText.includes('cancelled')); } async _grantPermissions(origin: string, permissions: string[]) { const webPermissionToProtocol = new Map<string, string>([ ['geolocation', 'geolocation'], ]); const filtered = permissions.map(permission => { const protocolPermission = webPermissionToProtocol.get(permission); if (!protocolPermission) throw new Error('Unknown permission: ' + permission); return protocolPermission; }); await this._pageProxySession.send('Emulation.grantPermissions', { origin, permissions: filtered }); } async _clearPermissions() { await this._pageProxySession.send('Emulation.resetPermissions', {}); } } /** * WebKit Remote Addresses look like: * * macOS: * ::1.8911 * 2606:2800:220:1:248:1893:25c8:1946.443 * 127.0.0.1:8000 * * ubuntu: * ::1:8907 * 127.0.0.1:8000 * * NB: They look IPv4 and IPv6's with ports but use an alternative notation. */ function parseRemoteAddress(value?: string) { if (!value) return; try { const colon = value.lastIndexOf(':'); const dot = value.lastIndexOf('.'); if (dot < 0) { // IPv6ish:port return { ipAddress: `[${value.slice(0, colon)}]`, port: +value.slice(colon + 1) }; } if (colon > dot) { // IPv4:port const [address, port] = value.split(':'); return { ipAddress: address, port: +port, }; } else { // IPv6ish.port const [address, port] = value.split('.'); return { ipAddress: `[${address}]`, port: +port, }; } } catch (_) {} } /** * Adapted from Source/WebInspectorUI/UserInterface/Models/Resource.js in * WebKit codebase. */ function isLoadedSecurely(url: string, timing: network.ResourceTiming) { try { const u = new URL(url); if (u.protocol !== 'https:' && u.protocol !== 'wss:' && u.protocol !== 'sftp:') return false; if (timing.secureConnectionStart === -1 && timing.connectStart !== -1) return false; return true; } catch (_) {} }
src/server/webkit/wkPage.ts
1
https://github.com/microsoft/playwright/commit/cfe7c1a7e3ca96843b0efce4e74bd87ee6b085ae
[ 0.0024447739124298096, 0.00023363092623185366, 0.0001628964819246903, 0.00017090706387534738, 0.00028648055740632117 ]
{ "id": 9, "code_window": [ " const sizes = await response.request().sizes();\n", " expect(sizes.responseBodySize).toBe(fs.statSync(asset('simplezip.json')).size);\n", "});\n", "\n", "it('should have the correct responseBodySize for chunked request', async ({ page, server, asset }) => {\n", " it.fixme();\n", " const content = fs.readFileSync(asset('simplezip.json'));\n", " const AMOUNT_OF_CHUNKS = 10;\n", " const CHUNK_SIZE = Math.ceil(content.length / AMOUNT_OF_CHUNKS);\n", " server.setRoute('/chunked-simplezip.json', (req, resp) => {\n", " resp.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8', 'Transfer-Encoding': 'chunked' });\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "it('should have the correct responseBodySize for chunked request', async ({ page, server, asset, browserName, platform }) => {\n", " it.fixme(browserName === 'firefox');\n", " it.fixme(browserName === 'webkit' && platform !== 'darwin');\n" ], "file_path": "tests/page/page-network-sizes.spec.ts", "type": "replace", "edit_start_line_idx": 75 }
/* * Copyright (C) 2010 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. */ #ifdef __OBJC__ #import <Cocoa/Cocoa.h> #import <WebKit/WebKit.h> #endif #define ENABLE_LOGGING 0 #if ENABLE_LOGGING #define LOG NSLog #else #define LOG(...) ((void)0) #endif
browser_patches/webkit/embedder/Playwright/mac/Playwright_Prefix.pch
0
https://github.com/microsoft/playwright/commit/cfe7c1a7e3ca96843b0efce4e74bd87ee6b085ae
[ 0.0001741050073178485, 0.0001711951190372929, 0.0001661585265537724, 0.00017225847113877535, 0.0000030044234335946385 ]
{ "id": 9, "code_window": [ " const sizes = await response.request().sizes();\n", " expect(sizes.responseBodySize).toBe(fs.statSync(asset('simplezip.json')).size);\n", "});\n", "\n", "it('should have the correct responseBodySize for chunked request', async ({ page, server, asset }) => {\n", " it.fixme();\n", " const content = fs.readFileSync(asset('simplezip.json'));\n", " const AMOUNT_OF_CHUNKS = 10;\n", " const CHUNK_SIZE = Math.ceil(content.length / AMOUNT_OF_CHUNKS);\n", " server.setRoute('/chunked-simplezip.json', (req, resp) => {\n", " resp.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8', 'Transfer-Encoding': 'chunked' });\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "it('should have the correct responseBodySize for chunked request', async ({ page, server, asset, browserName, platform }) => {\n", " it.fixme(browserName === 'firefox');\n", " it.fixme(browserName === 'webkit' && platform !== 'darwin');\n" ], "file_path": "tests/page/page-network-sizes.spec.ts", "type": "replace", "edit_start_line_idx": 75 }
/* * Copyright 2017 Google Inc. All rights reserved. * Modifications copyright (c) Microsoft Corporation. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import { ActionTraceEvent } from '../../../server/trace/common/traceEvents'; import { ContextEntry } from '../../../server/trace/viewer/traceModel'; import './timeline.css'; import { Boundaries } from '../geometry'; import * as React from 'react'; import { useMeasure } from './helpers'; import { msToString } from '../../uiUtils'; import { FilmStrip } from './filmStrip'; type TimelineBar = { action?: ActionTraceEvent; event?: ActionTraceEvent; leftPosition: number; rightPosition: number; leftTime: number; rightTime: number; type: string; label: string; className: string; }; export const Timeline: React.FunctionComponent<{ context: ContextEntry, boundaries: Boundaries, selectedAction: ActionTraceEvent | undefined, highlightedAction: ActionTraceEvent | undefined, onSelected: (action: ActionTraceEvent) => void, onHighlighted: (action: ActionTraceEvent | undefined) => void, }> = ({ context, boundaries, selectedAction, highlightedAction, onSelected, onHighlighted }) => { const [measure, ref] = useMeasure<HTMLDivElement>(); const barsRef = React.useRef<HTMLDivElement | null>(null); const [previewPoint, setPreviewPoint] = React.useState<{ x: number, clientY: number } | undefined>(); const [hoveredBarIndex, setHoveredBarIndex] = React.useState<number | undefined>(); const offsets = React.useMemo(() => { return calculateDividerOffsets(measure.width, boundaries); }, [measure.width, boundaries]); const bars = React.useMemo(() => { const bars: TimelineBar[] = []; for (const page of context.pages) { for (const entry of page.actions) { let detail = trimRight(entry.metadata.params.selector || '', 50); if (entry.metadata.method === 'goto') detail = trimRight(entry.metadata.params.url || '', 50); bars.push({ action: entry, leftTime: entry.metadata.startTime, rightTime: entry.metadata.endTime, leftPosition: timeToPosition(measure.width, boundaries, entry.metadata.startTime), rightPosition: timeToPosition(measure.width, boundaries, entry.metadata.endTime), label: entry.metadata.apiName + ' ' + detail, type: entry.metadata.type + '.' + entry.metadata.method, className: `${entry.metadata.type}_${entry.metadata.method}`.toLowerCase() }); } for (const event of page.events) { const startTime = event.metadata.startTime; bars.push({ event, leftTime: startTime, rightTime: startTime, leftPosition: timeToPosition(measure.width, boundaries, startTime), rightPosition: timeToPosition(measure.width, boundaries, startTime), label: event.metadata.method, type: event.metadata.type + '.' + event.metadata.method, className: `${event.metadata.type}_${event.metadata.method}`.toLowerCase() }); } } return bars; }, [context, boundaries, measure.width]); const hoveredBar = hoveredBarIndex !== undefined ? bars[hoveredBarIndex] : undefined; let targetBar: TimelineBar | undefined = bars.find(bar => bar.action === (highlightedAction || selectedAction)); targetBar = hoveredBar || targetBar; const findHoveredBarIndex = (x: number, y: number) => { const time = positionToTime(measure.width, boundaries, x); const time1 = positionToTime(measure.width, boundaries, x - 5); const time2 = positionToTime(measure.width, boundaries, x + 5); let index: number | undefined; let yDistance: number | undefined; let xDistance: number | undefined; for (let i = 0; i < bars.length; i++) { const bar = bars[i]; const yMiddle = kBarHeight / 2 + barTop(bar); const left = Math.max(bar.leftTime, time1); const right = Math.min(bar.rightTime, time2); const xMiddle = (bar.leftTime + bar.rightTime) / 2; const xd = Math.abs(time - xMiddle); const yd = Math.abs(y - yMiddle); if (left > right) continue; // Prefer closest yDistance (the same bar), among those prefer the closest xDistance. if (index === undefined || (yd < yDistance!) || (Math.abs(yd - yDistance!) < 1e-2 && xd < xDistance!)) { index = i; xDistance = xd; yDistance = yd; } } return index; }; const onMouseMove = (event: React.MouseEvent) => { if (!ref.current || !barsRef.current) return; const x = event.clientX - ref.current.getBoundingClientRect().left; const y = event.clientY - barsRef.current.getBoundingClientRect().top; const index = findHoveredBarIndex(x, y); setPreviewPoint({ x, clientY: event.clientY }); setHoveredBarIndex(index); if (typeof index === 'number') onHighlighted(bars[index].action); }; const onMouseLeave = () => { setPreviewPoint(undefined); setHoveredBarIndex(undefined); onHighlighted(undefined); }; const onClick = (event: React.MouseEvent) => { setPreviewPoint(undefined); if (!ref.current || !barsRef.current) return; const x = event.clientX - ref.current.getBoundingClientRect().left; const y = event.clientY - barsRef.current.getBoundingClientRect().top; const index = findHoveredBarIndex(x, y); if (index === undefined) return; const entry = bars[index].action; if (entry) onSelected(entry); }; return <div ref={ref} className='timeline-view' onMouseMove={onMouseMove} onMouseOver={onMouseMove} onMouseLeave={onMouseLeave} onClick={onClick}> <div className='timeline-grid'>{ offsets.map((offset, index) => { return <div key={index} className='timeline-divider' style={{ left: offset.position + 'px' }}> <div className='timeline-time'>{msToString(offset.time - boundaries.minimum)}</div> </div>; }) }</div> <div className='timeline-lane timeline-labels'>{ bars.map((bar, index) => { return <div key={index} className={'timeline-label ' + bar.className + (targetBar === bar ? ' selected' : '')} style={{ left: bar.leftPosition, maxWidth: 100, }} > {bar.label} </div>; }) }</div> <div className='timeline-lane timeline-bars' ref={barsRef}>{ bars.map((bar, index) => { return <div key={index} className={'timeline-bar ' + (bar.action ? 'action ' : '') + (bar.event ? 'event ' : '') + bar.className + (targetBar === bar ? ' selected' : '')} style={{ left: bar.leftPosition + 'px', width: Math.max(1, bar.rightPosition - bar.leftPosition) + 'px', top: barTop(bar) + 'px', }} ></div>; }) }</div> <FilmStrip context={context} boundaries={boundaries} previewPoint={previewPoint} /> <div className='timeline-marker timeline-marker-hover' style={{ display: (previewPoint !== undefined) ? 'block' : 'none', left: (previewPoint?.x || 0) + 'px', }}></div> </div>; }; function calculateDividerOffsets(clientWidth: number, boundaries: Boundaries): { position: number, time: number }[] { const minimumGap = 64; let dividerCount = clientWidth / minimumGap; const boundarySpan = boundaries.maximum - boundaries.minimum; const pixelsPerMillisecond = clientWidth / boundarySpan; let sectionTime = boundarySpan / dividerCount; const logSectionTime = Math.ceil(Math.log(sectionTime) / Math.LN10); sectionTime = Math.pow(10, logSectionTime); if (sectionTime * pixelsPerMillisecond >= 5 * minimumGap) sectionTime = sectionTime / 5; if (sectionTime * pixelsPerMillisecond >= 2 * minimumGap) sectionTime = sectionTime / 2; const firstDividerTime = boundaries.minimum; let lastDividerTime = boundaries.maximum; lastDividerTime += minimumGap / pixelsPerMillisecond; dividerCount = Math.ceil((lastDividerTime - firstDividerTime) / sectionTime); if (!sectionTime) dividerCount = 0; const offsets = []; for (let i = 0; i < dividerCount; ++i) { const time = firstDividerTime + sectionTime * i; offsets.push({ position: timeToPosition(clientWidth, boundaries, time), time }); } return offsets; } function timeToPosition(clientWidth: number, boundaries: Boundaries, time: number): number { return (time - boundaries.minimum) / (boundaries.maximum - boundaries.minimum) * clientWidth; } function positionToTime(clientWidth: number, boundaries: Boundaries, x: number): number { return x / clientWidth * (boundaries.maximum - boundaries.minimum) + boundaries.minimum; } function trimRight(s: string, maxLength: number): string { return s.length <= maxLength ? s : s.substring(0, maxLength - 1) + '\u2026'; } const kBarHeight = 11; function barTop(bar: TimelineBar): number { return bar.event ? 22 : (bar.action?.metadata.method === 'waitForEventInfo' ? 0 : 11); }
src/web/traceViewer/ui/timeline.tsx
0
https://github.com/microsoft/playwright/commit/cfe7c1a7e3ca96843b0efce4e74bd87ee6b085ae
[ 0.00019416223221924156, 0.00017386501713190228, 0.00016609356680419296, 0.00017324372311122715, 0.000005022824097977718 ]
{ "id": 9, "code_window": [ " const sizes = await response.request().sizes();\n", " expect(sizes.responseBodySize).toBe(fs.statSync(asset('simplezip.json')).size);\n", "});\n", "\n", "it('should have the correct responseBodySize for chunked request', async ({ page, server, asset }) => {\n", " it.fixme();\n", " const content = fs.readFileSync(asset('simplezip.json'));\n", " const AMOUNT_OF_CHUNKS = 10;\n", " const CHUNK_SIZE = Math.ceil(content.length / AMOUNT_OF_CHUNKS);\n", " server.setRoute('/chunked-simplezip.json', (req, resp) => {\n", " resp.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8', 'Transfer-Encoding': 'chunked' });\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "it('should have the correct responseBodySize for chunked request', async ({ page, server, asset, browserName, platform }) => {\n", " it.fixme(browserName === 'firefox');\n", " it.fixme(browserName === 'webkit' && platform !== 'darwin');\n" ], "file_path": "tests/page/page-network-sizes.spec.ts", "type": "replace", "edit_start_line_idx": 75 }
/** * Copyright 2017 Google Inc. All rights reserved. * Modifications copyright (c) Microsoft Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import { test as it, expect } from './pageTest'; import * as os from 'os'; function crash({ page, toImpl, browserName, platform, mode }: any) { if (browserName === 'chromium') { page.goto('chrome://crash').catch(e => {}); } else if (browserName === 'webkit') { it.skip(mode !== 'default'); it.fixme(platform === 'darwin' && parseInt(os.release(), 10) >= 20, 'Timing out after roll on BigSur'); toImpl(page)._delegate._session.send('Page.crash', {}).catch(e => {}); } else if (browserName === 'firefox') { it.skip(mode !== 'default'); toImpl(page)._delegate._session.send('Page.crash', {}).catch(e => {}); } } it.describe('', () => { it('should emit crash event when page crashes', async ({ page, toImpl, browserName, platform, mode }) => { await page.setContent(`<div>This page should crash</div>`); crash({ page, toImpl, browserName, platform, mode }); const crashedPage = await new Promise(f => page.on('crash', f)); expect(crashedPage).toBe(page); }); it('should throw on any action after page crashes', async ({ page, toImpl, browserName, platform, mode }) => { await page.setContent(`<div>This page should crash</div>`); crash({ page, toImpl, browserName, platform, mode }); await page.waitForEvent('crash'); const err = await page.evaluate(() => {}).then(() => null, e => e); expect(err).toBeTruthy(); expect(err.message).toContain('Target crashed'); }); it('should cancel waitForEvent when page crashes', async ({ page, toImpl, browserName, platform, mode }) => { await page.setContent(`<div>This page should crash</div>`); const promise = page.waitForEvent('response').catch(e => e); crash({ page, toImpl, browserName, platform, mode }); const error = await promise; expect(error.message).toContain('Page crashed'); }); it('should cancel navigation when page crashes', async ({ server, page, toImpl, browserName, platform, mode }) => { await page.setContent(`<div>This page should crash</div>`); server.setRoute('/one-style.css', () => {}); const promise = page.goto(server.PREFIX + '/one-style.html').catch(e => e); await page.waitForNavigation({ waitUntil: 'domcontentloaded' }); crash({ page, toImpl, browserName, platform, mode }); const error = await promise; expect(error.message).toContain('Navigation failed because page crashed'); }); it('should be able to close context when page crashes', async ({ isAndroid, isElectron, page, toImpl, browserName, platform, mode }) => { it.skip(isAndroid); it.skip(isElectron); await page.setContent(`<div>This page should crash</div>`); crash({ page, toImpl, browserName, platform, mode }); await page.waitForEvent('crash'); await page.context().close(); }); });
tests/page/page-event-crash.spec.ts
0
https://github.com/microsoft/playwright/commit/cfe7c1a7e3ca96843b0efce4e74bd87ee6b085ae
[ 0.00033877979149110615, 0.00019095756579190493, 0.00016465202497784048, 0.00017142260912805796, 0.00005594880349235609 ]
{ "id": 10, "code_window": [ " resp.end();\n", " });\n", " const response = await page.goto(server.PREFIX + '/chunked-simplezip.json');\n", " const sizes = await response.request().sizes();\n", " expect(sizes.responseBodySize).toBe(fs.statSync(asset('simplezip.json')).size);\n", "});\n", "\n", "it('should have the correct responseBodySize with gzip compression', async ({ page, server, asset }, testInfo) => {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " // The actual file size is 5100 bytes. The extra 75 bytes are coming from the chunked encoding headers and end bytes.\n", " if (browserName === 'webkit')\n", " // It should be 5175 there. On the actual network response, the body has a size of 5175.\n", " expect(sizes.responseBodySize).toBe(5173);\n", " else\n", " expect(sizes.responseBodySize).toBe(5175);\n" ], "file_path": "tests/page/page-network-sizes.spec.ts", "type": "replace", "edit_start_line_idx": 90 }
/** * Copyright 2017 Google Inc. All rights reserved. * Modifications copyright (c) Microsoft Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import { CRSession } from './crConnection'; import { Page } from '../page'; import { helper } from '../helper'; import { eventsHelper, RegisteredListener } from '../../utils/eventsHelper'; import { Protocol } from './protocol'; import * as network from '../network'; import * as frames from '../frames'; import * as types from '../types'; import { CRPage } from './crPage'; import { assert, headersObjectToArray } from '../../utils/utils'; export class CRNetworkManager { private _client: CRSession; private _page: Page; private _parentManager: CRNetworkManager | null; private _requestIdToRequest = new Map<string, InterceptableRequest>(); private _requestIdToRequestWillBeSentEvent = new Map<string, Protocol.Network.requestWillBeSentPayload>(); private _credentials: {username: string, password: string} | null = null; private _attemptedAuthentications = new Set<string>(); private _userRequestInterceptionEnabled = false; private _protocolRequestInterceptionEnabled = false; private _requestIdToRequestPausedEvent = new Map<string, Protocol.Fetch.requestPausedPayload>(); private _eventListeners: RegisteredListener[]; private _responseExtraInfoTracker = new ResponseExtraInfoTracker(); constructor(client: CRSession, page: Page, parentManager: CRNetworkManager | null) { this._client = client; this._page = page; this._parentManager = parentManager; this._eventListeners = this.instrumentNetworkEvents(client); } instrumentNetworkEvents(session: CRSession, workerFrame?: frames.Frame): RegisteredListener[] { return [ eventsHelper.addEventListener(session, 'Fetch.requestPaused', this._onRequestPaused.bind(this, workerFrame)), eventsHelper.addEventListener(session, 'Fetch.authRequired', this._onAuthRequired.bind(this)), eventsHelper.addEventListener(session, 'Network.dataReceived', this._onDataReceived.bind(this)), eventsHelper.addEventListener(session, 'Network.requestWillBeSent', this._onRequestWillBeSent.bind(this, workerFrame)), eventsHelper.addEventListener(session, 'Network.requestWillBeSentExtraInfo', this._onRequestWillBeSentExtraInfo.bind(this)), eventsHelper.addEventListener(session, 'Network.responseReceived', this._onResponseReceived.bind(this)), eventsHelper.addEventListener(session, 'Network.responseReceivedExtraInfo', this._onResponseReceivedExtraInfo.bind(this)), eventsHelper.addEventListener(session, 'Network.loadingFinished', this._onLoadingFinished.bind(this)), eventsHelper.addEventListener(session, 'Network.loadingFailed', this._onLoadingFailed.bind(this)), eventsHelper.addEventListener(session, 'Network.webSocketCreated', e => this._page._frameManager.onWebSocketCreated(e.requestId, e.url)), eventsHelper.addEventListener(session, 'Network.webSocketWillSendHandshakeRequest', e => this._page._frameManager.onWebSocketRequest(e.requestId)), eventsHelper.addEventListener(session, 'Network.webSocketHandshakeResponseReceived', e => this._page._frameManager.onWebSocketResponse(e.requestId, e.response.status, e.response.statusText)), eventsHelper.addEventListener(session, 'Network.webSocketFrameSent', e => e.response.payloadData && this._page._frameManager.onWebSocketFrameSent(e.requestId, e.response.opcode, e.response.payloadData)), eventsHelper.addEventListener(session, 'Network.webSocketFrameReceived', e => e.response.payloadData && this._page._frameManager.webSocketFrameReceived(e.requestId, e.response.opcode, e.response.payloadData)), eventsHelper.addEventListener(session, 'Network.webSocketClosed', e => this._page._frameManager.webSocketClosed(e.requestId)), eventsHelper.addEventListener(session, 'Network.webSocketFrameError', e => this._page._frameManager.webSocketError(e.requestId, e.errorMessage)), ]; } async initialize() { await this._client.send('Network.enable'); } dispose() { eventsHelper.removeEventListeners(this._eventListeners); } async authenticate(credentials: types.Credentials | null) { this._credentials = credentials; await this._updateProtocolRequestInterception(); } async setOffline(offline: boolean) { await this._client.send('Network.emulateNetworkConditions', { offline, // values of 0 remove any active throttling. crbug.com/456324#c9 latency: 0, downloadThroughput: -1, uploadThroughput: -1 }); } async setRequestInterception(value: boolean) { this._userRequestInterceptionEnabled = value; await this._updateProtocolRequestInterception(); } async _updateProtocolRequestInterception() { const enabled = this._userRequestInterceptionEnabled || !!this._credentials; if (enabled === this._protocolRequestInterceptionEnabled) return; this._protocolRequestInterceptionEnabled = enabled; if (enabled) { await Promise.all([ this._client.send('Network.setCacheDisabled', { cacheDisabled: true }), this._client.send('Fetch.enable', { handleAuthRequests: true, patterns: [{urlPattern: '*', requestStage: 'Request'}, {urlPattern: '*', requestStage: 'Response'}], }), ]); } else { await Promise.all([ this._client.send('Network.setCacheDisabled', { cacheDisabled: false }), this._client.send('Fetch.disable') ]); } } _onRequestWillBeSent(workerFrame: frames.Frame | undefined, event: Protocol.Network.requestWillBeSentPayload) { this._responseExtraInfoTracker.requestWillBeSent(event); // Request interception doesn't happen for data URLs with Network Service. if (this._protocolRequestInterceptionEnabled && !event.request.url.startsWith('data:')) { const requestId = event.requestId; const requestPausedEvent = this._requestIdToRequestPausedEvent.get(requestId); if (requestPausedEvent) { this._onRequest(workerFrame, event, requestPausedEvent); this._requestIdToRequestPausedEvent.delete(requestId); } else { this._requestIdToRequestWillBeSentEvent.set(event.requestId, event); } } else { this._onRequest(workerFrame, event, null); } } _onRequestWillBeSentExtraInfo(event: Protocol.Network.requestWillBeSentExtraInfoPayload) { this._responseExtraInfoTracker.requestWillBeSentExtraInfo(event); } _onAuthRequired(event: Protocol.Fetch.authRequiredPayload) { let response: 'Default' | 'CancelAuth' | 'ProvideCredentials' = 'Default'; if (this._attemptedAuthentications.has(event.requestId)) { response = 'CancelAuth'; } else if (this._credentials) { response = 'ProvideCredentials'; this._attemptedAuthentications.add(event.requestId); } const {username, password} = this._credentials || {username: undefined, password: undefined}; this._client._sendMayFail('Fetch.continueWithAuth', { requestId: event.requestId, authChallengeResponse: { response, username, password }, }); } _onRequestPaused(workerFrame: frames.Frame | undefined, event: Protocol.Fetch.requestPausedPayload) { if (!this._userRequestInterceptionEnabled && this._protocolRequestInterceptionEnabled) { this._client._sendMayFail('Fetch.continueRequest', { requestId: event.requestId }); } if (!event.networkId) { // Fetch without networkId means that request was not recongnized by inspector, and // it will never receive Network.requestWillBeSent. Most likely, this is an internal request // that we can safely fail. this._client._sendMayFail('Fetch.failRequest', { requestId: event.requestId, errorReason: 'Aborted', }); return; } if (event.request.url.startsWith('data:')) return; if (event.responseStatusCode || event.responseErrorReason) { const isRedirect = event.responseStatusCode && event.responseStatusCode >= 300 && event.responseStatusCode < 400; const request = this._requestIdToRequest.get(event.networkId!); const route = request?._routeForRedirectChain(); if (isRedirect || !route || !route._interceptingResponse) { this._client._sendMayFail('Fetch.continueRequest', { requestId: event.requestId }); return; } route._responseInterceptedCallback(event); return; } const requestId = event.networkId; const requestWillBeSentEvent = this._requestIdToRequestWillBeSentEvent.get(requestId); if (requestWillBeSentEvent) { this._onRequest(workerFrame, requestWillBeSentEvent, event); this._requestIdToRequestWillBeSentEvent.delete(requestId); } else { this._requestIdToRequestPausedEvent.set(requestId, event); } } _onRequest(workerFrame: frames.Frame | undefined, requestWillBeSentEvent: Protocol.Network.requestWillBeSentPayload, requestPausedEvent: Protocol.Fetch.requestPausedPayload | null) { if (requestWillBeSentEvent.request.url.startsWith('data:')) return; let redirectedFrom: InterceptableRequest | null = null; if (requestWillBeSentEvent.redirectResponse) { const request = this._requestIdToRequest.get(requestWillBeSentEvent.requestId); // If we connect late to the target, we could have missed the requestWillBeSent event. if (request) { this._handleRequestRedirect(request, requestWillBeSentEvent.redirectResponse, requestWillBeSentEvent.timestamp); redirectedFrom = request; } } let frame = requestWillBeSentEvent.frameId ? this._page._frameManager.frame(requestWillBeSentEvent.frameId) : workerFrame; // Requests from workers lack frameId, because we receive Network.requestWillBeSent // on the worker target. However, we receive Fetch.requestPaused on the page target, // and lack workerFrame there. Luckily, Fetch.requestPaused provides a frameId. if (!frame && requestPausedEvent && requestPausedEvent.frameId) frame = this._page._frameManager.frame(requestPausedEvent.frameId); // Check if it's main resource request interception (targetId === main frame id). if (!frame && requestWillBeSentEvent.frameId === (this._page._delegate as CRPage)._targetId) { // Main resource request for the page is being intercepted so the Frame is not created // yet. Precreate it here for the purposes of request interception. It will be updated // later as soon as the request continues and we receive frame tree from the page. frame = this._page._frameManager.frameAttached(requestWillBeSentEvent.frameId, null); } // CORS options request is generated by the network stack. If interception is enabled, // we accept all CORS options, assuming that this was intended when setting route. // // Note: it would be better to match the URL against interception patterns, but // that information is only available to the client. Perhaps we can just route to the client? if (requestPausedEvent && requestPausedEvent.request.method === 'OPTIONS' && this._page._needsRequestInterception()) { const requestHeaders = requestPausedEvent.request.headers; const responseHeaders: Protocol.Fetch.HeaderEntry[] = [ { name: 'Access-Control-Allow-Origin', value: requestHeaders['Origin'] || '*' }, { name: 'Access-Control-Allow-Methods', value: requestHeaders['Access-Control-Request-Method'] || 'GET, POST, OPTIONS, DELETE' }, { name: 'Access-Control-Allow-Credentials', value: 'true' } ]; if (requestHeaders['Access-Control-Request-Headers']) responseHeaders.push({ name: 'Access-Control-Allow-Headers', value: requestHeaders['Access-Control-Request-Headers'] }); this._client._sendMayFail('Fetch.fulfillRequest', { requestId: requestPausedEvent.requestId, responseCode: 204, responsePhrase: network.STATUS_TEXTS['204'], responseHeaders, body: '', }); return; } if (!frame) { if (requestPausedEvent) this._client._sendMayFail('Fetch.continueRequest', { requestId: requestPausedEvent.requestId }); return; } let route = null; if (requestPausedEvent) { // We do not support intercepting redirects. if (redirectedFrom) this._client._sendMayFail('Fetch.continueRequest', { requestId: requestPausedEvent.requestId }); else route = new RouteImpl(this._client, requestPausedEvent.requestId); } const isNavigationRequest = requestWillBeSentEvent.requestId === requestWillBeSentEvent.loaderId && requestWillBeSentEvent.type === 'Document'; const documentId = isNavigationRequest ? requestWillBeSentEvent.loaderId : undefined; const request = new InterceptableRequest({ frame, documentId, route, requestWillBeSentEvent, requestPausedEvent, redirectedFrom }); this._requestIdToRequest.set(requestWillBeSentEvent.requestId, request); this._page._frameManager.requestStarted(request.request, route || undefined); } _createResponse(request: InterceptableRequest, responsePayload: Protocol.Network.Response): network.Response { const getResponseBody = async () => { const response = await this._client.send('Network.getResponseBody', { requestId: request._requestId }); return Buffer.from(response.body, response.base64Encoded ? 'base64' : 'utf8'); }; const timingPayload = responsePayload.timing!; let timing: network.ResourceTiming; if (timingPayload) { timing = { startTime: (timingPayload.requestTime - request._timestamp + request._wallTime) * 1000, domainLookupStart: timingPayload.dnsStart, domainLookupEnd: timingPayload.dnsEnd, connectStart: timingPayload.connectStart, secureConnectionStart: timingPayload.sslStart, connectEnd: timingPayload.connectEnd, requestStart: timingPayload.sendStart, responseStart: timingPayload.receiveHeadersEnd, }; } else { timing = { startTime: request._wallTime * 1000, domainLookupStart: -1, domainLookupEnd: -1, connectStart: -1, secureConnectionStart: -1, connectEnd: -1, requestStart: -1, responseStart: -1, }; } const response = new network.Response(request.request, responsePayload.status, responsePayload.statusText, headersObjectToArray(responsePayload.headers), timing, getResponseBody, responsePayload.protocol); if (responsePayload?.remoteIPAddress && typeof responsePayload?.remotePort === 'number') { response._serverAddrFinished({ ipAddress: responsePayload.remoteIPAddress, port: responsePayload.remotePort, }); } else { response._serverAddrFinished(); } response._securityDetailsFinished({ protocol: responsePayload?.securityDetails?.protocol, subjectName: responsePayload?.securityDetails?.subjectName, issuer: responsePayload?.securityDetails?.issuer, validFrom: responsePayload?.securityDetails?.validFrom, validTo: responsePayload?.securityDetails?.validTo, }); this._responseExtraInfoTracker.processResponse(request._requestId, response, request.wasFulfilled()); return response; } _handleRequestRedirect(request: InterceptableRequest, responsePayload: Protocol.Network.Response, timestamp: number) { const response = this._createResponse(request, responsePayload); response._requestFinished((timestamp - request._timestamp) * 1000); this._requestIdToRequest.delete(request._requestId); if (request._interceptionId) this._attemptedAuthentications.delete(request._interceptionId); this._page._frameManager.requestReceivedResponse(response); this._page._frameManager.reportRequestFinished(request.request, response); } _onResponseReceivedExtraInfo(event: Protocol.Network.responseReceivedExtraInfoPayload) { this._responseExtraInfoTracker.responseReceivedExtraInfo(event); } _onResponseReceived(event: Protocol.Network.responseReceivedPayload) { this._responseExtraInfoTracker.responseReceived(event); const request = this._requestIdToRequest.get(event.requestId); // FileUpload sends a response without a matching request. if (!request) return; const response = this._createResponse(request, event.response); this._page._frameManager.requestReceivedResponse(response); } _onDataReceived(event: Protocol.Network.dataReceivedPayload) { const request = this._requestIdToRequest.get(event.requestId); if (request) request.request.responseSize.encodedBodySize += event.encodedDataLength; } _onLoadingFinished(event: Protocol.Network.loadingFinishedPayload) { this._responseExtraInfoTracker.loadingFinished(event); let request = this._requestIdToRequest.get(event.requestId); if (!request) request = this._maybeAdoptMainRequest(event.requestId); // For certain requestIds we never receive requestWillBeSent event. // @see https://crbug.com/750469 if (!request) return; // Under certain conditions we never get the Network.responseReceived // event from protocol. @see https://crbug.com/883475 const response = request.request._existingResponse(); if (response) { request.request.responseSize.transferSize = event.encodedDataLength; response._requestFinished(helper.secondsToRoundishMillis(event.timestamp - request._timestamp)); } this._requestIdToRequest.delete(request._requestId); if (request._interceptionId) this._attemptedAuthentications.delete(request._interceptionId); this._page._frameManager.reportRequestFinished(request.request, response); } _onLoadingFailed(event: Protocol.Network.loadingFailedPayload) { this._responseExtraInfoTracker.loadingFailed(event); let request = this._requestIdToRequest.get(event.requestId); if (!request) request = this._maybeAdoptMainRequest(event.requestId); // For certain requestIds we never receive requestWillBeSent event. // @see https://crbug.com/750469 if (!request) return; const response = request.request._existingResponse(); if (response) response._requestFinished(helper.secondsToRoundishMillis(event.timestamp - request._timestamp)); this._requestIdToRequest.delete(request._requestId); if (request._interceptionId) this._attemptedAuthentications.delete(request._interceptionId); request.request._setFailureText(event.errorText); this._page._frameManager.requestFailed(request.request, !!event.canceled); } private _maybeAdoptMainRequest(requestId: Protocol.Network.RequestId): InterceptableRequest | undefined { // OOPIF has a main request that starts in the parent session but finishes in the child session. if (!this._parentManager) return; const request = this._parentManager._requestIdToRequest.get(requestId); // Main requests have matching loaderId and requestId. if (!request || request._documentId !== requestId) return; this._requestIdToRequest.set(requestId, request); this._parentManager._requestIdToRequest.delete(requestId); if (request._interceptionId && this._parentManager._attemptedAuthentications.has(request._interceptionId)) { this._parentManager._attemptedAuthentications.delete(request._interceptionId); this._attemptedAuthentications.add(request._interceptionId); } return request; } } class InterceptableRequest { readonly request: network.Request; readonly _requestId: string; readonly _interceptionId: string | null; readonly _documentId: string | undefined; readonly _timestamp: number; readonly _wallTime: number; private _route: RouteImpl | null; private _redirectedFrom: InterceptableRequest | null; constructor(options: { frame: frames.Frame; documentId?: string; route: RouteImpl | null; requestWillBeSentEvent: Protocol.Network.requestWillBeSentPayload; requestPausedEvent: Protocol.Fetch.requestPausedPayload | null; redirectedFrom: InterceptableRequest | null; }) { const { frame, documentId, route, requestWillBeSentEvent, requestPausedEvent, redirectedFrom } = options; this._timestamp = requestWillBeSentEvent.timestamp; this._wallTime = requestWillBeSentEvent.wallTime; this._requestId = requestWillBeSentEvent.requestId; this._interceptionId = requestPausedEvent && requestPausedEvent.requestId; this._documentId = documentId; this._route = route; this._redirectedFrom = redirectedFrom; const { headers, method, url, postDataEntries = null, } = requestPausedEvent ? requestPausedEvent.request : requestWillBeSentEvent.request; const type = (requestWillBeSentEvent.type || '').toLowerCase(); let postDataBuffer = null; if (postDataEntries && postDataEntries.length && postDataEntries[0].bytes) postDataBuffer = Buffer.from(postDataEntries[0].bytes, 'base64'); this.request = new network.Request(frame, redirectedFrom?.request || null, documentId, url, type, method, postDataBuffer, headersObjectToArray(headers)); } _routeForRedirectChain(): RouteImpl | null { let request: InterceptableRequest = this; while (request._redirectedFrom) request = request._redirectedFrom; return request._route; } wasFulfilled() { return this._routeForRedirectChain()?._wasFulfilled || false; } } class RouteImpl implements network.RouteDelegate { private readonly _client: CRSession; private _interceptionId: string; private _responseInterceptedPromise: Promise<Protocol.Fetch.requestPausedPayload>; _responseInterceptedCallback: ((event: Protocol.Fetch.requestPausedPayload) => void) = () => {}; _interceptingResponse: boolean = false; _wasFulfilled = false; constructor(client: CRSession, interceptionId: string) { this._client = client; this._interceptionId = interceptionId; this._responseInterceptedPromise = new Promise(resolve => this._responseInterceptedCallback = resolve); } async responseBody(): Promise<Buffer> { const response = await this._client.send('Fetch.getResponseBody', { requestId: this._interceptionId! }); return Buffer.from(response.body, response.base64Encoded ? 'base64' : 'utf8'); } async continue(request: network.Request, overrides: types.NormalizedContinueOverrides): Promise<network.InterceptedResponse|null> { this._interceptingResponse = !!overrides.interceptResponse; // In certain cases, protocol will return error if the request was already canceled // or the page was closed. We should tolerate these errors. await this._client._sendMayFail('Fetch.continueRequest', { requestId: this._interceptionId!, url: overrides.url, headers: overrides.headers, method: overrides.method, postData: overrides.postData ? overrides.postData.toString('base64') : undefined }); if (!this._interceptingResponse) return null; const event = await this._responseInterceptedPromise; this._interceptionId = event.requestId; // FIXME: plumb status text from browser if (event.responseErrorReason) { this._client._sendMayFail('Fetch.continueRequest', { requestId: event.requestId }); throw new Error(`Request failed: ${event.responseErrorReason}`); } return new network.InterceptedResponse(request, event.responseStatusCode!, '', event.responseHeaders!); } async fulfill(response: types.NormalizedFulfillResponse) { this._wasFulfilled = true; const body = response.isBase64 ? response.body : Buffer.from(response.body).toString('base64'); // In certain cases, protocol will return error if the request was already canceled // or the page was closed. We should tolerate these errors. await this._client._sendMayFail('Fetch.fulfillRequest', { requestId: this._interceptionId!, responseCode: response.status, responsePhrase: network.STATUS_TEXTS[String(response.status)], responseHeaders: response.headers, body, }); } async abort(errorCode: string = 'failed') { const errorReason = errorReasons[errorCode]; assert(errorReason, 'Unknown error code: ' + errorCode); // In certain cases, protocol will return error if the request was already canceled // or the page was closed. We should tolerate these errors. await this._client._sendMayFail('Fetch.failRequest', { requestId: this._interceptionId!, errorReason }); } } const errorReasons: { [reason: string]: Protocol.Network.ErrorReason } = { 'aborted': 'Aborted', 'accessdenied': 'AccessDenied', 'addressunreachable': 'AddressUnreachable', 'blockedbyclient': 'BlockedByClient', 'blockedbyresponse': 'BlockedByResponse', 'connectionaborted': 'ConnectionAborted', 'connectionclosed': 'ConnectionClosed', 'connectionfailed': 'ConnectionFailed', 'connectionrefused': 'ConnectionRefused', 'connectionreset': 'ConnectionReset', 'internetdisconnected': 'InternetDisconnected', 'namenotresolved': 'NameNotResolved', 'timedout': 'TimedOut', 'failed': 'Failed', }; type RequestInfo = { requestId: string, requestWillBeSentExtraInfo: Protocol.Network.requestWillBeSentExtraInfoPayload[], responseReceivedExtraInfo: Protocol.Network.responseReceivedExtraInfoPayload[], responses: network.Response[], loadingFinished?: Protocol.Network.loadingFinishedPayload, loadingFailed?: Protocol.Network.loadingFailedPayload, sawResponseWithoutConnectionId: boolean }; // This class aligns responses with response headers from extra info: // - Network.requestWillBeSent, Network.responseReceived, Network.loadingFinished/loadingFailed are // dispatched using one channel. // - Network.requestWillBeSentExtraInfo and Network.responseReceivedExtraInfo are dispatches on // another channel. Those channels are not associated, so events come in random order. // // This class will associate responses with the new headers. These extra info headers will become // available to client reliably upon requestfinished event only. It consumes CDP // signals on one end and processResponse(network.Response) signals on the other hands. It then makes // sure that responses have all the extra headers in place by the time request finises. // // The shape of the instrumentation API is deliberately following the CDP, so that it // what clear what is called when and what this means to the tracker without extra // documentation. class ResponseExtraInfoTracker { private _requests = new Map<string, RequestInfo>(); requestWillBeSent(event: Protocol.Network.requestWillBeSentPayload) { const info = this._requests.get(event.requestId); if (info && event.redirectResponse) this._innerResponseReceived(info, event.redirectResponse); else this._getOrCreateEntry(event.requestId); } requestWillBeSentExtraInfo(event: Protocol.Network.requestWillBeSentExtraInfoPayload) { const info = this._getOrCreateEntry(event.requestId); if (!info) return; info.requestWillBeSentExtraInfo.push(event); this._patchHeaders(info, info.requestWillBeSentExtraInfo.length - 1); } responseReceived(event: Protocol.Network.responseReceivedPayload) { const info = this._requests.get(event.requestId); if (!info) return; this._innerResponseReceived(info, event.response); } private _innerResponseReceived(info: RequestInfo, response: Protocol.Network.Response) { if (!response.connectionId) { // Starting with this response we no longer can guarantee that response and extra info correspond to the same index. info.sawResponseWithoutConnectionId = true; } } responseReceivedExtraInfo(event: Protocol.Network.responseReceivedExtraInfoPayload) { const info = this._getOrCreateEntry(event.requestId); info.responseReceivedExtraInfo.push(event); this._patchHeaders(info, info.responseReceivedExtraInfo.length - 1); this._checkFinished(info); } processResponse(requestId: string, response: network.Response, wasFulfilled: boolean) { // We are not interested in ExtraInfo tracking for fulfilled requests, our Blink // headers are the ones that contain fulfilled headers. if (wasFulfilled) { this._stopTracking(requestId); return; } const info = this._requests.get(requestId); if (!info || info.sawResponseWithoutConnectionId) return; response.setWillReceiveExtraHeaders(); info.responses.push(response); this._patchHeaders(info, info.responses.length - 1); } loadingFinished(event: Protocol.Network.loadingFinishedPayload) { const info = this._requests.get(event.requestId); if (!info) return; info.loadingFinished = event; this._checkFinished(info); } loadingFailed(event: Protocol.Network.loadingFailedPayload) { const info = this._requests.get(event.requestId); if (!info) return; info.loadingFailed = event; this._checkFinished(info); } _getOrCreateEntry(requestId: string): RequestInfo { let info = this._requests.get(requestId); if (!info) { info = { requestId: requestId, requestWillBeSentExtraInfo: [], responseReceivedExtraInfo: [], responses: [], sawResponseWithoutConnectionId: false }; this._requests.set(requestId, info); } return info; } private _patchHeaders(info: RequestInfo, index: number) { const response = info.responses[index]; const requestExtraInfo = info.requestWillBeSentExtraInfo[index]; if (response && requestExtraInfo) response.setRawRequestHeaders(headersObjectToArray(requestExtraInfo.headers, '\n')); const responseExtraInfo = info.responseReceivedExtraInfo[index]; if (response && responseExtraInfo) response.setRawResponseHeaders(headersObjectToArray(responseExtraInfo.headers, '\n')); } private _checkFinished(info: RequestInfo) { if (!info.loadingFinished && !info.loadingFailed) return; if (info.responses.length <= info.responseReceivedExtraInfo.length) { // We have extra info for each response. // We could have more extra infos because we stopped collecting responses at some point. this._stopTracking(info.requestId); return; } // We are not done yet. } private _stopTracking(requestId: string) { this._requests.delete(requestId); } }
src/server/chromium/crNetworkManager.ts
1
https://github.com/microsoft/playwright/commit/cfe7c1a7e3ca96843b0efce4e74bd87ee6b085ae
[ 0.0016273708315566182, 0.0002378202771069482, 0.00016135736950673163, 0.00017220631707459688, 0.00024552945978939533 ]
{ "id": 10, "code_window": [ " resp.end();\n", " });\n", " const response = await page.goto(server.PREFIX + '/chunked-simplezip.json');\n", " const sizes = await response.request().sizes();\n", " expect(sizes.responseBodySize).toBe(fs.statSync(asset('simplezip.json')).size);\n", "});\n", "\n", "it('should have the correct responseBodySize with gzip compression', async ({ page, server, asset }, testInfo) => {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " // The actual file size is 5100 bytes. The extra 75 bytes are coming from the chunked encoding headers and end bytes.\n", " if (browserName === 'webkit')\n", " // It should be 5175 there. On the actual network response, the body has a size of 5175.\n", " expect(sizes.responseBodySize).toBe(5173);\n", " else\n", " expect(sizes.responseBodySize).toBe(5175);\n" ], "file_path": "tests/page/page-network-sizes.spec.ts", "type": "replace", "edit_start_line_idx": 90 }
Playwright Copyright (c) Microsoft Corporation This software contains code derived from the Puppeteer project (https://github.com/puppeteer/puppeteer), available under the Apache 2.0 license (https://github.com/puppeteer/puppeteer/blob/master/LICENSE).
NOTICE
0
https://github.com/microsoft/playwright/commit/cfe7c1a7e3ca96843b0efce4e74bd87ee6b085ae
[ 0.00017723790369927883, 0.00017723790369927883, 0.00017723790369927883, 0.00017723790369927883, 0 ]
{ "id": 10, "code_window": [ " resp.end();\n", " });\n", " const response = await page.goto(server.PREFIX + '/chunked-simplezip.json');\n", " const sizes = await response.request().sizes();\n", " expect(sizes.responseBodySize).toBe(fs.statSync(asset('simplezip.json')).size);\n", "});\n", "\n", "it('should have the correct responseBodySize with gzip compression', async ({ page, server, asset }, testInfo) => {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " // The actual file size is 5100 bytes. The extra 75 bytes are coming from the chunked encoding headers and end bytes.\n", " if (browserName === 'webkit')\n", " // It should be 5175 there. On the actual network response, the body has a size of 5175.\n", " expect(sizes.responseBodySize).toBe(5173);\n", " else\n", " expect(sizes.responseBodySize).toBe(5175);\n" ], "file_path": "tests/page/page-network-sizes.spec.ts", "type": "replace", "edit_start_line_idx": 90 }
{ "compilerOptions": { "allowJs": true, "checkJs": false, "noEmit": true, "moduleResolution": "node", "target": "ESNext", "strictNullChecks": false, "strictBindCallApply": true, "allowSyntheticDefaultImports": true, }, "include": ["**/*.spec.js", "**/*.ts", "index.d.ts"] }
tests/tsconfig.json
0
https://github.com/microsoft/playwright/commit/cfe7c1a7e3ca96843b0efce4e74bd87ee6b085ae
[ 0.0001718046551104635, 0.00017126771854236722, 0.0001707307674223557, 0.00017126771854236722, 5.369438440538943e-7 ]
{ "id": 10, "code_window": [ " resp.end();\n", " });\n", " const response = await page.goto(server.PREFIX + '/chunked-simplezip.json');\n", " const sizes = await response.request().sizes();\n", " expect(sizes.responseBodySize).toBe(fs.statSync(asset('simplezip.json')).size);\n", "});\n", "\n", "it('should have the correct responseBodySize with gzip compression', async ({ page, server, asset }, testInfo) => {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " // The actual file size is 5100 bytes. The extra 75 bytes are coming from the chunked encoding headers and end bytes.\n", " if (browserName === 'webkit')\n", " // It should be 5175 there. On the actual network response, the body has a size of 5175.\n", " expect(sizes.responseBodySize).toBe(5173);\n", " else\n", " expect(sizes.responseBodySize).toBe(5175);\n" ], "file_path": "tests/page/page-network-sizes.spec.ts", "type": "replace", "edit_start_line_idx": 90 }
/* http://jmblog.github.com/color-themes-for-google-code-highlightjs */ /* Tomorrow Comment */ .hljs-comment, .hljs-quote { color: #8e908c; } /* Tomorrow Red */ .hljs-variable, .hljs-template-variable, .hljs-tag, .hljs-name, .hljs-selector-id, .hljs-selector-class, .hljs-regexp, .hljs-deletion { color: #c82829; } /* Tomorrow Orange */ .hljs-number, .hljs-built_in, .hljs-builtin-name, .hljs-literal, .hljs-type, .hljs-params, .hljs-meta, .hljs-link { color: #f5871f; } /* Tomorrow Yellow */ .hljs-attribute { color: #eab700; } /* Tomorrow Green */ .hljs-string, .hljs-symbol, .hljs-bullet, .hljs-addition { color: #718c00; } /* Tomorrow Blue */ .hljs-title, .hljs-section { color: #4271ae; } /* Tomorrow Purple */ .hljs-keyword, .hljs-selector-tag { color: #8959a8; } .hljs { display: block; overflow-x: auto; background: white; color: #4d4d4c; padding: 0.5em; } .hljs-emphasis { font-style: italic; } .hljs-strong { font-weight: bold; }
src/third_party/highlightjs/highlightjs/tomorrow.css
0
https://github.com/microsoft/playwright/commit/cfe7c1a7e3ca96843b0efce4e74bd87ee6b085ae
[ 0.00017663612379692495, 0.00017492206825409085, 0.0001716936385491863, 0.00017529769684188068, 0.0000015387588518933626 ]
{ "id": 0, "code_window": [ " };\n", " }\n", "\n", " shouldComponentUpdate() {\n", " return true;\n", " }\n", "\n", " handleHover() {\n", " this.setState({\n", " hovered: true\n", " });\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "lib/components/tab.js", "type": "replace", "edit_start_line_idx": 16 }
/* global Blob,URL,requestAnimationFrame */ import React from 'react'; import {Terminal} from 'xterm'; import * as fit from 'xterm/lib/addons/fit/fit'; import {clipboard} from 'electron'; import * as Color from 'color'; import {PureComponent} from '../base-components'; import terms from '../terms'; import processClipboard from '../utils/paste'; Terminal.applyAddon(fit); // map old hterm constants to xterm.js const CURSOR_STYLES = { BEAM: 'bar', UNDERLINE: 'underline', BLOCK: 'block' }; const getTermOptions = props => { // Set a background color only if it is opaque const backgroundColor = Color(props.backgroundColor).alpha() < 1 ? 'transparent' : props.backgroundColor; return { macOptionIsMeta: props.modifierKeys.altIsMeta, cursorStyle: CURSOR_STYLES[props.cursorShape], cursorBlink: props.cursorBlink, fontFamily: props.fontFamily, fontSize: props.fontSize, allowTransparency: true, theme: { foreground: props.foregroundColor, background: backgroundColor, cursor: props.cursorColor, cursorAccent: props.cursorAccentColor, selection: props.selectionColor, black: props.colors.black, red: props.colors.red, green: props.colors.green, yellow: props.colors.yellow, blue: props.colors.blue, magenta: props.colors.magenta, cyan: props.colors.cyan, white: props.colors.white, brightBlack: props.colors.lightBlack, brightRed: props.colors.lightRed, brightGreen: props.colors.lightGreen, brightYellow: props.colors.lightYellow, brightBlue: props.colors.lightBlue, brightMagenta: props.colors.lightMagenta, brightCyan: props.colors.lightCyan, brightWhite: props.colors.lightWhite } }; }; export default class Term extends PureComponent { constructor(props) { super(props); props.ref_(props.uid, this); this.termRef = null; this.termWrapperRef = null; this.termRect = null; this.onOpen = this.onOpen.bind(this); this.onWindowResize = this.onWindowResize.bind(this); this.onWindowPaste = this.onWindowPaste.bind(this); this.onTermRef = this.onTermRef.bind(this); this.onTermWrapperRef = this.onTermWrapperRef.bind(this); this.onMouseUp = this.onMouseUp.bind(this); this.termOptions = {}; } componentDidMount() { const {props} = this; this.termOptions = getTermOptions(props); this.term = props.term || new Terminal(this.termOptions); this.term.attachCustomKeyEventHandler(this.keyboardHandler); this.term.open(this.termRef); if (props.term) { //We need to set options again after reattaching an existing term Object.keys(this.termOptions).forEach(option => this.term.setOption(option, this.termOptions[option])); } this.onOpen(this.termOptions); if (props.onTitle) { this.term.on('title', props.onTitle); } if (props.onActive) { this.term.on('focus', () => { // xterm@2 emits this event 2 times. Will be fixed in xterm@3. if (!this.props.isTermActive) { props.onActive(); } }); } if (props.onData) { this.term.on('data', props.onData); } if (props.onResize) { this.term.on('resize', ({cols, rows}) => { props.onResize(cols, rows); }); } if (props.onCursorMove) { this.term.on('cursormove', () => { const cursorFrame = { x: this.term.buffer.x * this.term.renderer.dimensions.actualCellWidth, y: this.term.buffer.y * this.term.renderer.dimensions.actualCellHeight, width: this.term.renderer.dimensions.actualCellWidth, height: this.term.renderer.dimensions.actualCellHeight, col: this.term.buffer.y, row: this.term.buffer.x }; props.onCursorMove(cursorFrame); }); } window.addEventListener('resize', this.onWindowResize, { passive: true }); window.addEventListener('paste', this.onWindowPaste, { capture: true }); terms[this.props.uid] = this; } onOpen(termOptions) { // we need to delay one frame so that aphrodite styles // get applied and we can make an accurate measurement // of the container width and height requestAnimationFrame(() => { // at this point it would make sense for character // measurement to have taken place but it seems that // xterm.js might be doing this asynchronously, so // we force it instead // eslint-disable-next-line no-debugger //debugger; this.term.charMeasure.measure(termOptions); this.fitResize(); }); } getTermDocument() { // eslint-disable-next-line no-console console.warn( 'The underlying terminal engine of Hyper no longer ' + 'uses iframes with individual `document` objects for each ' + 'terminal instance. This method call is retained for ' + "backwards compatibility reasons. It's ok to attach directly" + 'to the `document` object of the main `window`.' ); return document; } onWindowResize() { this.fitResize(); } // intercepting paste event for any necessary processing of // clipboard data, if result is falsy, paste event continues onWindowPaste(e) { if (!this.props.isTermActive) return; const processed = processClipboard(); if (processed) { e.preventDefault(); e.stopPropagation(); this.term.send(processed); } } onMouseUp(e) { if (this.props.quickEdit && e.button === 2) { if (this.term.hasSelection()) { clipboard.writeText(this.term.getSelection()); this.term.clearSelection(); } else { document.execCommand('paste'); } } else if (this.props.copyOnSelect && this.term.hasSelection()) { clipboard.writeText(this.term.getSelection()); } } write(data) { this.term.write(data); } focus() { this.term.focus(); } clear() { this.term.clear(); } reset() { this.term.reset(); } resize(cols, rows) { this.term.resize(cols, rows); } selectAll() { this.term.selectAll(); } fitResize() { if (!this.termWrapperRef) { return; } this.term.fit(); } keyboardHandler(e) { // Has Mousetrap flagged this event as a command? return !e.catched; } componentWillReceiveProps(nextProps) { if (!this.props.cleared && nextProps.cleared) { this.clear(); } const nextTermOptions = getTermOptions(nextProps); // Update only options that have changed. Object.keys(nextTermOptions) .filter(option => option !== 'theme' && nextTermOptions[option] !== this.termOptions[option]) .forEach(option => this.term.setOption(option, nextTermOptions[option])); // Do we need to update theme? const shouldUpdateTheme = !this.termOptions.theme || Object.keys(nextTermOptions.theme).some(option => { nextTermOptions.theme[option] !== this.termOptions.theme[option]; }); if (shouldUpdateTheme) { this.term.setOption('theme', nextTermOptions.theme); } this.termOptions = nextTermOptions; if (!this.props.isTermActive && nextProps.isTermActive) { requestAnimationFrame(() => { this.term.charMeasure.measure(this.termOptions); this.fitResize(); }); } if (this.props.fontSize !== nextProps.fontSize || this.props.fontFamily !== nextProps.fontFamily) { // invalidate xterm cache about how wide each // character is this.term.charMeasure.measure(this.termOptions); // resize to fit the container this.fitResize(); } if (nextProps.rows !== this.props.rows || nextProps.cols !== this.props.cols) { this.resize(nextProps.cols, nextProps.rows); } } onTermWrapperRef(component) { this.termWrapperRef = component; } onTermRef(component) { this.termRef = component; } componentWillUnmount() { terms[this.props.uid] = null; this.props.ref_(this.props.uid, null); // to clean up the terminal, we remove the listeners // instead of invoking `destroy`, since it will make the // term insta un-attachable in the future (which we need // to do in case of splitting, see `componentDidMount` ['title', 'focus', 'data', 'resize', 'cursormove'].forEach(type => this.term.removeAllListeners(type)); window.removeEventListener('resize', this.onWindowResize, { passive: true }); window.removeEventListener('paste', this.onWindowPaste, { capture: true }); } template(css) { return ( <div className={css('fit', this.props.isTermActive && 'active')} style={{padding: this.props.padding}} onMouseUp={this.onMouseUp} > {this.props.customChildrenBefore} <div ref={this.onTermWrapperRef} className={css('fit', 'wrapper')}> <div ref={this.onTermRef} className={css('fit', 'term')} /> </div> {this.props.customChildren} </div> ); } styles() { return { fit: { display: 'block', width: '100%', height: '100%' }, wrapper: { // TODO: decide whether to keep this or not based on // understanding what xterm-selection is for overflow: 'hidden' }, term: {} }; } }
lib/components/term.js
1
https://github.com/vercel/hyper/commit/887fb5ac1a56d50d2f7ab694b8b1e92a2cebc101
[ 0.00040570643614046276, 0.00018039392307400703, 0.00016365871124435216, 0.00016927537217270583, 0.000045662654883926734 ]
{ "id": 0, "code_window": [ " };\n", " }\n", "\n", " shouldComponentUpdate() {\n", " return true;\n", " }\n", "\n", " handleHover() {\n", " this.setState({\n", " hovered: true\n", " });\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "lib/components/tab.js", "type": "replace", "edit_start_line_idx": 16 }
import React from 'react'; import {PureComponent} from '../base-components'; import {decorate, getTabsProps} from '../utils/plugins'; import Tabs_ from './tabs'; const Tabs = decorate(Tabs_, 'Tabs'); export default class Header extends PureComponent { constructor() { super(); this.onChangeIntent = this.onChangeIntent.bind(this); this.handleHeaderMouseDown = this.handleHeaderMouseDown.bind(this); this.handleHamburgerMenuClick = this.handleHamburgerMenuClick.bind(this); this.handleMaximizeClick = this.handleMaximizeClick.bind(this); this.handleMinimizeClick = this.handleMinimizeClick.bind(this); this.handleCloseClick = this.handleCloseClick.bind(this); } onChangeIntent(active) { // we ignore clicks if they're a byproduct of a drag // motion to move the window if (window.screenX !== this.headerMouseDownWindowX || window.screenY !== this.headerMouseDownWindowY) { return; } this.props.onChangeTab(active); } handleHeaderMouseDown(ev) { // the hack of all hacks, this prevents the term // iframe from losing focus, for example, when // the user drags the nav around ev.preventDefault(); // persist start positions of a potential drag motion // to differentiate dragging from clicking this.headerMouseDownWindowX = window.screenX; this.headerMouseDownWindowY = window.screenY; } handleHamburgerMenuClick(event) { let {right: x, bottom: y} = event.currentTarget.getBoundingClientRect(); x -= 15; // to compensate padding y -= 12; // ^ same this.props.openHamburgerMenu({x, y}); } handleMaximizeClick() { if (this.props.maximized) { this.props.unmaximize(); } else { this.props.maximize(); } } handleMinimizeClick() { this.props.minimize(); } handleCloseClick() { this.props.close(); } componentWillUnmount() { delete this.clicks; clearTimeout(this.clickTimer); } getWindowHeaderConfig() { const {showHamburgerMenu, showWindowControls} = this.props; const defaults = { hambMenu: process.platform === 'win32', // show by default on windows winCtrls: !this.props.isMac // show by default on Windows and Linux }; // don't allow the user to change defaults on macOS if (this.props.isMac) { return defaults; } return { hambMenu: showHamburgerMenu === '' ? defaults.hambMenu : showHamburgerMenu, winCtrls: showWindowControls === '' ? defaults.winCtrls : showWindowControls }; } template(css) { const {isMac} = this.props; const props = getTabsProps(this.props, { tabs: this.props.tabs, borderColor: this.props.borderColor, onClose: this.props.onCloseTab, onChange: this.onChangeIntent }); const {borderColor} = props; let title = 'Hyper'; if (props.tabs.length === 1 && props.tabs[0].title) { // if there's only one tab we use its title as the window title title = props.tabs[0].title; } const {hambMenu, winCtrls} = this.getWindowHeaderConfig(); const left = winCtrls === 'left'; const maxButtonHref = this.props.maximized ? './renderer/assets/icons.svg#restore-window' : './renderer/assets/icons.svg#maximize-window'; return ( <header className={css('header', isMac && 'headerRounded')} onMouseDown={this.handleHeaderMouseDown} onDoubleClick={this.handleMaximizeClick} > {!isMac && ( <div className={css('windowHeader', props.tabs.length > 1 && 'windowHeaderWithBorder')} style={{borderColor}}> {hambMenu && ( <svg className={css('shape', (left && 'hamburgerMenuRight') || 'hamburgerMenuLeft')} onClick={this.handleHamburgerMenuClick} > <use xlinkHref="./renderer/assets/icons.svg#hamburger-menu" /> </svg> )} <span className={css('appTitle')}>{title}</span> {winCtrls && ( <div className={css('windowControls', left && 'windowControlsLeft')}> <svg className={css('shape', left && 'minimizeWindowLeft')} onClick={this.handleMinimizeClick}> <use xlinkHref="./renderer/assets/icons.svg#minimize-window" /> </svg> <svg className={css('shape', left && 'maximizeWindowLeft')} onClick={this.handleMaximizeClick}> <use xlinkHref={maxButtonHref} /> </svg> <svg className={css('shape', 'closeWindow', left && 'closeWindowLeft')} onClick={this.handleCloseClick}> <use xlinkHref="./renderer/assets/icons.svg#close-window" /> </svg> </div> )} </div> )} {this.props.customChildrenBefore} <Tabs {...props} /> {this.props.customChildren} </header> ); } styles() { return { header: { position: 'fixed', top: '1px', left: '1px', right: '1px', zIndex: '100' }, headerRounded: { borderTopLeftRadius: '4px', borderTopRightRadius: '4px' }, windowHeader: { height: '34px', width: '100%', position: 'fixed', top: '1px', left: '1px', right: '1px', WebkitAppRegion: 'drag', WebkitUserSelect: 'none', display: 'flex', justifyContent: 'center', alignItems: 'center' }, windowHeaderWithBorder: { borderColor: '#ccc', borderBottomStyle: 'solid', borderBottomWidth: '1px' }, appTitle: { fontSize: '12px' }, shape: { width: '40px', height: '34px', padding: '12px 15px 12px 15px', WebkitAppRegion: 'no-drag', color: '#FFFFFF', opacity: 0.5, shapeRendering: 'crispEdges', ':hover': { opacity: 1 }, ':active': { opacity: 0.3 } }, hamburgerMenuLeft: { position: 'fixed', top: '0', left: '0' }, hamburgerMenuRight: { position: 'fixed', top: '0', right: '0' }, windowControls: { display: 'flex', width: '120px', height: '34px', justifyContent: 'space-between', position: 'fixed', right: '0' }, windowControlsLeft: {left: '0px'}, closeWindowLeft: {order: 1}, minimizeWindowLeft: {order: 2}, maximizeWindowLeft: {order: 3}, closeWindow: {':hover': {color: '#FE354E'}, ':active': {color: '#FE354E'}} }; } }
lib/components/header.js
0
https://github.com/vercel/hyper/commit/887fb5ac1a56d50d2f7ab694b8b1e92a2cebc101
[ 0.0024176742881536484, 0.0003288429870735854, 0.00016533795860596, 0.00016908231191337109, 0.0005044013960286975 ]
{ "id": 0, "code_window": [ " };\n", " }\n", "\n", " shouldComponentUpdate() {\n", " return true;\n", " }\n", "\n", " handleHover() {\n", " this.setState({\n", " hovered: true\n", " });\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "lib/components/tab.js", "type": "replace", "edit_start_line_idx": 16 }
import {php_escapeshellcmd as escapeShellCmd} from 'php-escape-shell'; import last from '../utils/array'; import isExecutable from '../utils/file'; import getRootGroups from '../selectors'; import findBySession from '../utils/term-groups'; import notify from '../utils/notify'; import rpc from '../rpc'; import {requestSession, sendSessionData, setActiveSession} from '../actions/sessions'; import { UI_FONT_SIZE_SET, UI_FONT_SIZE_INCR, UI_FONT_SIZE_DECR, UI_FONT_SIZE_RESET, UI_FONT_SMOOTHING_SET, UI_MOVE_LEFT, UI_MOVE_RIGHT, UI_MOVE_TO, UI_MOVE_NEXT_PANE, UI_MOVE_PREV_PANE, UI_WINDOW_GEOMETRY_CHANGED, UI_WINDOW_MOVE, UI_OPEN_FILE, UI_CONTEXTMENU_OPEN, UI_COMMAND_EXEC } from '../constants/ui'; import {setActiveGroup} from './term-groups'; const {stat} = window.require('fs'); export function openContextMenu(uid, selection) { return (dispatch, getState) => { dispatch({ type: UI_CONTEXTMENU_OPEN, uid, effect() { const state = getState(); const show = !state.ui.quickEdit; if (show) { rpc.emit('open context menu', selection); } } }); }; } export function increaseFontSize() { return (dispatch, getState) => { dispatch({ type: UI_FONT_SIZE_INCR, effect() { const state = getState(); const old = state.ui.fontSizeOverride || state.ui.fontSize; const value = old + 1; dispatch({ type: UI_FONT_SIZE_SET, value }); } }); }; } export function decreaseFontSize() { return (dispatch, getState) => { dispatch({ type: UI_FONT_SIZE_DECR, effect() { const state = getState(); const old = state.ui.fontSizeOverride || state.ui.fontSize; const value = old - 1; dispatch({ type: UI_FONT_SIZE_SET, value }); } }); }; } export function resetFontSize() { return { type: UI_FONT_SIZE_RESET }; } export function setFontSmoothing() { return dispatch => { setTimeout(() => { const devicePixelRatio = window.devicePixelRatio; const fontSmoothing = devicePixelRatio < 2 ? 'subpixel-antialiased' : 'antialiased'; dispatch({ type: UI_FONT_SMOOTHING_SET, fontSmoothing }); }, 100); }; } export function windowGeometryUpdated() { return { type: UI_WINDOW_GEOMETRY_CHANGED }; } // Find all sessions that are below the given // termGroup uid in the hierarchy: const findChildSessions = (termGroups, uid) => { const group = termGroups[uid]; if (group.sessionUid) { return [uid]; } return group.children.reduce((total, childUid) => total.concat(findChildSessions(termGroups, childUid)), []); }; // Get the index of the next or previous group, // depending on the movement direction: const getNeighborIndex = (groups, uid, type) => { if (type === UI_MOVE_NEXT_PANE) { return (groups.indexOf(uid) + 1) % groups.length; } return (groups.indexOf(uid) + groups.length - 1) % groups.length; }; function moveToNeighborPane(type) { return () => (dispatch, getState) => { dispatch({ type, effect() { const {sessions, termGroups} = getState(); const {uid} = findBySession(termGroups, sessions.activeUid); const childGroups = findChildSessions(termGroups.termGroups, termGroups.activeRootGroup); if (childGroups.length === 1) { //eslint-disable-next-line no-console console.log('ignoring move for single group'); } else { const index = getNeighborIndex(childGroups, uid, type); const {sessionUid} = termGroups.termGroups[childGroups[index]]; dispatch(setActiveSession(sessionUid)); } } }); }; } export const moveToNextPane = moveToNeighborPane(UI_MOVE_NEXT_PANE); export const moveToPreviousPane = moveToNeighborPane(UI_MOVE_PREV_PANE); const getGroupUids = state => { const rootGroups = getRootGroups(state); return rootGroups.map(({uid}) => uid); }; export function moveLeft() { return (dispatch, getState) => { dispatch({ type: UI_MOVE_LEFT, effect() { const state = getState(); const uid = state.termGroups.activeRootGroup; const groupUids = getGroupUids(state); const index = groupUids.indexOf(uid); const next = groupUids[index - 1] || last(groupUids); if (!next || uid === next) { //eslint-disable-next-line no-console console.log('ignoring left move action'); } else { dispatch(setActiveGroup(next)); } } }); }; } export function moveRight() { return (dispatch, getState) => { dispatch({ type: UI_MOVE_RIGHT, effect() { const state = getState(); const groupUids = getGroupUids(state); const uid = state.termGroups.activeRootGroup; const index = groupUids.indexOf(uid); const next = groupUids[index + 1] || groupUids[0]; if (!next || uid === next) { //eslint-disable-next-line no-console console.log('ignoring right move action'); } else { dispatch(setActiveGroup(next)); } } }); }; } export function moveTo(i) { return (dispatch, getState) => { if (i === 'last') { // Finding last tab index const {termGroups} = getState().termGroups; i = Object.keys(termGroups) .map(uid => termGroups[uid]) .filter(({parentUid}) => !parentUid).length - 1; } dispatch({ type: UI_MOVE_TO, index: i, effect() { const state = getState(); const groupUids = getGroupUids(state); const uid = state.termGroups.activeRootGroup; if (uid === groupUids[i]) { //eslint-disable-next-line no-console console.log('ignoring same uid'); } else if (groupUids[i]) { dispatch(setActiveGroup(groupUids[i])); } else { //eslint-disable-next-line no-console console.log('ignoring inexistent index', i); } } }); }; } export function windowMove() { return dispatch => { dispatch({ type: UI_WINDOW_MOVE, effect() { dispatch(setFontSmoothing()); } }); }; } export function windowGeometryChange() { return dispatch => { dispatch({ type: UI_WINDOW_MOVE, effect() { dispatch(setFontSmoothing()); } }); }; } export function openFile(path) { return dispatch => { dispatch({ type: UI_OPEN_FILE, effect() { stat(path, (err, stats) => { if (err) { //eslint-disable-next-line no-console console.error(err.stack); notify('Unable to open path', `"${path}" doesn't exist.`); } else { let command = escapeShellCmd(path).replace(/ /g, '\\ '); if (stats.isDirectory()) { command = `cd ${command}\n`; } else if (stats.isFile() && isExecutable(stats)) { command += '\n'; } rpc.once('session add', ({uid}) => { rpc.once('session data', () => { dispatch(sendSessionData(uid, command)); }); }); } dispatch(requestSession()); }); } }); }; } export function execCommand(command, fn, e) { return dispatch => dispatch({ type: UI_COMMAND_EXEC, command, effect() { if (fn) { fn(e); } else { rpc.emit('command', command); } } }); }
lib/actions/ui.js
0
https://github.com/vercel/hyper/commit/887fb5ac1a56d50d2f7ab694b8b1e92a2cebc101
[ 0.00019964954117313027, 0.00017255585407838225, 0.0001650286139920354, 0.00016992821474559605, 0.000007569752142444486 ]
{ "id": 0, "code_window": [ " };\n", " }\n", "\n", " shouldComponentUpdate() {\n", " return true;\n", " }\n", "\n", " handleHover() {\n", " this.setState({\n", " hovered: true\n", " });\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "lib/components/tab.js", "type": "replace", "edit_start_line_idx": 16 }
module.exports = (commandKeys, execCommand) => { const isMac = process.platform === 'darwin'; return { label: isMac ? 'Shell' : 'File', submenu: [ { label: 'New Tab', accelerator: commandKeys['tab:new'], click(item, focusedWindow) { execCommand('tab:new', focusedWindow); } }, { label: 'New Window', accelerator: commandKeys['window:new'], click(item, focusedWindow) { execCommand('window:new', focusedWindow); } }, { type: 'separator' }, { label: 'Split Horizontally', accelerator: commandKeys['pane:splitHorizontal'], click(item, focusedWindow) { execCommand('pane:splitHorizontal', focusedWindow); } }, { label: 'Split Vertically', accelerator: commandKeys['pane:splitVertical'], click(item, focusedWindow) { execCommand('pane:splitVertical', focusedWindow); } }, { type: 'separator' }, { label: 'Close', accelerator: commandKeys['pane:close'], click(item, focusedWindow) { execCommand('pane:close', focusedWindow); } }, { label: isMac ? 'Close Window' : 'Quit', role: 'close', accelerator: commandKeys['window:close'] } ] }; };
app/menus/menus/shell.js
0
https://github.com/vercel/hyper/commit/887fb5ac1a56d50d2f7ab694b8b1e92a2cebc101
[ 0.00017361331265419722, 0.00017288204981014132, 0.00017166203178931028, 0.00017304596258327365, 6.624649699915608e-7 ]
{ "id": 1, "code_window": [ " if (props.term) {\n", " //We need to set options again after reattaching an existing term\n", " Object.keys(this.termOptions).forEach(option => this.term.setOption(option, this.termOptions[option]));\n", " }\n", "\n", " this.onOpen(this.termOptions);\n", "\n", " if (props.onTitle) {\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " if (this.props.isTermActive) {\n", " this.term.focus();\n", " }\n" ], "file_path": "lib/components/term.js", "type": "add", "edit_start_line_idx": 82 }
import React from 'react'; import {PureComponent} from '../base-components'; export default class Tab extends PureComponent { constructor() { super(); this.handleHover = this.handleHover.bind(this); this.handleBlur = this.handleBlur.bind(this); this.handleClick = this.handleClick.bind(this); this.state = { hovered: false }; } shouldComponentUpdate() { return true; } handleHover() { this.setState({ hovered: true }); } handleBlur() { this.setState({ hovered: false }); } handleClick(event) { const isLeftClick = event.nativeEvent.which === 1; const isMiddleClick = event.nativeEvent.which === 2; if (isLeftClick && !this.props.isActive) { this.props.onSelect(); } else if (isMiddleClick) { this.props.onClose(); } } template(css) { const {isActive, isFirst, isLast, borderColor, hasActivity} = this.props; const {hovered} = this.state; return ( <li onMouseEnter={this.handleHover} onMouseLeave={this.handleBlur} onClick={this.props.onClick} style={{borderColor}} className={css( 'tab', isFirst && 'first', isActive && 'active', isFirst && isActive && 'firstActive', hasActivity && 'hasActivity' )} > {this.props.customChildrenBefore} <span className={css('text', isLast && 'textLast', isActive && 'textActive')} onClick={this.handleClick}> <span title={this.props.text} className={css('textInner')}> {this.props.text} </span> </span> <i className={css('icon', hovered && 'iconHovered')} onClick={this.props.onClose}> <svg className={css('shape')}> <use xlinkHref="./renderer/assets/icons.svg#close-tab" /> </svg> </i> {this.props.customChildren} </li> ); } styles() { return { tab: { color: '#ccc', borderColor: '#ccc', borderBottomWidth: 1, borderBottomStyle: 'solid', borderLeftWidth: 1, borderLeftStyle: 'solid', listStyleType: 'none', flexGrow: 1, position: 'relative', ':hover': { color: '#ccc' } }, first: { borderLeftWidth: 0, paddingLeft: 1 }, firstActive: { borderLeftWidth: 1, paddingLeft: 0 }, active: { color: '#fff', borderBottomWidth: 0, ':hover': { color: '#fff' } }, hasActivity: { color: '#50E3C2', ':hover': { color: '#50E3C2' } }, text: { transition: 'color .2s ease', height: '34px', display: 'block', width: '100%', position: 'relative', overflow: 'hidden' }, textInner: { position: 'absolute', left: '24px', right: '24px', top: 0, bottom: 0, textAlign: 'center', textOverflow: 'ellipsis', whiteSpace: 'nowrap', overflow: 'hidden' }, icon: { transition: `opacity .2s ease, color .2s ease, transform .25s ease, background-color .1s ease`, pointerEvents: 'none', position: 'absolute', right: '7px', top: '10px', display: 'inline-block', width: '14px', height: '14px', borderRadius: '100%', color: '#e9e9e9', opacity: 0, transform: 'scale(.95)', ':hover': { backgroundColor: 'rgba(255,255,255, .13)', color: '#fff' }, ':active': { backgroundColor: 'rgba(255,255,255, .1)', color: '#909090' } }, iconHovered: { opacity: 1, transform: 'none', pointerEvents: 'all' }, shape: { position: 'absolute', left: '4px', top: '4px', width: '6px', height: '6px', verticalAlign: 'middle', fill: 'currentColor', shapeRendering: 'crispEdges' } }; } }
lib/components/tab.js
1
https://github.com/vercel/hyper/commit/887fb5ac1a56d50d2f7ab694b8b1e92a2cebc101
[ 0.0026404031086713076, 0.0003492454416118562, 0.00017066043801605701, 0.00017806998221203685, 0.000550840690266341 ]
{ "id": 1, "code_window": [ " if (props.term) {\n", " //We need to set options again after reattaching an existing term\n", " Object.keys(this.termOptions).forEach(option => this.term.setOption(option, this.termOptions[option]));\n", " }\n", "\n", " this.onOpen(this.termOptions);\n", "\n", " if (props.onTitle) {\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " if (this.props.isTermActive) {\n", " this.term.focus();\n", " }\n" ], "file_path": "lib/components/term.js", "type": "add", "edit_start_line_idx": 82 }
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 14 16" width="14"><path fill="#989898" fill-rule="evenodd" d="M13.47 13.393c-.065-.075-.158-.147-.276-.22-.018-.01-.067-.04-.147-.084-.08-.045-.143-.084-.192-.117-.048-.032-.11-.09-.188-.17-.077-.08-.14-.164-.183-.254-.044-.09-.088-.21-.13-.362-.04-.152-.064-.32-.07-.504-.084.072-.13.212-.14.424-.01.21.037.426.135.647.096.22.243.362.44.43.192.064.344.135.46.208.117.075.192.158.225.255.033.094-.023.197-.165.308-.144.11-.372.22-.687.327-.434.148-.743.276-.924.38-.183.103-.45.3-.8.593-.238.196-.49.302-.76.317-.267.014-.484-.084-.65-.294-.167-.212-.22-.512-.16-.9.112-.744.11-1.323-.008-1.74-.095-.326-.116-.615-.062-.865.053-.25.137-.395.25-.437.112-.043.234.047.365.267.01.03.04.088.08.175.042.087.075.147.103.183.026.036.067.08.12.14.055.056.122.095.202.12.08.024.174.04.28.044.203.006.384-.036.546-.126.16-.09.28-.19.36-.298.08-.11.16-.215.242-.317.08-.1.15-.158.21-.17.066-.01.126-.076.18-.195.053-.12.088-.284.106-.495.018-.21.004-.464-.044-.754-.09-.517-.266-1.085-.53-1.706-.265-.618-.562-1.103-.888-1.454-.59-.626-.985-1.274-1.187-1.946-.208-.71-.298-1.346-.268-1.91.03-.405-.06-.845-.263-1.318-.204-.474-.478-.834-.816-1.084-.214-.16-.48-.284-.795-.37-.316-.087-.63-.126-.947-.122-.387 0-.697.062-.93.188-.476.256-.79.567-.946.932-.155.366-.227.817-.214 1.352.024 1.18.072 2.1.144 2.768-.084.31-.453.89-1.107 1.74-.12.12-.236.28-.348.482-.113.202-.203.383-.268.545-.065.16-.153.393-.263.695-.11.304-.19.518-.237.644-.042.107-.107.232-.195.375-.09.143-.162.284-.214.42-.054.138-.084.293-.09.464-.007.13 0 .244.018.34.024.144.068.188.134.134.267-.202.604-.083 1.01.358.284.31.787 1.03 1.507 2.16.06.1.12.208.178.326.06.116.116.27.17.464.054.194.077.367.067.522-.01.155-.077.297-.206.428-.127.13-.32.214-.576.25-.137.018-.302.006-.496-.036-.193-.043-.44-.11-.737-.206-.297-.095-.517-.16-.66-.196-.21-.047-.505-.108-.89-.183-.383-.075-.634-.13-.753-.165-.203-.053-.312-.13-.33-.23-.018-.085.024-.228.126-.43.1-.202.15-.347.15-.437.008-.065.005-.13-.007-.196-.01-.065-.024-.116-.04-.15-.015-.037-.04-.09-.077-.16-.036-.073-.06-.127-.072-.16-.108-.25-.123-.42-.044-.51.054-.078.18-.11.383-.09.304.03.55-.015.742-.135.315-.195.41-.512.285-.946 0 .202-.036.354-.107.455-.072.102-.196.207-.376.313-.1.06-.28.095-.535.108-.257.012-.427.054-.51.126-.06.054-.09.134-.093.242-.004.108.01.215.04.326.03.11.06.237.09.38.03.143.042.262.036.357-.007.066-.06.228-.16.487-.102.26-.123.457-.062.595.03.065.08.124.15.174.073.05.173.093.3.13.128.035.245.063.353.084.108.02.256.048.446.08.19.033.342.06.455.085.38.077.815.206 1.303.384.49.177.82.27.992.275.167.006.327-.028.478-.103.152-.075.28-.16.39-.255.107-.095.265-.184.477-.268.21-.084.448-.128.71-.134.12-.007.293-.014.518-.023.227-.01.395-.013.51-.013.512 0 .897.003 1.16.008.178.006.32.034.42.085.1.05.166.11.196.174.03.066.08.142.148.227.068.087.156.157.263.21.226.107.492.15.796.128.303-.02.506-.078.607-.174.167-.16.392-.35.674-.572.283-.22.537-.387.764-.5l.243-.115c.113-.053.21-.1.286-.138.075-.04.17-.088.28-.147.11-.06.2-.114.267-.165.07-.05.14-.108.21-.175.07-.065.117-.13.138-.196.02-.066.028-.133.023-.2-.016-.072-.052-.143-.118-.217zm-4.785-8.63c.018-.012.03-.016.036-.013.007.003.02.014.037.036l.05.058.06.072c.027.03.056.054.086.072.036.025.078.04.13.05.05.007.09.024.115.043.026.022.045.057.058.104.012.065.002.126-.03.178-.033.054-.077.077-.13.072-.107-.025-.223-.118-.347-.28-.127-.166-.148-.295-.065-.39zM7.578 1.295c.03-.04.047-.07.054-.093.01-.036.013-.073.005-.11-.01-.04-.007-.078.008-.117.015-.04.05-.06.103-.067.054 0 .126.044.214.134.018.01.045.03.085.054.04.024.065.044.08.062.014.018.023.033.023.044-.012.03-.04.05-.08.062-.04.012-.087.018-.134.018-.048 0-.075.003-.08.008-.048.018-.093.044-.134.08-.04.036-.075.062-.098.08-.025.018-.048.018-.072 0-.025-.036-.033-.06-.026-.075.005-.015.023-.04.052-.08zM3.256 7.978c.04-.048.072-.087.09-.116.018-.03.035-.07.05-.12.014-.052.027-.09.04-.112.01-.025.03-.033.054-.026.01-.004.02.003.026.018.007.014.008.022.008.022v.027c0 .01 0 .022-.005.037l-.014.04c-.006.012-.01.03-.018.054-.006.026-.01.045-.018.063-.024.06-.06.113-.11.16-.05.048-.09.07-.112.062-.036-.013-.032-.05.008-.107zm5.84 5.508c-.01.19-.052.46-.12.803-.07.344-.11.574-.13.687-.125-.007-.195-.053-.213-.14-.018-.086 0-.197.054-.334.13-.398.2-.672.205-.82.012-.275-.018-.43-.09-.465-.065-.047-.166.043-.303.268-.264.43-.79.687-1.58.777-.715.095-1.21-.01-1.484-.32-.06-.044-.12-.05-.178-.024-.06.025-.098.054-.116.084-.006.01 0 .03.018.054l.085.107c.04.048.07.095.093.144.232.404.21.678-.062.82 0-.274-.02-.483-.062-.628-.042-.146-.126-.307-.25-.482-.125-.176-.21-.31-.26-.397.18-.018.314-.086.407-.205.094-.12.135-.247.127-.384-.01-.137-.06-.25-.157-.34-.054-.054-.33-.28-.83-.682-.5-.402-.81-.67-.93-.808-.024-.025-.095-.084-.214-.178-.12-.095-.194-.178-.223-.25-.275-.6-.304-1.096-.09-1.483l.036-.044c.028-.007.03.047.007.16-.036.166-.047.332-.036.5.025.374.132.654.323.838.125.126.21.116.26-.026.035-.047.05-.224.048-.527-.002-.304.003-.51.014-.616.048-.34.19-.76.425-1.26.234-.5.42-.767.557-.803-.108-.173-.142-.36-.103-.563.04-.203.1-.376.188-.518.087-.142.175-.308.263-.494.09-.188.134-.356.134-.505 0-.04.002-.072.01-.09.016-.054.092.012.222.196.25.37.438.586.563.652.13.072.276.068.438-.01.16-.077.36-.206.594-.384.235-.177.436-.31.603-.392.018-.007.045-.02.085-.04.04-.022.068-.037.09-.045.02-.008.047-.023.08-.04l.075-.045c.017-.01.035-.026.053-.04.018-.016.03-.03.036-.045.006-.015.01-.028.01-.04-.012-.055-.038-.087-.078-.1-.04-.01-.09-.004-.156.024-.066.026-.14.062-.22.108-.08.044-.17.095-.267.152-.1.057-.198.11-.3.156-.1.048-.21.09-.32.126-.114.035-.222.056-.323.06-.25.008-.45-.058-.597-.195-.095-.09-.146-.145-.152-.17-.007-.024.02-.03.08-.017.32.042.556.047.705.018.155-.025.362-.094.625-.206.054-.025.19-.082.407-.175.217-.09.385-.157.504-.193.07-.018.12-.045.146-.084.026-.04.036-.076.026-.108-.008-.033-.027-.06-.058-.075-.066-.036-.126-.012-.178.072-.03.053-.093.106-.188.156s-.183.09-.263.116c-.08.025-.183.058-.31.092-.124.036-.19.057-.204.062-.326.102-.63.146-.91.134-.13-.006-.237-.024-.317-.06-.08-.03-.136-.07-.165-.115-.03-.044-.077-.1-.144-.17-.065-.068-.14-.125-.223-.174-.058-.03-.08-.084-.066-.16.015-.078.06-.16.14-.243.005-.006.066-.042.18-.11.117-.07.2-.14.246-.21.054-.085.146-.17.276-.26.007-.025.01-.09.013-.197.003-.108-.027-.223-.086-.348-.058-.125-.14-.187-.24-.187-.145-.007-.244.036-.305.125-.06.09-.087.2-.08.33.006.113.033.212.084.3.05.086.096.128.14.128.064-.007.085.018.06.072-.035.065-.082.108-.143.126-.04.01-.087-.028-.138-.12-.05-.094-.09-.205-.116-.336-.026-.13-.037-.242-.03-.33.01-.184.06-.36.146-.53.087-.17.21-.252.37-.245.168.006.3.107.403.303.1.196.148.464.143.804.018.042.064.057.14.044.074-.012.172-.013.293-.005.123.01.21.042.264.094.006 0 .01-.044.01-.134-.108-.75.158-1.15.795-1.197.093.018.173.04.24.067.066.026.136.072.21.134.076.062.138.154.19.273.05.12.09.267.12.445v.33c0 .19-.04.297-.116.322-.126.042-.214.04-.268-.005-.054-.045-.047-.125.018-.238.06-.148.047-.32-.036-.517-.083-.196-.235-.286-.456-.268-.148.006-.256.086-.32.242-.067.154-.09.306-.073.454.017.15.05.227.097.232.036.006.142.054.317.144.176.09.308.142.396.16.232.047.364.122.397.223.033.1.02.248-.04.443-.06.194-.077.352-.055.478.025.13.07.25.134.358.066.107.136.205.21.294.074.09.16.256.262.5.1.242.193.55.276.918l.067.062c.04.036.078.08.117.134.04.054.085.126.14.22.053.092.11.226.173.406.062.177.12.383.175.615.065.275.1.594.103.956.003.363.026.612.072.746.044.134.16.19.344.165.232-.01.38-.137.446-.375.196-.69.036-1.52-.482-2.482-.196-.376-.365-.622-.51-.74.21.118.424.342.644.668.22.328.36.634.42.92l.05.236c.025.127.04.203.043.224l.036.183c.022.102.032.167.032.197s.003.088.01.174c.006.088.004.155-.005.202-.01.047-.018.11-.026.193-.01.08-.024.158-.044.232l-.066.244c.326.145.49.27.49.377-.12-.1-.3-.167-.533-.2-.232-.032-.447 0-.646.094-.2.096-.3.254-.308.474-.214 0-.366.054-.456.16-.13.155-.2.364-.205.63-.006.265.017.554.068.866.05.313.07.53.058.656zM5.354 3.138c-.018-.006-.032-.024-.044-.054 0-.053.026-.075.08-.062.036.012.07.058.103.134.033.077.04.167.023.268 0 .018-.008.026-.026.026-.065 0-.09-.06-.072-.178.018-.09-.003-.134-.064-.134zm2.314.144l-.018.026c-.047.03-.072.036-.072.018-.024-.16-.077-.253-.16-.277l-.036-.02c-.042-.035-.02-.057.062-.06.018-.008.044.002.08.025.036.024.07.06.098.11.03.053.046.11.046.177z"/></svg>
website/static/linux-logo.svg
0
https://github.com/vercel/hyper/commit/887fb5ac1a56d50d2f7ab694b8b1e92a2cebc101
[ 0.00048353392048738897, 0.00048353392048738897, 0.00048353392048738897, 0.00048353392048738897, 0 ]
{ "id": 1, "code_window": [ " if (props.term) {\n", " //We need to set options again after reattaching an existing term\n", " Object.keys(this.termOptions).forEach(option => this.term.setOption(option, this.termOptions[option]));\n", " }\n", "\n", " this.onOpen(this.termOptions);\n", "\n", " if (props.onTitle) {\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " if (this.props.isTermActive) {\n", " this.term.focus();\n", " }\n" ], "file_path": "lib/components/term.js", "type": "add", "edit_start_line_idx": 82 }
import {NOTIFICATION_MESSAGE, NOTIFICATION_DISMISS} from '../constants/notifications'; export function dismissNotification(id) { return { type: NOTIFICATION_DISMISS, id }; } export function addNotificationMessage(text, url = null, dismissable = true) { return { type: NOTIFICATION_MESSAGE, text, url, dismissable }; }
lib/actions/notifications.js
0
https://github.com/vercel/hyper/commit/887fb5ac1a56d50d2f7ab694b8b1e92a2cebc101
[ 0.0001784731721272692, 0.00017676601419225335, 0.0001750588562572375, 0.00017676601419225335, 0.0000017071579350158572 ]
{ "id": 1, "code_window": [ " if (props.term) {\n", " //We need to set options again after reattaching an existing term\n", " Object.keys(this.termOptions).forEach(option => this.term.setOption(option, this.termOptions[option]));\n", " }\n", "\n", " this.onOpen(this.termOptions);\n", "\n", " if (props.onTitle) {\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " if (this.props.isTermActive) {\n", " this.term.focus();\n", " }\n" ], "file_path": "lib/components/term.js", "type": "add", "edit_start_line_idx": 82 }
import React from 'react'; export default class StyleSheet extends React.PureComponent { render() { const {customCSS, backgroundColor, fontFamily, foregroundColor, borderColor} = this.props; return ( <style dangerouslySetInnerHTML={{ __html: ` .xterm { font-family: ${fontFamily}; font-feature-settings: "liga" 0; position: relative; user-select: none; -ms-user-select: none; -webkit-user-select: none; } .xterm.focus, .xterm:focus { outline: none; } .xterm .xterm-helpers { position: absolute; top: 0; /** * The z-index of the helpers must be higher than the canvases in order for * IMEs to appear on top. */ z-index: 10; } .xterm .xterm-helper-textarea { /* * HACK: to fix IE's blinking cursor * Move textarea out of the screen to the far left, so that the cursor is not visible. */ position: absolute; opacity: 0; left: -9999em; top: 0; width: 0; height: 0; z-index: -10; /** Prevent wrapping so the IME appears against the textarea at the correct position */ white-space: nowrap; overflow: hidden; resize: none; } .xterm .composition-view { /* TODO: Composition position got messed up somewhere */ background: ${backgroundColor}; color: ${foregroundColor}; display: none; position: absolute; white-space: nowrap; z-index: 1; } .xterm .composition-view.active { display: block; } .xterm .xterm-viewport { /* On OS X this is required in order for the scroll bar to appear fully opaque */ background-color: ${backgroundColor}; overflow-y: scroll; } .xterm canvas { position: absolute; left: 0; top: 0; } .xterm .xterm-scroll-area { visibility: hidden; } .xterm .xterm-char-measure-element { display: inline-block; visibility: hidden; position: absolute; left: -9999em; } .xterm.enable-mouse-events { /* When mouse events are enabled (eg. tmux), revert to the standard pointer cursor */ cursor: default; } .xterm:not(.enable-mouse-events) { cursor: text; } ::-webkit-scrollbar { width: 5px; } ::-webkit-scrollbar-thumb { -webkit-border-radius: 10px; border-radius: 10px; background: ${borderColor}; } ::-webkit-scrollbar-thumb:window-inactive { background: ${borderColor}; } ${customCSS} ` }} /> ); } }
lib/components/style-sheet.js
0
https://github.com/vercel/hyper/commit/887fb5ac1a56d50d2f7ab694b8b1e92a2cebc101
[ 0.00031044884235598147, 0.00018272198212798685, 0.00016379906446672976, 0.00017138161638285965, 0.00003876248229062185 ]
{ "id": 2, "code_window": [ " if (props.onTitle) {\n", " this.term.on('title', props.onTitle);\n", " }\n", "\n", " if (props.onActive) {\n", " this.term.on('focus', () => {\n", " // xterm@2 emits this event 2 times. Will be fixed in xterm@3.\n", " if (!this.props.isTermActive) {\n", " props.onActive();\n", " }\n", " });\n", " }\n", "\n", " if (props.onData) {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ " this.term.on('focus', props.onActive);\n" ], "file_path": "lib/components/term.js", "type": "replace", "edit_start_line_idx": 90 }
/* global Blob,URL,requestAnimationFrame */ import React from 'react'; import {Terminal} from 'xterm'; import * as fit from 'xterm/lib/addons/fit/fit'; import {clipboard} from 'electron'; import * as Color from 'color'; import {PureComponent} from '../base-components'; import terms from '../terms'; import processClipboard from '../utils/paste'; Terminal.applyAddon(fit); // map old hterm constants to xterm.js const CURSOR_STYLES = { BEAM: 'bar', UNDERLINE: 'underline', BLOCK: 'block' }; const getTermOptions = props => { // Set a background color only if it is opaque const backgroundColor = Color(props.backgroundColor).alpha() < 1 ? 'transparent' : props.backgroundColor; return { macOptionIsMeta: props.modifierKeys.altIsMeta, cursorStyle: CURSOR_STYLES[props.cursorShape], cursorBlink: props.cursorBlink, fontFamily: props.fontFamily, fontSize: props.fontSize, allowTransparency: true, theme: { foreground: props.foregroundColor, background: backgroundColor, cursor: props.cursorColor, cursorAccent: props.cursorAccentColor, selection: props.selectionColor, black: props.colors.black, red: props.colors.red, green: props.colors.green, yellow: props.colors.yellow, blue: props.colors.blue, magenta: props.colors.magenta, cyan: props.colors.cyan, white: props.colors.white, brightBlack: props.colors.lightBlack, brightRed: props.colors.lightRed, brightGreen: props.colors.lightGreen, brightYellow: props.colors.lightYellow, brightBlue: props.colors.lightBlue, brightMagenta: props.colors.lightMagenta, brightCyan: props.colors.lightCyan, brightWhite: props.colors.lightWhite } }; }; export default class Term extends PureComponent { constructor(props) { super(props); props.ref_(props.uid, this); this.termRef = null; this.termWrapperRef = null; this.termRect = null; this.onOpen = this.onOpen.bind(this); this.onWindowResize = this.onWindowResize.bind(this); this.onWindowPaste = this.onWindowPaste.bind(this); this.onTermRef = this.onTermRef.bind(this); this.onTermWrapperRef = this.onTermWrapperRef.bind(this); this.onMouseUp = this.onMouseUp.bind(this); this.termOptions = {}; } componentDidMount() { const {props} = this; this.termOptions = getTermOptions(props); this.term = props.term || new Terminal(this.termOptions); this.term.attachCustomKeyEventHandler(this.keyboardHandler); this.term.open(this.termRef); if (props.term) { //We need to set options again after reattaching an existing term Object.keys(this.termOptions).forEach(option => this.term.setOption(option, this.termOptions[option])); } this.onOpen(this.termOptions); if (props.onTitle) { this.term.on('title', props.onTitle); } if (props.onActive) { this.term.on('focus', () => { // xterm@2 emits this event 2 times. Will be fixed in xterm@3. if (!this.props.isTermActive) { props.onActive(); } }); } if (props.onData) { this.term.on('data', props.onData); } if (props.onResize) { this.term.on('resize', ({cols, rows}) => { props.onResize(cols, rows); }); } if (props.onCursorMove) { this.term.on('cursormove', () => { const cursorFrame = { x: this.term.buffer.x * this.term.renderer.dimensions.actualCellWidth, y: this.term.buffer.y * this.term.renderer.dimensions.actualCellHeight, width: this.term.renderer.dimensions.actualCellWidth, height: this.term.renderer.dimensions.actualCellHeight, col: this.term.buffer.y, row: this.term.buffer.x }; props.onCursorMove(cursorFrame); }); } window.addEventListener('resize', this.onWindowResize, { passive: true }); window.addEventListener('paste', this.onWindowPaste, { capture: true }); terms[this.props.uid] = this; } onOpen(termOptions) { // we need to delay one frame so that aphrodite styles // get applied and we can make an accurate measurement // of the container width and height requestAnimationFrame(() => { // at this point it would make sense for character // measurement to have taken place but it seems that // xterm.js might be doing this asynchronously, so // we force it instead // eslint-disable-next-line no-debugger //debugger; this.term.charMeasure.measure(termOptions); this.fitResize(); }); } getTermDocument() { // eslint-disable-next-line no-console console.warn( 'The underlying terminal engine of Hyper no longer ' + 'uses iframes with individual `document` objects for each ' + 'terminal instance. This method call is retained for ' + "backwards compatibility reasons. It's ok to attach directly" + 'to the `document` object of the main `window`.' ); return document; } onWindowResize() { this.fitResize(); } // intercepting paste event for any necessary processing of // clipboard data, if result is falsy, paste event continues onWindowPaste(e) { if (!this.props.isTermActive) return; const processed = processClipboard(); if (processed) { e.preventDefault(); e.stopPropagation(); this.term.send(processed); } } onMouseUp(e) { if (this.props.quickEdit && e.button === 2) { if (this.term.hasSelection()) { clipboard.writeText(this.term.getSelection()); this.term.clearSelection(); } else { document.execCommand('paste'); } } else if (this.props.copyOnSelect && this.term.hasSelection()) { clipboard.writeText(this.term.getSelection()); } } write(data) { this.term.write(data); } focus() { this.term.focus(); } clear() { this.term.clear(); } reset() { this.term.reset(); } resize(cols, rows) { this.term.resize(cols, rows); } selectAll() { this.term.selectAll(); } fitResize() { if (!this.termWrapperRef) { return; } this.term.fit(); } keyboardHandler(e) { // Has Mousetrap flagged this event as a command? return !e.catched; } componentWillReceiveProps(nextProps) { if (!this.props.cleared && nextProps.cleared) { this.clear(); } const nextTermOptions = getTermOptions(nextProps); // Update only options that have changed. Object.keys(nextTermOptions) .filter(option => option !== 'theme' && nextTermOptions[option] !== this.termOptions[option]) .forEach(option => this.term.setOption(option, nextTermOptions[option])); // Do we need to update theme? const shouldUpdateTheme = !this.termOptions.theme || Object.keys(nextTermOptions.theme).some(option => { nextTermOptions.theme[option] !== this.termOptions.theme[option]; }); if (shouldUpdateTheme) { this.term.setOption('theme', nextTermOptions.theme); } this.termOptions = nextTermOptions; if (!this.props.isTermActive && nextProps.isTermActive) { requestAnimationFrame(() => { this.term.charMeasure.measure(this.termOptions); this.fitResize(); }); } if (this.props.fontSize !== nextProps.fontSize || this.props.fontFamily !== nextProps.fontFamily) { // invalidate xterm cache about how wide each // character is this.term.charMeasure.measure(this.termOptions); // resize to fit the container this.fitResize(); } if (nextProps.rows !== this.props.rows || nextProps.cols !== this.props.cols) { this.resize(nextProps.cols, nextProps.rows); } } onTermWrapperRef(component) { this.termWrapperRef = component; } onTermRef(component) { this.termRef = component; } componentWillUnmount() { terms[this.props.uid] = null; this.props.ref_(this.props.uid, null); // to clean up the terminal, we remove the listeners // instead of invoking `destroy`, since it will make the // term insta un-attachable in the future (which we need // to do in case of splitting, see `componentDidMount` ['title', 'focus', 'data', 'resize', 'cursormove'].forEach(type => this.term.removeAllListeners(type)); window.removeEventListener('resize', this.onWindowResize, { passive: true }); window.removeEventListener('paste', this.onWindowPaste, { capture: true }); } template(css) { return ( <div className={css('fit', this.props.isTermActive && 'active')} style={{padding: this.props.padding}} onMouseUp={this.onMouseUp} > {this.props.customChildrenBefore} <div ref={this.onTermWrapperRef} className={css('fit', 'wrapper')}> <div ref={this.onTermRef} className={css('fit', 'term')} /> </div> {this.props.customChildren} </div> ); } styles() { return { fit: { display: 'block', width: '100%', height: '100%' }, wrapper: { // TODO: decide whether to keep this or not based on // understanding what xterm-selection is for overflow: 'hidden' }, term: {} }; } }
lib/components/term.js
1
https://github.com/vercel/hyper/commit/887fb5ac1a56d50d2f7ab694b8b1e92a2cebc101
[ 0.9943878054618835, 0.036230891942977905, 0.0001619404647499323, 0.00034644349943846464, 0.17010535299777985 ]
{ "id": 2, "code_window": [ " if (props.onTitle) {\n", " this.term.on('title', props.onTitle);\n", " }\n", "\n", " if (props.onActive) {\n", " this.term.on('focus', () => {\n", " // xterm@2 emits this event 2 times. Will be fixed in xterm@3.\n", " if (!this.props.isTermActive) {\n", " props.onActive();\n", " }\n", " });\n", " }\n", "\n", " if (props.onData) {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ " this.term.on('focus', props.onActive);\n" ], "file_path": "lib/components/term.js", "type": "replace", "edit_start_line_idx": 90 }
# build output dist app/renderer bin/cli.* # dependencies node_modules # logs npm-debug.log # optional dev config file and plugins directory .hyper.js .hyper_plugins
.gitignore
0
https://github.com/vercel/hyper/commit/887fb5ac1a56d50d2f7ab694b8b1e92a2cebc101
[ 0.0001708397176116705, 0.00017042006948031485, 0.00017000040679704398, 0.00017042006948031485, 4.1965540731325746e-7 ]
{ "id": 2, "code_window": [ " if (props.onTitle) {\n", " this.term.on('title', props.onTitle);\n", " }\n", "\n", " if (props.onActive) {\n", " this.term.on('focus', () => {\n", " // xterm@2 emits this event 2 times. Will be fixed in xterm@3.\n", " if (!this.props.isTermActive) {\n", " props.onActive();\n", " }\n", " });\n", " }\n", "\n", " if (props.onData) {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ " this.term.on('focus', props.onActive);\n" ], "file_path": "lib/components/term.js", "type": "replace", "edit_start_line_idx": 90 }
import {CONFIG_LOAD, CONFIG_RELOAD} from '../constants/config'; export function loadConfig(config) { return { type: CONFIG_LOAD, config }; } export function reloadConfig(config) { const now = Date.now(); return { type: CONFIG_RELOAD, config, now }; }
lib/actions/config.js
0
https://github.com/vercel/hyper/commit/887fb5ac1a56d50d2f7ab694b8b1e92a2cebc101
[ 0.00017399946227669716, 0.0001734475081320852, 0.00017289553943555802, 0.0001734475081320852, 5.519614205695689e-7 ]
{ "id": 2, "code_window": [ " if (props.onTitle) {\n", " this.term.on('title', props.onTitle);\n", " }\n", "\n", " if (props.onActive) {\n", " this.term.on('focus', () => {\n", " // xterm@2 emits this event 2 times. Will be fixed in xterm@3.\n", " if (!this.props.isTermActive) {\n", " props.onActive();\n", " }\n", " });\n", " }\n", "\n", " if (props.onData) {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ " this.term.on('focus', props.onActive);\n" ], "file_path": "lib/components/term.js", "type": "replace", "edit_start_line_idx": 90 }
export const NOTIFICATION_MESSAGE = 'NOTIFICATION_MESSAGE'; export const NOTIFICATION_DISMISS = 'NOTIFICATION_DISMISS';
lib/constants/notifications.js
0
https://github.com/vercel/hyper/commit/887fb5ac1a56d50d2f7ab694b8b1e92a2cebc101
[ 0.00016521566431038082, 0.00016521566431038082, 0.00016521566431038082, 0.00016521566431038082, 0 ]
{ "id": 0, "code_window": [ " toggleRow: jest.fn(),\n", " on: jest.fn(),\n", " meta: {\n", " canEdit: true,\n", " },\n", " };\n", "\n", " panel = new PanelModel({ collapsed: false });\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " events: { subscribe: jest.fn() },\n" ], "file_path": "public/app/features/dashboard/components/DashboardRow/DashboardRow.test.tsx", "type": "add", "edit_start_line_idx": 15 }
import React from 'react'; import classNames from 'classnames'; import { Icon } from '@grafana/ui'; import { PanelModel } from '../../state/PanelModel'; import { DashboardModel } from '../../state/DashboardModel'; import appEvents from 'app/core/app_events'; import { CoreEvents } from 'app/types'; import { RowOptionsButton } from '../RowOptions/RowOptionsButton'; import { getTemplateSrv } from '@grafana/runtime'; import { ShowConfirmModalEvent } from '../../../../types/events'; export interface DashboardRowProps { panel: PanelModel; dashboard: DashboardModel; } export class DashboardRow extends React.Component<DashboardRowProps, any> { constructor(props: DashboardRowProps) { super(props); this.state = { collapsed: this.props.panel.collapsed, }; this.props.dashboard.on(CoreEvents.templateVariableValueUpdated, this.onVariableUpdated); } componentWillUnmount() { this.props.dashboard.off(CoreEvents.templateVariableValueUpdated, this.onVariableUpdated); } onVariableUpdated = () => { this.forceUpdate(); }; onToggle = () => { this.props.dashboard.toggleRow(this.props.panel); this.setState((prevState: any) => { return { collapsed: !prevState.collapsed }; }); }; onUpdate = (title: string, repeat: string | undefined) => { this.props.panel['title'] = title; this.props.panel['repeat'] = repeat; this.props.panel.render(); this.props.dashboard.processRepeats(); this.forceUpdate(); }; onDelete = () => { appEvents.publish( new ShowConfirmModalEvent({ title: 'Delete row', text: 'Are you sure you want to remove this row and all its panels?', altActionText: 'Delete row only', icon: 'trash-alt', onConfirm: () => { this.props.dashboard.removeRow(this.props.panel, true); }, onAltAction: () => { this.props.dashboard.removeRow(this.props.panel, false); }, }) ); }; render() { const classes = classNames({ 'dashboard-row': true, 'dashboard-row--collapsed': this.state.collapsed, }); const title = getTemplateSrv().replace(this.props.panel.title, this.props.panel.scopedVars, 'text'); const count = this.props.panel.panels ? this.props.panel.panels.length : 0; const panels = count === 1 ? 'panel' : 'panels'; const canEdit = this.props.dashboard.meta.canEdit === true; return ( <div className={classes}> <a className="dashboard-row__title pointer" onClick={this.onToggle}> <Icon name={this.state.collapsed ? 'angle-right' : 'angle-down'} /> {title} <span className="dashboard-row__panel_count"> ({count} {panels}) </span> </a> {canEdit && ( <div className="dashboard-row__actions"> <RowOptionsButton title={this.props.panel.title} repeat={this.props.panel.repeat} onUpdate={this.onUpdate} /> <a className="pointer" onClick={this.onDelete}> <Icon name="trash-alt" /> </a> </div> )} {this.state.collapsed === true && ( <div className="dashboard-row__toggle-target" onClick={this.onToggle}> &nbsp; </div> )} {canEdit && <div className="dashboard-row__drag grid-drag-handle" />} </div> ); } }
public/app/features/dashboard/components/DashboardRow/DashboardRow.tsx
1
https://github.com/grafana/grafana/commit/395d7eb74cdce7c2a405bba80738cd4a3d342784
[ 0.3767698109149933, 0.03496537730097771, 0.00016847194638103247, 0.0011978645343333483, 0.10332197695970535 ]
{ "id": 0, "code_window": [ " toggleRow: jest.fn(),\n", " on: jest.fn(),\n", " meta: {\n", " canEdit: true,\n", " },\n", " };\n", "\n", " panel = new PanelModel({ collapsed: false });\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " events: { subscribe: jest.fn() },\n" ], "file_path": "public/app/features/dashboard/components/DashboardRow/DashboardRow.test.tsx", "type": "add", "edit_start_line_idx": 15 }
# Grafana admin app The grafana catalog is enabled or disabled by setting `plugin_admin_enabled` in the setup files.
plugins-bundled/internal/plugin-admin-app/README.md
0
https://github.com/grafana/grafana/commit/395d7eb74cdce7c2a405bba80738cd4a3d342784
[ 0.00016616533685009927, 0.00016616533685009927, 0.00016616533685009927, 0.00016616533685009927, 0 ]
{ "id": 0, "code_window": [ " toggleRow: jest.fn(),\n", " on: jest.fn(),\n", " meta: {\n", " canEdit: true,\n", " },\n", " };\n", "\n", " panel = new PanelModel({ collapsed: false });\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " events: { subscribe: jest.fn() },\n" ], "file_path": "public/app/features/dashboard/components/DashboardRow/DashboardRow.test.tsx", "type": "add", "edit_start_line_idx": 15 }
import { GrafanaTheme, GrafanaTheme2 } from '@grafana/data'; export interface Themeable { theme: GrafanaTheme; } export interface Themeable2 { theme: GrafanaTheme2; }
packages/grafana-ui/src/types/theme.ts
0
https://github.com/grafana/grafana/commit/395d7eb74cdce7c2a405bba80738cd4a3d342784
[ 0.00016776708071120083, 0.00016776708071120083, 0.00016776708071120083, 0.00016776708071120083, 0 ]
{ "id": 0, "code_window": [ " toggleRow: jest.fn(),\n", " on: jest.fn(),\n", " meta: {\n", " canEdit: true,\n", " },\n", " };\n", "\n", " panel = new PanelModel({ collapsed: false });\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " events: { subscribe: jest.fn() },\n" ], "file_path": "public/app/features/dashboard/components/DashboardRow/DashboardRow.test.tsx", "type": "add", "edit_start_line_idx": 15 }
import { of } from 'rxjs'; import { dataFrameToJSON, dateTime, MetricFindValue, MutableDataFrame } from '@grafana/data'; import { MssqlDatasource } from '../datasource'; import { TemplateSrv } from 'app/features/templating/template_srv'; import { backendSrv } from 'app/core/services/backend_srv'; import { initialCustomVariableModelState } from '../../../../features/variables/custom/reducer'; import { createFetchResponse } from 'test/helpers/createFetchResponse'; import { TimeSrvStub } from 'test/specs/helpers'; jest.mock('@grafana/runtime', () => ({ ...((jest.requireActual('@grafana/runtime') as unknown) as object), getBackendSrv: () => backendSrv, })); describe('MSSQLDatasource', () => { const templateSrv: TemplateSrv = new TemplateSrv(); const fetchMock = jest.spyOn(backendSrv, 'fetch'); const ctx: any = { timeSrv: new TimeSrvStub(), }; beforeEach(() => { jest.clearAllMocks(); ctx.instanceSettings = { name: 'mssql' }; ctx.ds = new MssqlDatasource(ctx.instanceSettings, templateSrv, ctx.timeSrv); }); describe('When performing annotationQuery', () => { let results: any; const annotationName = 'MyAnno'; const options = { annotation: { name: annotationName, rawQuery: 'select time, text, tags from table;', }, range: { from: dateTime(1432288354), to: dateTime(1432288401), }, }; const response = { results: { MyAnno: { frames: [ dataFrameToJSON( new MutableDataFrame({ fields: [ { name: 'time', values: [1521545610656, 1521546251185, 1521546501378] }, { name: 'text', values: ['some text', 'some text2', 'some text3'] }, { name: 'tags', values: ['TagA,TagB', ' TagB , TagC', null] }, ], }) ), ], }, }, }; beforeEach(() => { fetchMock.mockImplementation(() => of(createFetchResponse(response))); return ctx.ds.annotationQuery(options).then((data: any) => { results = data; }); }); it('should return annotation list', () => { expect(results.length).toBe(3); expect(results[0].text).toBe('some text'); expect(results[0].tags[0]).toBe('TagA'); expect(results[0].tags[1]).toBe('TagB'); expect(results[1].tags[0]).toBe('TagB'); expect(results[1].tags[1]).toBe('TagC'); expect(results[2].tags.length).toBe(0); }); }); describe('When performing metricFindQuery', () => { let results: MetricFindValue[]; const query = 'select * from atable'; const response = { results: { tempvar: { frames: [ dataFrameToJSON( new MutableDataFrame({ fields: [ { name: 'title', values: ['aTitle', 'aTitle2', 'aTitle3'] }, { name: 'text', values: ['some text', 'some text2', 'some text3'] }, ], }) ), ], }, }, }; beforeEach(() => { fetchMock.mockImplementation(() => of(createFetchResponse(response))); return ctx.ds.metricFindQuery(query).then((data: MetricFindValue[]) => { results = data; }); }); it('should return list of all column values', () => { expect(results.length).toBe(6); expect(results[0].text).toBe('aTitle'); expect(results[5].text).toBe('some text3'); }); }); describe('When performing metricFindQuery with key, value columns', () => { let results: any; const query = 'select * from atable'; const response = { results: { tempvar: { frames: [ dataFrameToJSON( new MutableDataFrame({ fields: [ { name: '__value', values: ['value1', 'value2', 'value3'] }, { name: '__text', values: ['aTitle', 'aTitle2', 'aTitle3'] }, ], }) ), ], }, }, }; beforeEach(() => { fetchMock.mockImplementation(() => of(createFetchResponse(response))); return ctx.ds.metricFindQuery(query).then((data: any) => { results = data; }); }); it('should return list of as text, value', () => { expect(results.length).toBe(3); expect(results[0].text).toBe('aTitle'); expect(results[0].value).toBe('value1'); expect(results[2].text).toBe('aTitle3'); expect(results[2].value).toBe('value3'); }); }); describe('When performing metricFindQuery with key, value columns and with duplicate keys', () => { let results: any; const query = 'select * from atable'; const response = { results: { tempvar: { frames: [ dataFrameToJSON( new MutableDataFrame({ fields: [ { name: '__text', values: ['aTitle', 'aTitle', 'aTitle'] }, { name: '__value', values: ['same', 'same', 'diff'] }, ], }) ), ], }, }, }; beforeEach(() => { fetchMock.mockImplementation(() => of(createFetchResponse(response))); return ctx.ds.metricFindQuery(query).then((data: any) => { results = data; }); }); it('should return list of unique keys', () => { expect(results.length).toBe(1); expect(results[0].text).toBe('aTitle'); expect(results[0].value).toBe('same'); }); }); describe('When performing metricFindQuery', () => { const query = 'select * from atable'; const response = { results: { tempvar: { frames: [ dataFrameToJSON( new MutableDataFrame({ fields: [{ name: 'test', values: ['aTitle'] }], }) ), ], }, }, }; const time = { from: dateTime(1521545610656), to: dateTime(1521546251185), }; beforeEach(() => { ctx.timeSrv.setTime(time); fetchMock.mockImplementation(() => of(createFetchResponse(response))); return ctx.ds.metricFindQuery(query, { range: time }); }); it('should pass timerange to datasourceRequest', () => { expect(fetchMock).toBeCalledTimes(1); expect(fetchMock.mock.calls[0][0].data.from).toBe(time.from.valueOf().toString()); expect(fetchMock.mock.calls[0][0].data.to).toBe(time.to.valueOf().toString()); expect(fetchMock.mock.calls[0][0].data.queries.length).toBe(1); expect(fetchMock.mock.calls[0][0].data.queries[0].rawSql).toBe(query); }); }); describe('When interpolating variables', () => { beforeEach(() => { ctx.variable = { ...initialCustomVariableModelState }; }); describe('and value is a string', () => { it('should return an unquoted value', () => { expect(ctx.ds.interpolateVariable('abc', ctx.variable)).toEqual('abc'); }); }); describe('and value is a number', () => { it('should return an unquoted value', () => { expect(ctx.ds.interpolateVariable(1000, ctx.variable)).toEqual(1000); }); }); describe('and value is an array of strings', () => { it('should return comma separated quoted values', () => { expect(ctx.ds.interpolateVariable(['a', 'b', 'c'], ctx.variable)).toEqual("'a','b','c'"); }); }); describe('and variable allows multi-value and value is a string', () => { it('should return a quoted value', () => { ctx.variable.multi = true; expect(ctx.ds.interpolateVariable('abc', ctx.variable)).toEqual("'abc'"); }); }); describe('and variable contains single quote', () => { it('should return a quoted value', () => { ctx.variable.multi = true; expect(ctx.ds.interpolateVariable("a'bc", ctx.variable)).toEqual("'a''bc'"); }); }); describe('and variable allows all and value is a string', () => { it('should return a quoted value', () => { ctx.variable.includeAll = true; expect(ctx.ds.interpolateVariable('abc', ctx.variable)).toEqual("'abc'"); }); }); }); describe('targetContainsTemplate', () => { it('given query that contains template variable it should return true', () => { const rawSql = `SELECT $__timeGroup(createdAt,'$summarize') as time, avg(value) as value, hostname as metric FROM grafana_metric WHERE $__timeFilter(createdAt) AND measurement = 'logins.count' AND hostname IN($host) GROUP BY $__timeGroup(createdAt,'$summarize'), hostname ORDER BY 1`; const query = { rawSql, }; templateSrv.init([ { type: 'query', name: 'summarize', current: { value: '1m' } }, { type: 'query', name: 'host', current: { value: 'a' } }, ]); expect(ctx.ds.targetContainsTemplate(query)).toBeTruthy(); }); it('given query that only contains global template variable it should return false', () => { const rawSql = `SELECT $__timeGroup(createdAt,'$__interval') as time, avg(value) as value, hostname as metric FROM grafana_metric WHERE $__timeFilter(createdAt) AND measurement = 'logins.count' GROUP BY $__timeGroup(createdAt,'$summarize'), hostname ORDER BY 1`; const query = { rawSql, }; templateSrv.init([ { type: 'query', name: 'summarize', current: { value: '1m' } }, { type: 'query', name: 'host', current: { value: 'a' } }, ]); expect(ctx.ds.targetContainsTemplate(query)).toBeFalsy(); }); }); });
public/app/plugins/datasource/mssql/specs/datasource.test.ts
0
https://github.com/grafana/grafana/commit/395d7eb74cdce7c2a405bba80738cd4a3d342784
[ 0.00017737908638082445, 0.0001728986535454169, 0.00016416885773651302, 0.00017315306467935443, 0.0000025032659323187545 ]
{ "id": 1, "code_window": [ "\n", " expect(wrapper.find('.dashboard-row--collapsed')).toHaveLength(1);\n", " expect(dashboardMock.toggleRow.mock.calls).toHaveLength(1);\n", " });\n", "\n", " it('should have two actions as admin', () => {\n", " expect(wrapper.find('.dashboard-row__actions .pointer')).toHaveLength(2);\n", " });\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " it('Should subscribe to event during mount', () => {\n", " expect(dashboardMock.events.subscribe.mock.calls).toHaveLength(1);\n", " });\n", "\n" ], "file_path": "public/app/features/dashboard/components/DashboardRow/DashboardRow.test.tsx", "type": "add", "edit_start_line_idx": 33 }
import React from 'react'; import classNames from 'classnames'; import { Icon } from '@grafana/ui'; import { PanelModel } from '../../state/PanelModel'; import { DashboardModel } from '../../state/DashboardModel'; import appEvents from 'app/core/app_events'; import { CoreEvents } from 'app/types'; import { RowOptionsButton } from '../RowOptions/RowOptionsButton'; import { getTemplateSrv } from '@grafana/runtime'; import { ShowConfirmModalEvent } from '../../../../types/events'; export interface DashboardRowProps { panel: PanelModel; dashboard: DashboardModel; } export class DashboardRow extends React.Component<DashboardRowProps, any> { constructor(props: DashboardRowProps) { super(props); this.state = { collapsed: this.props.panel.collapsed, }; this.props.dashboard.on(CoreEvents.templateVariableValueUpdated, this.onVariableUpdated); } componentWillUnmount() { this.props.dashboard.off(CoreEvents.templateVariableValueUpdated, this.onVariableUpdated); } onVariableUpdated = () => { this.forceUpdate(); }; onToggle = () => { this.props.dashboard.toggleRow(this.props.panel); this.setState((prevState: any) => { return { collapsed: !prevState.collapsed }; }); }; onUpdate = (title: string, repeat: string | undefined) => { this.props.panel['title'] = title; this.props.panel['repeat'] = repeat; this.props.panel.render(); this.props.dashboard.processRepeats(); this.forceUpdate(); }; onDelete = () => { appEvents.publish( new ShowConfirmModalEvent({ title: 'Delete row', text: 'Are you sure you want to remove this row and all its panels?', altActionText: 'Delete row only', icon: 'trash-alt', onConfirm: () => { this.props.dashboard.removeRow(this.props.panel, true); }, onAltAction: () => { this.props.dashboard.removeRow(this.props.panel, false); }, }) ); }; render() { const classes = classNames({ 'dashboard-row': true, 'dashboard-row--collapsed': this.state.collapsed, }); const title = getTemplateSrv().replace(this.props.panel.title, this.props.panel.scopedVars, 'text'); const count = this.props.panel.panels ? this.props.panel.panels.length : 0; const panels = count === 1 ? 'panel' : 'panels'; const canEdit = this.props.dashboard.meta.canEdit === true; return ( <div className={classes}> <a className="dashboard-row__title pointer" onClick={this.onToggle}> <Icon name={this.state.collapsed ? 'angle-right' : 'angle-down'} /> {title} <span className="dashboard-row__panel_count"> ({count} {panels}) </span> </a> {canEdit && ( <div className="dashboard-row__actions"> <RowOptionsButton title={this.props.panel.title} repeat={this.props.panel.repeat} onUpdate={this.onUpdate} /> <a className="pointer" onClick={this.onDelete}> <Icon name="trash-alt" /> </a> </div> )} {this.state.collapsed === true && ( <div className="dashboard-row__toggle-target" onClick={this.onToggle}> &nbsp; </div> )} {canEdit && <div className="dashboard-row__drag grid-drag-handle" />} </div> ); } }
public/app/features/dashboard/components/DashboardRow/DashboardRow.tsx
1
https://github.com/grafana/grafana/commit/395d7eb74cdce7c2a405bba80738cd4a3d342784
[ 0.034559160470962524, 0.0031490635592490435, 0.00016679218970239162, 0.0002343626692891121, 0.009471982717514038 ]
{ "id": 1, "code_window": [ "\n", " expect(wrapper.find('.dashboard-row--collapsed')).toHaveLength(1);\n", " expect(dashboardMock.toggleRow.mock.calls).toHaveLength(1);\n", " });\n", "\n", " it('should have two actions as admin', () => {\n", " expect(wrapper.find('.dashboard-row__actions .pointer')).toHaveLength(2);\n", " });\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " it('Should subscribe to event during mount', () => {\n", " expect(dashboardMock.events.subscribe.mock.calls).toHaveLength(1);\n", " });\n", "\n" ], "file_path": "public/app/features/dashboard/components/DashboardRow/DashboardRow.test.tsx", "type": "add", "edit_start_line_idx": 33 }
// // Code (inline and blocK) // -------------------------------------------------- // Inline and block code styles code, pre { @include font-family-monospace(); font-size: $font-size-base - 2; background-color: $code-tag-bg; color: $text-color; border: 1px solid $code-tag-border; border-radius: 4px; } // Inline code code { color: $text-color; white-space: nowrap; padding: 2px 5px; margin: 0 2px; } code.code--small { font-size: $font-size-xs; padding: $space-xxs; margin: 0 2px; } // Blocks of code pre { display: block; margin: 0 0 $line-height-base; line-height: $line-height-base; word-break: break-all; word-wrap: break-word; white-space: pre; white-space: pre-wrap; background-color: $code-tag-bg; padding: 10px; &.pre--no-style { background: transparent; border: none; padding: 0px; } // Make prettyprint styles more spaced out for readability &.prettyprint { margin-bottom: $line-height-base; } // Account for some code outputs that place code tags in pre tags code { padding: 0; color: inherit; white-space: pre; white-space: pre-wrap; background-color: transparent; border: 0; } }
public/sass/base/_code.scss
0
https://github.com/grafana/grafana/commit/395d7eb74cdce7c2a405bba80738cd4a3d342784
[ 0.00017744794604368508, 0.00017563732399139553, 0.00017231734818778932, 0.00017581312567926943, 0.000001533003796794219 ]
{ "id": 1, "code_window": [ "\n", " expect(wrapper.find('.dashboard-row--collapsed')).toHaveLength(1);\n", " expect(dashboardMock.toggleRow.mock.calls).toHaveLength(1);\n", " });\n", "\n", " it('should have two actions as admin', () => {\n", " expect(wrapper.find('.dashboard-row__actions .pointer')).toHaveLength(2);\n", " });\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " it('Should subscribe to event during mount', () => {\n", " expect(dashboardMock.events.subscribe.mock.calls).toHaveLength(1);\n", " });\n", "\n" ], "file_path": "public/app/features/dashboard/components/DashboardRow/DashboardRow.test.tsx", "type": "add", "edit_start_line_idx": 33 }
import { cloneDeep } from 'lodash'; import { LoadingState, VariableType } from '@grafana/data'; import { reducerTester } from '../../../../test/core/redux/reducerTester'; import { addVariable, changeVariableOrder, changeVariableProp, changeVariableType, duplicateVariable, removeVariable, setCurrentVariableValue, sharedReducer, variableStateCompleted, variableStateFailed, variableStateFetching, variableStateNotStarted, } from './sharedReducer'; import { ConstantVariableModel, QueryVariableModel, VariableHide, VariableOption } from '../types'; import { ALL_VARIABLE_TEXT, ALL_VARIABLE_VALUE, toVariablePayload, VariableIdentifier, initialVariablesState, VariablesState, } from './types'; import { variableAdapters } from '../adapters'; import { createQueryVariableAdapter } from '../query/adapter'; import { initialQueryVariableModelState } from '../query/reducer'; import { getVariableState, getVariableTestContext } from './helpers'; import { changeVariableNameSucceeded } from '../editor/reducer'; import { createConstantVariableAdapter } from '../constant/adapter'; import { initialConstantVariableModelState } from '../constant/reducer'; variableAdapters.setInit(() => [createQueryVariableAdapter(), createConstantVariableAdapter()]); describe('sharedReducer', () => { describe('when addVariable is dispatched', () => { it('then state should be correct', () => { const model: any = { name: 'name from model', type: 'type from model', current: undefined, }; const expected: QueryVariableModel = { ...initialQueryVariableModelState, id: 'name from model', global: true, index: 0, name: 'name from model', type: ('type from model' as unknown) as VariableType, current: ({} as unknown) as VariableOption, }; const payload = toVariablePayload({ id: 'name from model', type: 'query' }, { global: true, index: 0, model }); reducerTester<VariablesState>() .givenReducer(sharedReducer, { ...initialVariablesState }) .whenActionIsDispatched(addVariable(payload)) .thenStateShouldEqual({ ['name from model']: expected, }); }); }); describe('when addVariable is dispatched for a constant model', () => { it('then state should be correct', () => { const model: any = { name: 'constant', type: 'constant', query: 'a constant', current: { selected: true, text: 'A', value: 'A' }, options: [{ selected: true, text: 'A', value: 'A' }], }; const expected: ConstantVariableModel = { ...initialConstantVariableModelState, id: 'constant', global: true, index: 0, name: 'constant', type: 'constant', query: 'a constant', current: { selected: true, text: 'a constant', value: 'a constant' }, options: [{ selected: true, text: 'a constant', value: 'a constant' }], }; const payload = toVariablePayload({ id: 'constant', type: 'constant' }, { global: true, index: 0, model }); reducerTester<VariablesState>() .givenReducer(sharedReducer, { ...initialVariablesState }) .whenActionIsDispatched(addVariable(payload)) .thenStateShouldEqual({ ['constant']: expected, }); }); }); describe('when removeVariable is dispatched and reIndex is true', () => { it('then state should be correct', () => { const initialState: VariablesState = getVariableState(3); const payload = toVariablePayload({ id: '1', type: 'query' }, { reIndex: true }); reducerTester<VariablesState>() .givenReducer(sharedReducer, initialState) .whenActionIsDispatched(removeVariable(payload)) .thenStateShouldEqual({ '0': { id: '0', type: 'query', name: 'Name-0', hide: VariableHide.dontHide, index: 0, label: 'Label-0', skipUrlSync: false, global: false, state: LoadingState.NotStarted, error: null, description: null, }, '2': { id: '2', type: 'query', name: 'Name-2', hide: VariableHide.dontHide, index: 1, label: 'Label-2', skipUrlSync: false, global: false, state: LoadingState.NotStarted, error: null, description: null, }, }); }); }); describe('when removeVariable is dispatched and reIndex is false', () => { it('then state should be correct', () => { const initialState: VariablesState = getVariableState(3); const payload = toVariablePayload({ id: '1', type: 'query' }, { reIndex: false }); reducerTester<VariablesState>() .givenReducer(sharedReducer, initialState) .whenActionIsDispatched(removeVariable(payload)) .thenStateShouldEqual({ '0': { id: '0', type: 'query', name: 'Name-0', hide: VariableHide.dontHide, index: 0, label: 'Label-0', skipUrlSync: false, global: false, state: LoadingState.NotStarted, error: null, description: null, }, '2': { id: '2', type: 'query', name: 'Name-2', hide: VariableHide.dontHide, index: 2, label: 'Label-2', skipUrlSync: false, global: false, state: LoadingState.NotStarted, error: null, description: null, }, }); }); }); describe('when duplicateVariable is dispatched', () => { it('then state should be correct', () => { const initialState: VariablesState = getVariableState(3); const payload = toVariablePayload({ id: '1', type: 'query' }, { newId: '11' }); reducerTester<VariablesState>() .givenReducer(sharedReducer, initialState) .whenActionIsDispatched(duplicateVariable(payload)) .thenStateShouldEqual({ '0': { id: '0', type: 'query', name: 'Name-0', hide: VariableHide.dontHide, index: 0, label: 'Label-0', skipUrlSync: false, global: false, state: LoadingState.NotStarted, error: null, description: null, }, '1': { id: '1', type: 'query', name: 'Name-1', hide: VariableHide.dontHide, index: 1, label: 'Label-1', skipUrlSync: false, global: false, state: LoadingState.NotStarted, error: null, description: null, }, '2': { id: '2', type: 'query', name: 'Name-2', hide: VariableHide.dontHide, index: 2, label: 'Label-2', skipUrlSync: false, global: false, state: LoadingState.NotStarted, error: null, description: null, }, '11': { ...initialQueryVariableModelState, id: '11', name: 'copy_of_Name-1', index: 3, label: 'Label-1', }, }); }); }); describe('when changeVariableOrder is dispatched', () => { it('then state should be correct', () => { const initialState: VariablesState = getVariableState(3); const payload = toVariablePayload({ id: '1', type: 'query' }, { fromIndex: 1, toIndex: 0 }); reducerTester<VariablesState>() .givenReducer(sharedReducer, initialState) .whenActionIsDispatched(changeVariableOrder(payload)) .thenStateShouldEqual({ '0': { id: '0', type: 'query', name: 'Name-0', hide: VariableHide.dontHide, index: 1, label: 'Label-0', skipUrlSync: false, global: false, state: LoadingState.NotStarted, error: null, description: null, }, '1': { id: '1', type: 'query', name: 'Name-1', hide: VariableHide.dontHide, index: 0, label: 'Label-1', skipUrlSync: false, global: false, state: LoadingState.NotStarted, error: null, description: null, }, '2': { id: '2', type: 'query', name: 'Name-2', hide: VariableHide.dontHide, index: 2, label: 'Label-2', skipUrlSync: false, global: false, state: LoadingState.NotStarted, error: null, description: null, }, }); }); }); describe('when setCurrentVariableValue is dispatched and current.text is an Array with values', () => { it('then state should be correct', () => { const adapter = createQueryVariableAdapter(); const { initialState } = getVariableTestContext(adapter, { options: [ { text: 'All', value: '$__all', selected: false }, { text: 'A', value: 'A', selected: false }, { text: 'B', value: 'B', selected: false }, ], }); const current = { text: ['A', 'B'], selected: true, value: ['A', 'B'] }; const payload = toVariablePayload({ id: '0', type: 'query' }, { option: current }); reducerTester<VariablesState>() .givenReducer(sharedReducer, cloneDeep(initialState)) .whenActionIsDispatched(setCurrentVariableValue(payload)) .thenStateShouldEqual({ ...initialState, '0': ({ ...initialState[0], options: [ { selected: false, text: 'All', value: '$__all' }, { selected: true, text: 'A', value: 'A' }, { selected: true, text: 'B', value: 'B' }, ], current: { selected: true, text: ['A', 'B'], value: ['A', 'B'] }, } as unknown) as QueryVariableModel, }); }); }); describe('when setCurrentVariableValue is dispatched and current.value is an Array with values except All value', () => { it('then state should be correct', () => { const adapter = createQueryVariableAdapter(); const { initialState } = getVariableTestContext(adapter, { options: [ { text: 'All', value: '$__all', selected: false }, { text: 'A', value: 'A', selected: false }, { text: 'B', value: 'B', selected: false }, ], }); const current = { text: 'A + B', selected: true, value: ['A', 'B'] }; const payload = toVariablePayload({ id: '0', type: 'query' }, { option: current }); reducerTester<VariablesState>() .givenReducer(sharedReducer, cloneDeep(initialState)) .whenActionIsDispatched(setCurrentVariableValue(payload)) .thenStateShouldEqual({ ...initialState, '0': ({ ...initialState[0], options: [ { selected: false, text: 'All', value: '$__all' }, { selected: true, text: 'A', value: 'A' }, { selected: true, text: 'B', value: 'B' }, ], current: { selected: true, text: 'A + B', value: ['A', 'B'] }, } as unknown) as QueryVariableModel, }); }); }); describe('when setCurrentVariableValue is dispatched and current.value is an Array with values containing All value', () => { it('then state should be correct', () => { const adapter = createQueryVariableAdapter(); const { initialState } = getVariableTestContext(adapter, { options: [ { text: 'All', value: '$__all', selected: false }, { text: 'A', value: 'A', selected: false }, { text: 'B', value: 'B', selected: false }, ], }); const current = { text: ALL_VARIABLE_TEXT, selected: true, value: [ALL_VARIABLE_VALUE] }; const payload = toVariablePayload({ id: '0', type: 'query' }, { option: current }); reducerTester<VariablesState>() .givenReducer(sharedReducer, cloneDeep(initialState)) .whenActionIsDispatched(setCurrentVariableValue(payload)) .thenStateShouldEqual({ ...initialState, '0': ({ ...initialState[0], options: [ { selected: true, text: 'All', value: '$__all' }, { selected: false, text: 'A', value: 'A' }, { selected: false, text: 'B', value: 'B' }, ], current: { selected: true, text: 'All', value: ['$__all'] }, } as unknown) as QueryVariableModel, }); }); }); describe('when variableStateNotStarted is dispatched', () => { it('then state should be correct', () => { const adapter = createQueryVariableAdapter(); const { initialState } = getVariableTestContext(adapter, { state: LoadingState.Done, error: 'Some error', }); const payload = toVariablePayload({ id: '0', type: 'query' }); reducerTester<VariablesState>() .givenReducer(sharedReducer, cloneDeep(initialState)) .whenActionIsDispatched(variableStateNotStarted(payload)) .thenStateShouldEqual({ ...initialState, '0': ({ ...initialState[0], state: LoadingState.NotStarted, error: null, } as unknown) as QueryVariableModel, }); }); }); describe('when variableStateFetching is dispatched', () => { it('then state should be correct', () => { const adapter = createQueryVariableAdapter(); const { initialState } = getVariableTestContext(adapter, { state: LoadingState.Done, error: 'Some error', }); const payload = toVariablePayload({ id: '0', type: 'query' }); reducerTester<VariablesState>() .givenReducer(sharedReducer, cloneDeep(initialState)) .whenActionIsDispatched(variableStateFetching(payload)) .thenStateShouldEqual({ ...initialState, '0': ({ ...initialState[0], state: LoadingState.Loading, error: null, } as unknown) as QueryVariableModel, }); }); }); describe('when variableStateCompleted is dispatched', () => { it('then state should be correct', () => { const adapter = createQueryVariableAdapter(); const { initialState } = getVariableTestContext(adapter, { state: LoadingState.Loading, error: 'Some error', }); const payload = toVariablePayload({ id: '0', type: 'query' }); reducerTester<VariablesState>() .givenReducer(sharedReducer, cloneDeep(initialState)) .whenActionIsDispatched(variableStateCompleted(payload)) .thenStateShouldEqual({ ...initialState, '0': ({ ...initialState[0], state: LoadingState.Done, error: null, } as unknown) as QueryVariableModel, }); }); }); describe('when variableStateFailed is dispatched', () => { it('then state should be correct', () => { const adapter = createQueryVariableAdapter(); const { initialState } = getVariableTestContext(adapter, { state: LoadingState.Loading }); const payload = toVariablePayload({ id: '0', type: 'query' }, { error: 'Some error' }); reducerTester<VariablesState>() .givenReducer(sharedReducer, cloneDeep(initialState)) .whenActionIsDispatched(variableStateFailed(payload)) .thenStateShouldEqual({ ...initialState, '0': ({ ...initialState[0], state: LoadingState.Error, error: 'Some error', } as unknown) as QueryVariableModel, }); }); }); describe('when changeVariableProp is dispatched', () => { it('then state should be correct', () => { const adapter = createQueryVariableAdapter(); const { initialState } = getVariableTestContext(adapter); const propName = 'label'; const propValue = 'Updated label'; const payload = toVariablePayload({ id: '0', type: 'query' }, { propName, propValue }); reducerTester<VariablesState>() .givenReducer(sharedReducer, cloneDeep(initialState)) .whenActionIsDispatched(changeVariableProp(payload)) .thenStateShouldEqual({ ...initialState, '0': { ...initialState[0], label: 'Updated label', }, }); }); }); describe('when changeVariableNameSucceeded is dispatched', () => { it('then state should be correct', () => { const adapter = createQueryVariableAdapter(); const { initialState } = getVariableTestContext(adapter); const newName = 'A new name'; const payload = toVariablePayload({ id: '0', type: 'query' }, { newName }); reducerTester<VariablesState>() .givenReducer(sharedReducer, cloneDeep(initialState)) .whenActionIsDispatched(changeVariableNameSucceeded(payload)) .thenStateShouldEqual({ ...initialState, '0': { ...initialState[0], name: 'A new name', }, }); }); }); describe('when changeVariableType is dispatched', () => { it('then state should be correct', () => { const queryAdapter = createQueryVariableAdapter(); const { initialState: queryAdapterState } = getVariableTestContext(queryAdapter); const constantAdapter = createConstantVariableAdapter(); const { initialState: constantAdapterState } = getVariableTestContext(constantAdapter); const newType = 'constant' as VariableType; const identifier: VariableIdentifier = { id: '0', type: 'query' }; const payload = toVariablePayload(identifier, { newType }); reducerTester<VariablesState>() .givenReducer(sharedReducer, cloneDeep(queryAdapterState)) .whenActionIsDispatched(changeVariableNameSucceeded(toVariablePayload(identifier, { newName: 'test' }))) .whenActionIsDispatched( changeVariableProp(toVariablePayload(identifier, { propName: 'description', propValue: 'new description' })) ) .whenActionIsDispatched( changeVariableProp(toVariablePayload(identifier, { propName: 'label', propValue: 'new label' })) ) .whenActionIsDispatched(changeVariableType(payload)) .thenStateShouldEqual({ ...constantAdapterState, '0': { ...constantAdapterState[0], name: 'test', description: 'new description', label: 'new label', type: 'constant', }, }); }); }); });
public/app/features/variables/state/sharedReducer.test.ts
0
https://github.com/grafana/grafana/commit/395d7eb74cdce7c2a405bba80738cd4a3d342784
[ 0.00017879015649668872, 0.0001745693589327857, 0.0001677789114182815, 0.0001747759961290285, 0.000002397217713223654 ]
{ "id": 1, "code_window": [ "\n", " expect(wrapper.find('.dashboard-row--collapsed')).toHaveLength(1);\n", " expect(dashboardMock.toggleRow.mock.calls).toHaveLength(1);\n", " });\n", "\n", " it('should have two actions as admin', () => {\n", " expect(wrapper.find('.dashboard-row__actions .pointer')).toHaveLength(2);\n", " });\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " it('Should subscribe to event during mount', () => {\n", " expect(dashboardMock.events.subscribe.mock.calls).toHaveLength(1);\n", " });\n", "\n" ], "file_path": "public/app/features/dashboard/components/DashboardRow/DashboardRow.test.tsx", "type": "add", "edit_start_line_idx": 33 }
<svg xmlns="http://www.w3.org/2000/svg" width="64" height="64" viewBox="0 0 24 24" fill="none" stroke="#d8d9da" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-arrow-left"><line x1="19" y1="12" x2="5" y2="12"></line><polyline points="12 19 5 12 12 5"></polyline></svg>
public/img/icons_dark_theme/icon_arrow_left.svg
0
https://github.com/grafana/grafana/commit/395d7eb74cdce7c2a405bba80738cd4a3d342784
[ 0.0001740794541547075, 0.0001740794541547075, 0.0001740794541547075, 0.0001740794541547075, 0 ]
{ "id": 2, "code_window": [ "import { PanelModel } from '../../state/PanelModel';\n", "import { DashboardModel } from '../../state/DashboardModel';\n", "import appEvents from 'app/core/app_events';\n", "import { CoreEvents } from 'app/types';\n", "import { RowOptionsButton } from '../RowOptions/RowOptionsButton';\n", "import { getTemplateSrv } from '@grafana/runtime';\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep" ], "after_edit": [], "file_path": "public/app/features/dashboard/components/DashboardRow/DashboardRow.tsx", "type": "replace", "edit_start_line_idx": 6 }
import React from 'react'; import classNames from 'classnames'; import { Icon } from '@grafana/ui'; import { PanelModel } from '../../state/PanelModel'; import { DashboardModel } from '../../state/DashboardModel'; import appEvents from 'app/core/app_events'; import { CoreEvents } from 'app/types'; import { RowOptionsButton } from '../RowOptions/RowOptionsButton'; import { getTemplateSrv } from '@grafana/runtime'; import { ShowConfirmModalEvent } from '../../../../types/events'; export interface DashboardRowProps { panel: PanelModel; dashboard: DashboardModel; } export class DashboardRow extends React.Component<DashboardRowProps, any> { constructor(props: DashboardRowProps) { super(props); this.state = { collapsed: this.props.panel.collapsed, }; this.props.dashboard.on(CoreEvents.templateVariableValueUpdated, this.onVariableUpdated); } componentWillUnmount() { this.props.dashboard.off(CoreEvents.templateVariableValueUpdated, this.onVariableUpdated); } onVariableUpdated = () => { this.forceUpdate(); }; onToggle = () => { this.props.dashboard.toggleRow(this.props.panel); this.setState((prevState: any) => { return { collapsed: !prevState.collapsed }; }); }; onUpdate = (title: string, repeat: string | undefined) => { this.props.panel['title'] = title; this.props.panel['repeat'] = repeat; this.props.panel.render(); this.props.dashboard.processRepeats(); this.forceUpdate(); }; onDelete = () => { appEvents.publish( new ShowConfirmModalEvent({ title: 'Delete row', text: 'Are you sure you want to remove this row and all its panels?', altActionText: 'Delete row only', icon: 'trash-alt', onConfirm: () => { this.props.dashboard.removeRow(this.props.panel, true); }, onAltAction: () => { this.props.dashboard.removeRow(this.props.panel, false); }, }) ); }; render() { const classes = classNames({ 'dashboard-row': true, 'dashboard-row--collapsed': this.state.collapsed, }); const title = getTemplateSrv().replace(this.props.panel.title, this.props.panel.scopedVars, 'text'); const count = this.props.panel.panels ? this.props.panel.panels.length : 0; const panels = count === 1 ? 'panel' : 'panels'; const canEdit = this.props.dashboard.meta.canEdit === true; return ( <div className={classes}> <a className="dashboard-row__title pointer" onClick={this.onToggle}> <Icon name={this.state.collapsed ? 'angle-right' : 'angle-down'} /> {title} <span className="dashboard-row__panel_count"> ({count} {panels}) </span> </a> {canEdit && ( <div className="dashboard-row__actions"> <RowOptionsButton title={this.props.panel.title} repeat={this.props.panel.repeat} onUpdate={this.onUpdate} /> <a className="pointer" onClick={this.onDelete}> <Icon name="trash-alt" /> </a> </div> )} {this.state.collapsed === true && ( <div className="dashboard-row__toggle-target" onClick={this.onToggle}> &nbsp; </div> )} {canEdit && <div className="dashboard-row__drag grid-drag-handle" />} </div> ); } }
public/app/features/dashboard/components/DashboardRow/DashboardRow.tsx
1
https://github.com/grafana/grafana/commit/395d7eb74cdce7c2a405bba80738cd4a3d342784
[ 0.7508561611175537, 0.06662028282880783, 0.00017645230400376022, 0.0003995370934717357, 0.206593856215477 ]
{ "id": 2, "code_window": [ "import { PanelModel } from '../../state/PanelModel';\n", "import { DashboardModel } from '../../state/DashboardModel';\n", "import appEvents from 'app/core/app_events';\n", "import { CoreEvents } from 'app/types';\n", "import { RowOptionsButton } from '../RowOptions/RowOptionsButton';\n", "import { getTemplateSrv } from '@grafana/runtime';\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep" ], "after_edit": [], "file_path": "public/app/features/dashboard/components/DashboardRow/DashboardRow.tsx", "type": "replace", "edit_start_line_idx": 6 }
[paths] data = /tmp/override
pkg/setting/testdata/override.ini
0
https://github.com/grafana/grafana/commit/395d7eb74cdce7c2a405bba80738cd4a3d342784
[ 0.00017061228572856635, 0.00017061228572856635, 0.00017061228572856635, 0.00017061228572856635, 0 ]
{ "id": 2, "code_window": [ "import { PanelModel } from '../../state/PanelModel';\n", "import { DashboardModel } from '../../state/DashboardModel';\n", "import appEvents from 'app/core/app_events';\n", "import { CoreEvents } from 'app/types';\n", "import { RowOptionsButton } from '../RowOptions/RowOptionsButton';\n", "import { getTemplateSrv } from '@grafana/runtime';\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep" ], "after_edit": [], "file_path": "public/app/features/dashboard/components/DashboardRow/DashboardRow.tsx", "type": "replace", "edit_start_line_idx": 6 }
import React from 'react'; import { getBackendSrv } from '@grafana/runtime'; import { UserOrgDTO } from '@grafana/data'; import { Modal, Button, CustomScrollbar } from '@grafana/ui'; import { contextSrv } from 'app/core/services/context_srv'; import config from 'app/core/config'; import { css } from '@emotion/css'; interface Props { onDismiss: () => void; } interface State { orgs: UserOrgDTO[]; } export class OrgSwitcher extends React.PureComponent<Props, State> { state: State = { orgs: [], }; componentDidMount() { this.getUserOrgs(); } getUserOrgs = async () => { const orgs: UserOrgDTO[] = await getBackendSrv().get('/api/user/orgs'); this.setState({ orgs }); }; setCurrentOrg = async (org: UserOrgDTO) => { await getBackendSrv().post(`/api/user/using/${org.orgId}`); this.setWindowLocation(`${config.appSubUrl}${config.appSubUrl.endsWith('/') ? '' : '/'}?orgId=${org.orgId}`); }; setWindowLocation(href: string) { window.location.href = href; } render() { const { onDismiss } = this.props; const { orgs } = this.state; const currentOrgId = contextSrv.user.orgId; const contentClassName = css({ display: 'flex', maxHeight: 'calc(85vh - 42px)', }); return ( <Modal title="Switch Organization" icon="arrow-random" onDismiss={onDismiss} isOpen={true} contentClassName={contentClassName} > <CustomScrollbar autoHeightMin="100%"> <table className="filter-table form-inline"> <thead> <tr> <th>Name</th> <th>Role</th> <th /> </tr> </thead> <tbody> {orgs.map((org) => ( <tr key={org.orgId}> <td>{org.name}</td> <td>{org.role}</td> <td className="text-right"> {org.orgId === currentOrgId ? ( <Button size="sm">Current</Button> ) : ( <Button variant="secondary" size="sm" onClick={() => this.setCurrentOrg(org)}> Switch to </Button> )} </td> </tr> ))} </tbody> </table> </CustomScrollbar> </Modal> ); } }
public/app/core/components/OrgSwitcher.tsx
0
https://github.com/grafana/grafana/commit/395d7eb74cdce7c2a405bba80738cd4a3d342784
[ 0.00023934566706884652, 0.0001781473110895604, 0.00016523676458746195, 0.00017326895613223314, 0.000020781693820026703 ]
{ "id": 2, "code_window": [ "import { PanelModel } from '../../state/PanelModel';\n", "import { DashboardModel } from '../../state/DashboardModel';\n", "import appEvents from 'app/core/app_events';\n", "import { CoreEvents } from 'app/types';\n", "import { RowOptionsButton } from '../RowOptions/RowOptionsButton';\n", "import { getTemplateSrv } from '@grafana/runtime';\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep" ], "after_edit": [], "file_path": "public/app/features/dashboard/components/DashboardRow/DashboardRow.tsx", "type": "replace", "edit_start_line_idx": 6 }
<div class="modal-body" ng-cloak> <div class="modal-header"> <h2 class="modal-header-title"> <icon name="'{{icon}}'" size="'lg'"></icon> <span class="p-l-1"> {{title}} </span> </h2> <a class="modal-header-close" ng-click="dismiss();"> <icon name="'times'"></icon> </a> </div> <div class="modal-content text-center"> <div class="confirm-modal-text"> {{text}} <div ng-if="text2 && text2htmlBind" class="confirm-modal-text2" ng-bind-html="text2"></div> <div ng-if="text2 && !text2htmlBind" class="confirm-modal-text2">{{text2}}</div> </div> <div class="modal-content-confirm-text" ng-if="confirmText"> <input type="text" class="gf-form-input width-16" style="display: inline-block;" placeholder="Type {{confirmText}} to confirm" ng-model="confirmInput" ng-change="updateConfirmText(confirmInput)" /> </div> <div class="confirm-modal-buttons"> <button ng-show="onAltAction" type="button" class="btn btn-primary" ng-click="dismiss();onAltAction();"> {{altActionText}} </button> <button ng-show="onConfirm" type="button" class="btn btn-danger" ng-click="onConfirm();dismiss();" ng-disabled="!confirmTextValid" give-focus="true" aria-label="{{selectors.delete}}" > {{yesText}} </button> <button type="button" class="btn btn-inverse" ng-click="dismiss()">{{noText}}</button> </div> </div> </div>
public/app/partials/confirm_modal.html
0
https://github.com/grafana/grafana/commit/395d7eb74cdce7c2a405bba80738cd4a3d342784
[ 0.0001764714834280312, 0.0001722643501125276, 0.00016719807172194123, 0.00017277561710216105, 0.0000030828637136437465 ]
{ "id": 3, "code_window": [ "import { RowOptionsButton } from '../RowOptions/RowOptionsButton';\n", "import { getTemplateSrv } from '@grafana/runtime';\n", "import { ShowConfirmModalEvent } from '../../../../types/events';\n", "\n", "export interface DashboardRowProps {\n", " panel: PanelModel;\n", " dashboard: DashboardModel;\n" ], "labels": [ "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { RefreshEvent, ShowConfirmModalEvent } from '../../../../types/events';\n", "import { Unsubscribable } from 'rxjs';\n" ], "file_path": "public/app/features/dashboard/components/DashboardRow/DashboardRow.tsx", "type": "replace", "edit_start_line_idx": 9 }
import React from 'react'; import classNames from 'classnames'; import { Icon } from '@grafana/ui'; import { PanelModel } from '../../state/PanelModel'; import { DashboardModel } from '../../state/DashboardModel'; import appEvents from 'app/core/app_events'; import { CoreEvents } from 'app/types'; import { RowOptionsButton } from '../RowOptions/RowOptionsButton'; import { getTemplateSrv } from '@grafana/runtime'; import { ShowConfirmModalEvent } from '../../../../types/events'; export interface DashboardRowProps { panel: PanelModel; dashboard: DashboardModel; } export class DashboardRow extends React.Component<DashboardRowProps, any> { constructor(props: DashboardRowProps) { super(props); this.state = { collapsed: this.props.panel.collapsed, }; this.props.dashboard.on(CoreEvents.templateVariableValueUpdated, this.onVariableUpdated); } componentWillUnmount() { this.props.dashboard.off(CoreEvents.templateVariableValueUpdated, this.onVariableUpdated); } onVariableUpdated = () => { this.forceUpdate(); }; onToggle = () => { this.props.dashboard.toggleRow(this.props.panel); this.setState((prevState: any) => { return { collapsed: !prevState.collapsed }; }); }; onUpdate = (title: string, repeat: string | undefined) => { this.props.panel['title'] = title; this.props.panel['repeat'] = repeat; this.props.panel.render(); this.props.dashboard.processRepeats(); this.forceUpdate(); }; onDelete = () => { appEvents.publish( new ShowConfirmModalEvent({ title: 'Delete row', text: 'Are you sure you want to remove this row and all its panels?', altActionText: 'Delete row only', icon: 'trash-alt', onConfirm: () => { this.props.dashboard.removeRow(this.props.panel, true); }, onAltAction: () => { this.props.dashboard.removeRow(this.props.panel, false); }, }) ); }; render() { const classes = classNames({ 'dashboard-row': true, 'dashboard-row--collapsed': this.state.collapsed, }); const title = getTemplateSrv().replace(this.props.panel.title, this.props.panel.scopedVars, 'text'); const count = this.props.panel.panels ? this.props.panel.panels.length : 0; const panels = count === 1 ? 'panel' : 'panels'; const canEdit = this.props.dashboard.meta.canEdit === true; return ( <div className={classes}> <a className="dashboard-row__title pointer" onClick={this.onToggle}> <Icon name={this.state.collapsed ? 'angle-right' : 'angle-down'} /> {title} <span className="dashboard-row__panel_count"> ({count} {panels}) </span> </a> {canEdit && ( <div className="dashboard-row__actions"> <RowOptionsButton title={this.props.panel.title} repeat={this.props.panel.repeat} onUpdate={this.onUpdate} /> <a className="pointer" onClick={this.onDelete}> <Icon name="trash-alt" /> </a> </div> )} {this.state.collapsed === true && ( <div className="dashboard-row__toggle-target" onClick={this.onToggle}> &nbsp; </div> )} {canEdit && <div className="dashboard-row__drag grid-drag-handle" />} </div> ); } }
public/app/features/dashboard/components/DashboardRow/DashboardRow.tsx
1
https://github.com/grafana/grafana/commit/395d7eb74cdce7c2a405bba80738cd4a3d342784
[ 0.9993983507156372, 0.08865337818861008, 0.0001738609716994688, 0.003149172756820917, 0.2747747004032135 ]
{ "id": 3, "code_window": [ "import { RowOptionsButton } from '../RowOptions/RowOptionsButton';\n", "import { getTemplateSrv } from '@grafana/runtime';\n", "import { ShowConfirmModalEvent } from '../../../../types/events';\n", "\n", "export interface DashboardRowProps {\n", " panel: PanelModel;\n", " dashboard: DashboardModel;\n" ], "labels": [ "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { RefreshEvent, ShowConfirmModalEvent } from '../../../../types/events';\n", "import { Unsubscribable } from 'rxjs';\n" ], "file_path": "public/app/features/dashboard/components/DashboardRow/DashboardRow.tsx", "type": "replace", "edit_start_line_idx": 9 }
import { locationUtil } from '@grafana/data'; import { locationService, navigationLogger } from '@grafana/runtime'; export function interceptLinkClicks(e: MouseEvent) { const anchor = getParentAnchor(e.target as HTMLElement); // Ignore if opening new tab or already default prevented if (e.ctrlKey || e.metaKey || e.defaultPrevented) { return; } if (anchor) { let href = anchor.getAttribute('href'); const target = anchor.getAttribute('target'); if (href && !target) { navigationLogger('utils', false, 'intercepting link click', e); e.preventDefault(); href = locationUtil.stripBaseFromUrl(href); // Ensure old angular urls with no starting '/' are handled the same as before // Make sure external links are handled correctly // That is they where seen as being absolute from app root if (href[0] !== '/') { try { const external = new URL(href); if (external.origin !== window.location.origin) { window.location.href = external.toString(); return; } } catch (e) { console.warn(e); } href = `/${href}`; } locationService.push(href); } } } function getParentAnchor(element: HTMLElement | null): HTMLElement | null { while (element !== null && element.tagName) { if (element.tagName.toUpperCase() === 'A') { return element; } element = element.parentNode as HTMLElement; } return null; }
public/app/core/navigation/patch/interceptLinkClicks.ts
0
https://github.com/grafana/grafana/commit/395d7eb74cdce7c2a405bba80738cd4a3d342784
[ 0.00017739330360200256, 0.00017478970403317362, 0.0001718570856610313, 0.00017493829363957047, 0.0000017044550304490258 ]
{ "id": 3, "code_window": [ "import { RowOptionsButton } from '../RowOptions/RowOptionsButton';\n", "import { getTemplateSrv } from '@grafana/runtime';\n", "import { ShowConfirmModalEvent } from '../../../../types/events';\n", "\n", "export interface DashboardRowProps {\n", " panel: PanelModel;\n", " dashboard: DashboardModel;\n" ], "labels": [ "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { RefreshEvent, ShowConfirmModalEvent } from '../../../../types/events';\n", "import { Unsubscribable } from 'rxjs';\n" ], "file_path": "public/app/features/dashboard/components/DashboardRow/DashboardRow.tsx", "type": "replace", "edit_start_line_idx": 9 }
import React, { FC } from 'react'; import { config } from '@grafana/runtime'; import { Button, Field, Form, HorizontalGroup, Input, LinkButton } from '@grafana/ui'; import { selectors } from '@grafana/e2e-selectors'; import { Playlist } from './types'; import { DashboardPicker } from '../../core/components/Select/DashboardPicker'; import { TagFilter } from '../../core/components/TagFilter/TagFilter'; import { SearchSrv } from '../../core/services/search_srv'; import { usePlaylistItems } from './usePlaylistItems'; import { PlaylistTable } from './PlaylistTable'; interface PlaylistFormProps { onSubmit: (playlist: Playlist) => void; playlist: Playlist; } const searchSrv = new SearchSrv(); export const PlaylistForm: FC<PlaylistFormProps> = ({ onSubmit, playlist }) => { const { name, interval, items: propItems } = playlist; const { items, addById, addByTag, deleteItem, moveDown, moveUp } = usePlaylistItems(propItems); return ( <> <Form onSubmit={(list: Playlist) => onSubmit({ ...list, items })} validateOn={'onBlur'}> {({ register, errors }) => { const isDisabled = items.length === 0 || Object.keys(errors).length > 0; return ( <> <Field label="Name" invalid={!!errors.name} error={errors?.name?.message}> <Input type="text" {...register('name', { required: 'Name is required' })} placeholder="Name" defaultValue={name} aria-label={selectors.pages.PlaylistForm.name} /> </Field> <Field label="Interval" invalid={!!errors.interval} error={errors?.interval?.message}> <Input type="text" {...register('interval', { required: 'Interval is required' })} placeholder="5m" defaultValue={interval ?? '5m'} aria-label={selectors.pages.PlaylistForm.interval} /> </Field> <PlaylistTable items={items} onMoveUp={moveUp} onMoveDown={moveDown} onDelete={deleteItem} /> <div className="gf-form-group"> <h3 className="page-headering">Add dashboards</h3> <Field label="Add by title"> <DashboardPicker onChange={addById} isClearable /> </Field> <Field label="Add by tag"> <TagFilter isClearable tags={[]} hideValues tagOptions={searchSrv.getDashboardTags} onChange={addByTag} placeholder={''} /> </Field> </div> <HorizontalGroup> <Button variant="primary" disabled={isDisabled}> Save </Button> <LinkButton variant="secondary" href={`${config.appSubUrl}/playlists`}> Cancel </LinkButton> </HorizontalGroup> </> ); }} </Form> </> ); };
public/app/features/playlist/PlaylistForm.tsx
0
https://github.com/grafana/grafana/commit/395d7eb74cdce7c2a405bba80738cd4a3d342784
[ 0.0039323968812823296, 0.0006108618108555675, 0.0001690989447524771, 0.0001756708516040817, 0.0011750567937269807 ]
{ "id": 3, "code_window": [ "import { RowOptionsButton } from '../RowOptions/RowOptionsButton';\n", "import { getTemplateSrv } from '@grafana/runtime';\n", "import { ShowConfirmModalEvent } from '../../../../types/events';\n", "\n", "export interface DashboardRowProps {\n", " panel: PanelModel;\n", " dashboard: DashboardModel;\n" ], "labels": [ "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { RefreshEvent, ShowConfirmModalEvent } from '../../../../types/events';\n", "import { Unsubscribable } from 'rxjs';\n" ], "file_path": "public/app/features/dashboard/components/DashboardRow/DashboardRow.tsx", "type": "replace", "edit_start_line_idx": 9 }
import React, { FC, useState } from 'react'; import { Organization } from 'app/types'; import { Button, ConfirmModal } from '@grafana/ui'; interface Props { orgs: Organization[]; onDelete: (orgId: number) => void; } export const AdminOrgsTable: FC<Props> = ({ orgs, onDelete }) => { const [deleteOrg, setDeleteOrg] = useState<Organization>(); return ( <table className="filter-table form-inline filter-table--hover"> <thead> <tr> <th>ID</th> <th>Name</th> <th style={{ width: '1%' }}></th> </tr> </thead> <tbody> {orgs.map((org) => ( <tr key={`${org.id}-${org.name}`}> <td className="link-td"> <a href={`admin/orgs/edit/${org.id}`}>{org.id}</a> </td> <td className="link-td"> <a href={`admin/orgs/edit/${org.id}`}>{org.name}</a> </td> <td className="text-right"> <Button variant="destructive" size="sm" icon="times" onClick={() => setDeleteOrg(org)} /> </td> </tr> ))} </tbody> {deleteOrg && ( <ConfirmModal isOpen icon="trash-alt" title="Delete" body={ <div> Are you sure you want to delete &apos;{deleteOrg.name}&apos;? <br /> <small>All dashboards for this organization will be removed!</small> </div> } confirmText="Delete" onDismiss={() => setDeleteOrg(undefined)} onConfirm={() => { onDelete(deleteOrg.id); setDeleteOrg(undefined); }} /> )} </table> ); };
public/app/features/admin/AdminOrgsTable.tsx
0
https://github.com/grafana/grafana/commit/395d7eb74cdce7c2a405bba80738cd4a3d342784
[ 0.00022760995489079505, 0.0001817416778067127, 0.0001705343893263489, 0.00017283257329836488, 0.000020594176021404564 ]
{ "id": 4, "code_window": [ " panel: PanelModel;\n", " dashboard: DashboardModel;\n", "}\n", "\n", "export class DashboardRow extends React.Component<DashboardRowProps, any> {\n", " constructor(props: DashboardRowProps) {\n", " super(props);\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " sub?: Unsubscribable;\n" ], "file_path": "public/app/features/dashboard/components/DashboardRow/DashboardRow.tsx", "type": "add", "edit_start_line_idx": 17 }
import React from 'react'; import classNames from 'classnames'; import { Icon } from '@grafana/ui'; import { PanelModel } from '../../state/PanelModel'; import { DashboardModel } from '../../state/DashboardModel'; import appEvents from 'app/core/app_events'; import { CoreEvents } from 'app/types'; import { RowOptionsButton } from '../RowOptions/RowOptionsButton'; import { getTemplateSrv } from '@grafana/runtime'; import { ShowConfirmModalEvent } from '../../../../types/events'; export interface DashboardRowProps { panel: PanelModel; dashboard: DashboardModel; } export class DashboardRow extends React.Component<DashboardRowProps, any> { constructor(props: DashboardRowProps) { super(props); this.state = { collapsed: this.props.panel.collapsed, }; this.props.dashboard.on(CoreEvents.templateVariableValueUpdated, this.onVariableUpdated); } componentWillUnmount() { this.props.dashboard.off(CoreEvents.templateVariableValueUpdated, this.onVariableUpdated); } onVariableUpdated = () => { this.forceUpdate(); }; onToggle = () => { this.props.dashboard.toggleRow(this.props.panel); this.setState((prevState: any) => { return { collapsed: !prevState.collapsed }; }); }; onUpdate = (title: string, repeat: string | undefined) => { this.props.panel['title'] = title; this.props.panel['repeat'] = repeat; this.props.panel.render(); this.props.dashboard.processRepeats(); this.forceUpdate(); }; onDelete = () => { appEvents.publish( new ShowConfirmModalEvent({ title: 'Delete row', text: 'Are you sure you want to remove this row and all its panels?', altActionText: 'Delete row only', icon: 'trash-alt', onConfirm: () => { this.props.dashboard.removeRow(this.props.panel, true); }, onAltAction: () => { this.props.dashboard.removeRow(this.props.panel, false); }, }) ); }; render() { const classes = classNames({ 'dashboard-row': true, 'dashboard-row--collapsed': this.state.collapsed, }); const title = getTemplateSrv().replace(this.props.panel.title, this.props.panel.scopedVars, 'text'); const count = this.props.panel.panels ? this.props.panel.panels.length : 0; const panels = count === 1 ? 'panel' : 'panels'; const canEdit = this.props.dashboard.meta.canEdit === true; return ( <div className={classes}> <a className="dashboard-row__title pointer" onClick={this.onToggle}> <Icon name={this.state.collapsed ? 'angle-right' : 'angle-down'} /> {title} <span className="dashboard-row__panel_count"> ({count} {panels}) </span> </a> {canEdit && ( <div className="dashboard-row__actions"> <RowOptionsButton title={this.props.panel.title} repeat={this.props.panel.repeat} onUpdate={this.onUpdate} /> <a className="pointer" onClick={this.onDelete}> <Icon name="trash-alt" /> </a> </div> )} {this.state.collapsed === true && ( <div className="dashboard-row__toggle-target" onClick={this.onToggle}> &nbsp; </div> )} {canEdit && <div className="dashboard-row__drag grid-drag-handle" />} </div> ); } }
public/app/features/dashboard/components/DashboardRow/DashboardRow.tsx
1
https://github.com/grafana/grafana/commit/395d7eb74cdce7c2a405bba80738cd4a3d342784
[ 0.9959518909454346, 0.29725420475006104, 0.00017975372611545026, 0.024185292422771454, 0.3979610204696655 ]
{ "id": 4, "code_window": [ " panel: PanelModel;\n", " dashboard: DashboardModel;\n", "}\n", "\n", "export class DashboardRow extends React.Component<DashboardRowProps, any> {\n", " constructor(props: DashboardRowProps) {\n", " super(props);\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " sub?: Unsubscribable;\n" ], "file_path": "public/app/features/dashboard/components/DashboardRow/DashboardRow.tsx", "type": "add", "edit_start_line_idx": 17 }
import angular from 'angular'; const coreModule = angular.module('grafana.core', ['ngRoute']); // legacy modules const angularModules = [ coreModule, angular.module('grafana.controllers', []), angular.module('grafana.directives', []), angular.module('grafana.factories', []), angular.module('grafana.services', []), angular.module('grafana.filters', []), angular.module('grafana.routes', []), ]; export { angularModules, coreModule }; export default coreModule;
public/app/core/core_module.ts
0
https://github.com/grafana/grafana/commit/395d7eb74cdce7c2a405bba80738cd4a3d342784
[ 0.00017502647824585438, 0.00017467487487010658, 0.000174323286046274, 0.00017467487487010658, 3.515960997901857e-7 ]
{ "id": 4, "code_window": [ " panel: PanelModel;\n", " dashboard: DashboardModel;\n", "}\n", "\n", "export class DashboardRow extends React.Component<DashboardRowProps, any> {\n", " constructor(props: DashboardRowProps) {\n", " super(props);\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " sub?: Unsubscribable;\n" ], "file_path": "public/app/features/dashboard/components/DashboardRow/DashboardRow.tsx", "type": "add", "edit_start_line_idx": 17 }
<?xml version="1.0" encoding="utf-8"?> <!-- Generator: Adobe Illustrator 19.0.1, SVG Export Plug-In . SVG Version: 6.00 Build 0) --> <!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"> <svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="121px" height="100px" viewBox="0 0 121 100" style="enable-background:new 0 0 121 100;" xml:space="preserve"> <style type="text/css"> .st0{fill:url(#SVGID_1_);} .st1{fill:#FFFFFF;} .st2{fill:url(#SVGID_2_);} .st3{fill:url(#SVGID_3_);} </style> <g> <g> <linearGradient id="SVGID_1_" gradientUnits="userSpaceOnUse" x1="60.5" y1="130.7753" x2="60.5" y2="18.6673"> <stop offset="0" style="stop-color:#FBB017"/> <stop offset="1" style="stop-color:#EF4E28"/> </linearGradient> <path class="st0" d="M120.8,50L87.2,16.4C78.1,6.3,64.9,0,50.2,0c-27.6,0-50,22.4-50,50s22.4,50,50,50c14.4,0,27.5-6.1,36.6-15.9 c0.1-0.1,0.1-0.1,0.2-0.2L120.8,50z"/> </g> <path class="st1" d="M94.1,50c0-24.4-19.9-44.3-44.3-44.3S5.6,25.6,5.6,50s19.9,44.3,44.3,44.3S94.1,74.4,94.1,50z"/> <g> <linearGradient id="SVGID_2_" gradientUnits="userSpaceOnUse" x1="50.2576" y1="115.6711" x2="50.2576" y2="19.8747"> <stop offset="0" style="stop-color:#FBB017"/> <stop offset="1" style="stop-color:#EF4E28"/> </linearGradient> <path class="st2" d="M77.8,65.9H25.4V30.5c0-1.5-1.2-2.8-2.8-2.8c-1.5,0-2.8,1.2-2.8,2.8v38.1c0,1.5,1.2,2.8,2.8,2.8h55.2 c1.5,0,2.8-1.2,2.8-2.8S79.4,65.9,77.8,65.9z"/> <g> <linearGradient id="SVGID_3_" gradientUnits="userSpaceOnUse" x1="53.116" y1="115.6711" x2="53.116" y2="19.8747"> <stop offset="0" style="stop-color:#FBB017"/> <stop offset="1" style="stop-color:#EF4E28"/> </linearGradient> <polygon class="st3" points="77.7,63.1 78,49 62.9,28.3 47.1,49.5 35.8,38.7 28.2,43.1 28.2,63.1 "/> </g> </g> </g> </svg>
public/img/icons_light_theme/icon_visualize_active.svg
0
https://github.com/grafana/grafana/commit/395d7eb74cdce7c2a405bba80738cd4a3d342784
[ 0.00017405654944013804, 0.00017109894542954862, 0.00016570757725276053, 0.00017231582023669034, 0.000003274686378063052 ]
{ "id": 4, "code_window": [ " panel: PanelModel;\n", " dashboard: DashboardModel;\n", "}\n", "\n", "export class DashboardRow extends React.Component<DashboardRowProps, any> {\n", " constructor(props: DashboardRowProps) {\n", " super(props);\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " sub?: Unsubscribable;\n" ], "file_path": "public/app/features/dashboard/components/DashboardRow/DashboardRow.tsx", "type": "add", "edit_start_line_idx": 17 }
import React, { useState } from 'react'; import { Story, Meta } from '@storybook/react'; import { withCenteredStory } from '../../utils/storybook/withCenteredStory'; import mdx from './Input.mdx'; import { getAvailableIcons, IconName } from '../../types'; import { KeyValue } from '@grafana/data'; import { Field, Icon, Button, Input } from '@grafana/ui'; const prefixSuffixOpts = { None: null, Text: '$', ...getAvailableIcons().reduce<KeyValue<string>>((prev, c) => { return { ...prev, [`Icon: ${c}`]: `icon-${c}`, }; }, {}), }; export default { title: 'Forms/Input', component: Input, decorators: [withCenteredStory], parameters: { docs: { page: mdx, }, knobs: { disable: true, }, controls: { exclude: ['prefix', 'suffix', 'addonBefore', 'addonAfter'], }, }, args: { type: 'text', width: 40, prefixVisible: '', suffixVisible: '', invalid: false, loading: false, }, argTypes: { prefixVisible: { control: { type: 'select', options: prefixSuffixOpts, }, }, suffixVisible: { control: { type: 'select', options: prefixSuffixOpts, }, }, type: { control: { type: 'select', options: ['text', 'number', 'password'], }, }, // validation: { name: 'Validation regex (will do a partial match if you do not anchor it)' }, width: { control: { type: 'range', min: 10, max: 200, step: 10 } }, }, } as Meta; export const Simple: Story = (args) => { const addonAfter = <Button variant="secondary">Load</Button>; const addonBefore = <div style={{ display: 'flex', alignItems: 'center', padding: '5px' }}>Input</div>; const prefix = args.prefixVisible; const suffix = args.suffixVisible; let prefixEl: any = prefix; if (prefix && prefix.match(/icon-/g)) { prefixEl = <Icon name={prefix.replace(/icon-/g, '') as IconName} />; } let suffixEl: any = suffix; if (suffix && suffix.match(/icon-/g)) { suffixEl = <Icon name={suffix.replace(/icon-/g, '') as IconName} />; } return ( <Input disabled={args.disabled} width={args.width} prefix={prefixEl} invalid={args.invalid} suffix={suffixEl} loading={args.loading} addonBefore={args.before && addonBefore} addonAfter={args.after && addonAfter} type={args.type} placeholder={args.placeholder} /> ); }; Simple.args = { disabled: false, before: false, after: false, placeholder: 'Enter your name here...', }; export const WithFieldValidation: Story = (args) => { const [value, setValue] = useState(''); return ( <div> <Field invalid={value === ''} error={value === '' ? 'This input is required' : ''}> <Input value={value} onChange={(e) => setValue(e.currentTarget.value)} {...args} /> </Field> </div> ); };
packages/grafana-ui/src/components/Input/Input.story.tsx
0
https://github.com/grafana/grafana/commit/395d7eb74cdce7c2a405bba80738cd4a3d342784
[ 0.0003058742731809616, 0.0001864019432105124, 0.00017154715897049755, 0.00017636746633797884, 0.000036082066799281165 ]
{ "id": 5, "code_window": [ " super(props);\n", "\n", " this.state = {\n", " collapsed: this.props.panel.collapsed,\n", " };\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep" ], "after_edit": [ " }\n" ], "file_path": "public/app/features/dashboard/components/DashboardRow/DashboardRow.tsx", "type": "add", "edit_start_line_idx": 23 }
import React from 'react'; import classNames from 'classnames'; import { Icon } from '@grafana/ui'; import { PanelModel } from '../../state/PanelModel'; import { DashboardModel } from '../../state/DashboardModel'; import appEvents from 'app/core/app_events'; import { CoreEvents } from 'app/types'; import { RowOptionsButton } from '../RowOptions/RowOptionsButton'; import { getTemplateSrv } from '@grafana/runtime'; import { ShowConfirmModalEvent } from '../../../../types/events'; export interface DashboardRowProps { panel: PanelModel; dashboard: DashboardModel; } export class DashboardRow extends React.Component<DashboardRowProps, any> { constructor(props: DashboardRowProps) { super(props); this.state = { collapsed: this.props.panel.collapsed, }; this.props.dashboard.on(CoreEvents.templateVariableValueUpdated, this.onVariableUpdated); } componentWillUnmount() { this.props.dashboard.off(CoreEvents.templateVariableValueUpdated, this.onVariableUpdated); } onVariableUpdated = () => { this.forceUpdate(); }; onToggle = () => { this.props.dashboard.toggleRow(this.props.panel); this.setState((prevState: any) => { return { collapsed: !prevState.collapsed }; }); }; onUpdate = (title: string, repeat: string | undefined) => { this.props.panel['title'] = title; this.props.panel['repeat'] = repeat; this.props.panel.render(); this.props.dashboard.processRepeats(); this.forceUpdate(); }; onDelete = () => { appEvents.publish( new ShowConfirmModalEvent({ title: 'Delete row', text: 'Are you sure you want to remove this row and all its panels?', altActionText: 'Delete row only', icon: 'trash-alt', onConfirm: () => { this.props.dashboard.removeRow(this.props.panel, true); }, onAltAction: () => { this.props.dashboard.removeRow(this.props.panel, false); }, }) ); }; render() { const classes = classNames({ 'dashboard-row': true, 'dashboard-row--collapsed': this.state.collapsed, }); const title = getTemplateSrv().replace(this.props.panel.title, this.props.panel.scopedVars, 'text'); const count = this.props.panel.panels ? this.props.panel.panels.length : 0; const panels = count === 1 ? 'panel' : 'panels'; const canEdit = this.props.dashboard.meta.canEdit === true; return ( <div className={classes}> <a className="dashboard-row__title pointer" onClick={this.onToggle}> <Icon name={this.state.collapsed ? 'angle-right' : 'angle-down'} /> {title} <span className="dashboard-row__panel_count"> ({count} {panels}) </span> </a> {canEdit && ( <div className="dashboard-row__actions"> <RowOptionsButton title={this.props.panel.title} repeat={this.props.panel.repeat} onUpdate={this.onUpdate} /> <a className="pointer" onClick={this.onDelete}> <Icon name="trash-alt" /> </a> </div> )} {this.state.collapsed === true && ( <div className="dashboard-row__toggle-target" onClick={this.onToggle}> &nbsp; </div> )} {canEdit && <div className="dashboard-row__drag grid-drag-handle" />} </div> ); } }
public/app/features/dashboard/components/DashboardRow/DashboardRow.tsx
1
https://github.com/grafana/grafana/commit/395d7eb74cdce7c2a405bba80738cd4a3d342784
[ 0.9890726208686829, 0.2974964678287506, 0.00016843258345033973, 0.008890857920050621, 0.4057391285896301 ]
{ "id": 5, "code_window": [ " super(props);\n", "\n", " this.state = {\n", " collapsed: this.props.panel.collapsed,\n", " };\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep" ], "after_edit": [ " }\n" ], "file_path": "public/app/features/dashboard/components/DashboardRow/DashboardRow.tsx", "type": "add", "edit_start_line_idx": 23 }
# Repository updates deb/rpm ## Testing It's possible to test the repo updates for rpm and deb by running the test scripts within a docker container like this. Tests are being executed by using two buckets on gcp setup for testing. ```bash docker run -ti --rm -u 0:0 grafana/grafana-ci-deploy:1.2.3 bash # 1.2.3 is the newest image at the time of writing # in the container: mkdir -p /dist #outside of container: cd <grafana project dir>/.. docker cp grafana <container_name>:/ docker cp <gpg.key used for signing> <container_name>:/private.key #in container: ./scripts/build/update_repo/load-signing-key.sh cd dist && wget https://dl.grafana.com/oss/release/grafana_5.4.3_amd64.deb && wget https://dl.grafana.com/oss/release/grafana-5.4.3-1.x86_64.rpm && cd .. #run these scripts to update local deb and rpm repos and publish them: ./scripts/build/update_repo/test-update-deb-repo.sh <gpg key password> ./scripts/build/update_repo/test-publish-deb-repo.sh ./scripts/build/update_repo/test-update-rpm-repo.sh <gpg key password> ./scripts/build/update_repo/test-publish-rpm-repo.sh ```
scripts/build/update_repo/README.md
0
https://github.com/grafana/grafana/commit/395d7eb74cdce7c2a405bba80738cd4a3d342784
[ 0.00017198757268488407, 0.00016903626965358853, 0.0001636780652916059, 0.0001714431564323604, 0.0000037953325318085263 ]
{ "id": 5, "code_window": [ " super(props);\n", "\n", " this.state = {\n", " collapsed: this.props.panel.collapsed,\n", " };\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep" ], "after_edit": [ " }\n" ], "file_path": "public/app/features/dashboard/components/DashboardRow/DashboardRow.tsx", "type": "add", "edit_start_line_idx": 23 }
import { QueryRunner } from '@grafana/data'; let factory: QueryRunnerFactory | undefined; /** * @internal */ export type QueryRunnerFactory = () => QueryRunner; /** * Used to bootstrap the {@link createQueryRunner} during application start. * * @internal */ export const setQueryRunnerFactory = (instance: QueryRunnerFactory): void => { if (factory) { throw new Error('Runner should only be set when Grafana is starting.'); } factory = instance; }; /** * Used to create QueryRunner instances from outside the core Grafana application. * This is helpful to be able to create a QueryRunner to execute queries in e.g. an app plugin. * * @internal */ export const createQueryRunner = (): QueryRunner => { if (!factory) { throw new Error('`createQueryRunner` can only be used after Grafana instance has started.'); } return factory(); };
packages/grafana-runtime/src/services/QueryRunner.ts
0
https://github.com/grafana/grafana/commit/395d7eb74cdce7c2a405bba80738cd4a3d342784
[ 0.0001742370513966307, 0.00017064182611647993, 0.00016746837354730815, 0.0001704309252090752, 0.0000025588315111235715 ]
{ "id": 5, "code_window": [ " super(props);\n", "\n", " this.state = {\n", " collapsed: this.props.panel.collapsed,\n", " };\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep" ], "after_edit": [ " }\n" ], "file_path": "public/app/features/dashboard/components/DashboardRow/DashboardRow.tsx", "type": "add", "edit_start_line_idx": 23 }
import React, { PureComponent } from 'react'; import { connect, ConnectedProps } from 'react-redux'; import { Tooltip, Icon, Button } from '@grafana/ui'; import { SlideDown } from 'app/core/components/Animations/SlideDown'; import { StoreState } from 'app/types'; import { DashboardAcl, PermissionLevel, NewDashboardAclItem } from 'app/types/acl'; import { getDashboardPermissions, addDashboardPermission, removeDashboardPermission, updateDashboardPermission, } from '../../state/actions'; import { DashboardModel } from '../../state/DashboardModel'; import PermissionList from 'app/core/components/PermissionList/PermissionList'; import AddPermission from 'app/core/components/PermissionList/AddPermission'; import PermissionsInfo from 'app/core/components/PermissionList/PermissionsInfo'; const mapStateToProps = (state: StoreState) => ({ permissions: state.dashboard.permissions, }); const mapDispatchToProps = { getDashboardPermissions, addDashboardPermission, removeDashboardPermission, updateDashboardPermission, }; const connector = connect(mapStateToProps, mapDispatchToProps); export interface OwnProps { dashboard: DashboardModel; } export type Props = OwnProps & ConnectedProps<typeof connector>; export interface State { isAdding: boolean; } export class DashboardPermissionsUnconnected extends PureComponent<Props, State> { constructor(props: Props) { super(props); this.state = { isAdding: false, }; } componentDidMount() { this.props.getDashboardPermissions(this.props.dashboard.id); } onOpenAddPermissions = () => { this.setState({ isAdding: true }); }; onRemoveItem = (item: DashboardAcl) => { this.props.removeDashboardPermission(this.props.dashboard.id, item); }; onPermissionChanged = (item: DashboardAcl, level: PermissionLevel) => { this.props.updateDashboardPermission(this.props.dashboard.id, item, level); }; onAddPermission = (newItem: NewDashboardAclItem) => { return this.props.addDashboardPermission(this.props.dashboard.id, newItem); }; onCancelAddPermission = () => { this.setState({ isAdding: false }); }; getFolder() { const { dashboard } = this.props; return { id: dashboard.meta.folderId, title: dashboard.meta.folderTitle, url: dashboard.meta.folderUrl, }; } render() { const { permissions, dashboard: { meta: { hasUnsavedFolderChange }, }, } = this.props; const { isAdding } = this.state; return hasUnsavedFolderChange ? ( <h5>You have changed a folder, please save to view permissions.</h5> ) : ( <div> <div className="page-action-bar"> <h3 className="page-sub-heading">Permissions</h3> <Tooltip placement="auto" content={<PermissionsInfo />}> <Icon className="icon--has-hover page-sub-heading-icon" name="question-circle" /> </Tooltip> <div className="page-action-bar__spacer" /> <Button className="pull-right" onClick={this.onOpenAddPermissions} disabled={isAdding}> Add permission </Button> </div> <SlideDown in={isAdding}> <AddPermission onAddPermission={this.onAddPermission} onCancel={this.onCancelAddPermission} /> </SlideDown> <PermissionList items={permissions} onRemoveItem={this.onRemoveItem} onPermissionChanged={this.onPermissionChanged} isFetching={false} folderInfo={this.getFolder()} /> </div> ); } } export const DashboardPermissions = connector(DashboardPermissionsUnconnected);
public/app/features/dashboard/components/DashboardPermissions/DashboardPermissions.tsx
0
https://github.com/grafana/grafana/commit/395d7eb74cdce7c2a405bba80738cd4a3d342784
[ 0.010885244235396385, 0.003326439531520009, 0.00016667199088260531, 0.0014060684479773045, 0.003362645860761404 ]
{ "id": 6, "code_window": [ "\n", " this.props.dashboard.on(CoreEvents.templateVariableValueUpdated, this.onVariableUpdated);\n", " }\n", "\n", " componentWillUnmount() {\n" ], "labels": [ "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " componentDidMount() {\n", " this.sub = this.props.dashboard.events.subscribe(RefreshEvent, this.onVariableUpdated);\n" ], "file_path": "public/app/features/dashboard/components/DashboardRow/DashboardRow.tsx", "type": "replace", "edit_start_line_idx": 24 }
import React from 'react'; import classNames from 'classnames'; import { Icon } from '@grafana/ui'; import { PanelModel } from '../../state/PanelModel'; import { DashboardModel } from '../../state/DashboardModel'; import appEvents from 'app/core/app_events'; import { CoreEvents } from 'app/types'; import { RowOptionsButton } from '../RowOptions/RowOptionsButton'; import { getTemplateSrv } from '@grafana/runtime'; import { ShowConfirmModalEvent } from '../../../../types/events'; export interface DashboardRowProps { panel: PanelModel; dashboard: DashboardModel; } export class DashboardRow extends React.Component<DashboardRowProps, any> { constructor(props: DashboardRowProps) { super(props); this.state = { collapsed: this.props.panel.collapsed, }; this.props.dashboard.on(CoreEvents.templateVariableValueUpdated, this.onVariableUpdated); } componentWillUnmount() { this.props.dashboard.off(CoreEvents.templateVariableValueUpdated, this.onVariableUpdated); } onVariableUpdated = () => { this.forceUpdate(); }; onToggle = () => { this.props.dashboard.toggleRow(this.props.panel); this.setState((prevState: any) => { return { collapsed: !prevState.collapsed }; }); }; onUpdate = (title: string, repeat: string | undefined) => { this.props.panel['title'] = title; this.props.panel['repeat'] = repeat; this.props.panel.render(); this.props.dashboard.processRepeats(); this.forceUpdate(); }; onDelete = () => { appEvents.publish( new ShowConfirmModalEvent({ title: 'Delete row', text: 'Are you sure you want to remove this row and all its panels?', altActionText: 'Delete row only', icon: 'trash-alt', onConfirm: () => { this.props.dashboard.removeRow(this.props.panel, true); }, onAltAction: () => { this.props.dashboard.removeRow(this.props.panel, false); }, }) ); }; render() { const classes = classNames({ 'dashboard-row': true, 'dashboard-row--collapsed': this.state.collapsed, }); const title = getTemplateSrv().replace(this.props.panel.title, this.props.panel.scopedVars, 'text'); const count = this.props.panel.panels ? this.props.panel.panels.length : 0; const panels = count === 1 ? 'panel' : 'panels'; const canEdit = this.props.dashboard.meta.canEdit === true; return ( <div className={classes}> <a className="dashboard-row__title pointer" onClick={this.onToggle}> <Icon name={this.state.collapsed ? 'angle-right' : 'angle-down'} /> {title} <span className="dashboard-row__panel_count"> ({count} {panels}) </span> </a> {canEdit && ( <div className="dashboard-row__actions"> <RowOptionsButton title={this.props.panel.title} repeat={this.props.panel.repeat} onUpdate={this.onUpdate} /> <a className="pointer" onClick={this.onDelete}> <Icon name="trash-alt" /> </a> </div> )} {this.state.collapsed === true && ( <div className="dashboard-row__toggle-target" onClick={this.onToggle}> &nbsp; </div> )} {canEdit && <div className="dashboard-row__drag grid-drag-handle" />} </div> ); } }
public/app/features/dashboard/components/DashboardRow/DashboardRow.tsx
1
https://github.com/grafana/grafana/commit/395d7eb74cdce7c2a405bba80738cd4a3d342784
[ 0.9947341680526733, 0.08518768101930618, 0.00017252449470106512, 0.0006278594955801964, 0.2742595970630646 ]
{ "id": 6, "code_window": [ "\n", " this.props.dashboard.on(CoreEvents.templateVariableValueUpdated, this.onVariableUpdated);\n", " }\n", "\n", " componentWillUnmount() {\n" ], "labels": [ "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " componentDidMount() {\n", " this.sub = this.props.dashboard.events.subscribe(RefreshEvent, this.onVariableUpdated);\n" ], "file_path": "public/app/features/dashboard/components/DashboardRow/DashboardRow.tsx", "type": "replace", "edit_start_line_idx": 24 }
{ "conditions": [ { "evaluator": { "params": [ 0 ], "type": "lt" }, "operator": { "type": "" }, "query": { "datasourceId": 2, "model": { "expr": "avg_over_time(sum by (instance) (up)[1h:5m])", "interval": "", "legendFormat": "", "refId": "A" }, "params": [ "A", "5m", "now" ] }, "reducer": { "params": [], "type": "avg" }, "type": "query" }, { "evaluator": { "params": [ 0 ], "type": "gt" }, "operator": { "type": "and" }, "query": { "datasourceId": 2, "model": { "expr": "avg_over_time(sum by (instance) (up)[1h:5m])", "interval": "", "legendFormat": "", "refId": "A" }, "params": [ "A", "10m", "now-5m" ] }, "reducer": { "params": [], "type": "avg" }, "type": "query" } ]}
pkg/expr/translate/testdata/sameQueryDifferentTimeRange.json
0
https://github.com/grafana/grafana/commit/395d7eb74cdce7c2a405bba80738cd4a3d342784
[ 0.00017529136675875634, 0.00017221688176505268, 0.00016919960035011172, 0.00017225822375621647, 0.0000020120987755944952 ]
{ "id": 6, "code_window": [ "\n", " this.props.dashboard.on(CoreEvents.templateVariableValueUpdated, this.onVariableUpdated);\n", " }\n", "\n", " componentWillUnmount() {\n" ], "labels": [ "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " componentDidMount() {\n", " this.sub = this.props.dashboard.events.subscribe(RefreshEvent, this.onVariableUpdated);\n" ], "file_path": "public/app/features/dashboard/components/DashboardRow/DashboardRow.tsx", "type": "replace", "edit_start_line_idx": 24 }
{ "compilerOptions": { "types": ["cypress"] }, "extends": "../../tsconfig.json", "include": ["**/*.ts", "../../packages/grafana-e2e/cypress/support/index.d.ts"] }
e2e/verify/tsconfig.json
0
https://github.com/grafana/grafana/commit/395d7eb74cdce7c2a405bba80738cd4a3d342784
[ 0.00016873977438081056, 0.00016873977438081056, 0.00016873977438081056, 0.00016873977438081056, 0 ]
{ "id": 6, "code_window": [ "\n", " this.props.dashboard.on(CoreEvents.templateVariableValueUpdated, this.onVariableUpdated);\n", " }\n", "\n", " componentWillUnmount() {\n" ], "labels": [ "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " componentDidMount() {\n", " this.sub = this.props.dashboard.events.subscribe(RefreshEvent, this.onVariableUpdated);\n" ], "file_path": "public/app/features/dashboard/components/DashboardRow/DashboardRow.tsx", "type": "replace", "edit_start_line_idx": 24 }
+++ title = "What's new in Grafana v2.0" description = "Feature and improvement highlights for Grafana v2.0" keywords = ["grafana", "new", "documentation", "2.0", "release notes"] aliases = ["/docs/grafana/latest/guides/whats-new-in-v2/"] weight = -1 [_build] list = false +++ # What's new in Grafana v2.0 Grafana 2.0 represents months of work by the Grafana team and the community. We are pleased to be able to release the Grafana 2.0 beta. This is a guide that describes some of changes and new features that can be found in Grafana V2.0. If you are interested in how to migrate from Grafana V1.x to V2.0, please read our [Migration Guide](../installation/migrating_to2.md) ## New backend server Grafana now ships with its own required backend server. Also completely open-source, it's written in Go and has a full HTTP API. In addition to new features, the backend server makes it much easier to set up and enjoy Grafana. Grafana 2.0 now ships as cross platform binaries with no dependencies. Authentication is built in, and Grafana is now capable of proxying connections to Data Sources. There are no longer any CORS (Cross Origin Resource Sharing) issues requiring messy workarounds. Elasticsearch is no longer required just to store dashboards. ## User and Organization permissions All Dashboards and Data Sources are linked to an Organization (not to a User). Users are linked to Organizations via a role. That role can be: - `Viewer`: Can only view dashboards, not save / create them. - `Editor`: Can view, update and create dashboards. - `Admin`: Everything an Editor can plus edit and add data sources and organization users. > **Note:** A `Viewer` can still view all metrics exposed through a data source, not only > the metrics used in already existing dashboards. That is because there are not > per series permissions in Graphite, InfluxDB or OpenTSDB. There are currently no permissions on individual dashboards. Read more about Grafana's new user model on the [Admin section](../reference/admin/) ## Dashboard Snapshot sharing A Dashboard Snapshot is an easy way to create and share a URL for a stripped down, point-in-time version of any Dashboard. You can give this URL to anyone or everyone, and they can view the Snapshot even if they're not a User of your Grafana instance. You can set an expiration time for any Snapshots you create. When you create a Snapshot, we strip sensitive data, like panel metric queries, annotation and template queries and panel links. The data points displayed on screen for that specific time period in your Dashboard is saved in the JSON of the Snapshot itself. Sharing a Snapshot is similar to sharing a link to a screenshot of your dashboard, only way better (they'll look great at any screen resolution, you can hover over series, even zoom in). Also they are fast to load as they aren't actually connected to any live Data Sources in any way. They're a great way to communicate about a particular incident with specific people who aren't users of your Grafana instance. You can also use them to show off your dashboards over the Internet. ![](/img/docs/v2/dashboard_snapshot_dialog.png) ### Publish snapshots You can publish snapshots locally or to [snapshot.raintank.io](http://snapshot.raintank.io). snapshot.raintank is a free service provided by [raintank](http://raintank.io) for hosting external Grafana snapshots. Either way, anyone with the link (and access to your Grafana instance for local snapshots) can view it. ## Panel time overrides and timeshift In Grafana v2.x you can now override the relative time range for individual panels, causing them to be different than what is selected in the Dashboard time picker in the upper right. You can also add a time shift to individual panels. This allows you to show metrics from different time periods or days at the same time. ![](/img/docs/v2/panel_time_override.jpg) You control these overrides in panel editor mode and the new tab `Time Range`. ![](/img/docs/v2/time_range_tab.jpg) When you zoom or change the Dashboard time to a custom absolute time range, all panel overrides will be disabled. The panel relative time override is only active when the dashboard time is also relative. The panel timeshift override however is always active, even when the dashboard time is absolute. The `Hide time override info` option allows you to hide the override info text that is by default shown in the upper right of a panel when overridden time range options. Currently you can only override the dashboard time with relative time ranges, not absolute time ranges. ## Panel iframe embedding You can embed a single panel on another web page or your own application using the panel share dialog. Below you should see an iframe with a graph panel (taken from a Dashboard snapshot at [snapshot.raintank.io](http://snapshot.raintank.io). Try hovering or zooming on the panel below! <iframe src="https://snapshot.raintank.io/dashboard-solo/snapshot/4IKyWYNEQll1B9FXcN3RIgx4M2VGgU8d?panelId=4&fullscreen" width="650" height="300" frameborder="0"></iframe> This feature makes it easy to include interactive visualizations from your Grafana instance anywhere you want. ## New dashboard top header The top header has gotten a major streamlining in Grafana V2.0. <img class="no-shadow" src="/img/docs/v2/v2_top_nav_annotated.png"> 1. `Side menubar toggle` Toggle the side menubar on or off. This allows you to focus on the data presented on the Dashboard. The side menubar provides access to features unrelated to a Dashboard such as Users, Organizations, and Data Sources. 1. `Dashboard dropdown` The main dropdown shows you which Dashboard you are currently viewing, and allows you to easily switch to a new Dashboard. From here you can also create a new Dashboard, Import existing Dashboards, and manage the Playlist. 1. `Star Dashboard`: Star (or un-star) the current Dashboard. Starred Dashboards will show up on your own Home Dashboard by default, and are a convenient way to mark Dashboards that you're interested in. 1. `Share Dashboard`: Share the current dashboard by creating a link or create a static Snapshot of it. Make sure the Dashboard is saved before sharing. 1. `Save dashboard`: Save the current Dashboard with the current name. 1. `Settings`: Manage Dashboard settings and features such as Templating, Annotations and the name. > **Note:** In Grafana v2.0 when you change the title of a dashboard and then save it, it will no > longer create a new Dashboard. It will just change the name for the current Dashboard. > To change name and create a new Dashboard use the `Save As...` menu option ### New Side menubar The new side menubar provides access to features such as User Preferences, Organizations, and Data Sources. If you have multiple Organizations, you can easily switch between them here. The side menubar will become more useful as we build out additional functionality in Grafana 2.x You can easily collapse or re-open the side menubar at any time by clicking the Grafana icon in the top left. We never want to get in the way of the data. ## New search view and starring dashboards ![](/img/docs/v2/dashboard_search.jpg) The dashboard search view has gotten a big overhaul. You can now see and filter by which dashboard you have personally starred. ## Logarithmic scale The Graph panel now supports 3 logarithmic scales, `log base 10`, `log base 32`, `log base 1024`. Logarithmic y-axis scales are very useful when rendering many series of different order of magnitude on the same scale (eg. latency, network traffic, and storage) ![](/img/docs/v2/graph_logbase10_ms.png) ## Dashlist panel ![](/img/docs/v2/dashlist_starred.png) The dashlist is a new panel in Grafana v2.0. It allows you to show your personal starred dashboards, as well as do custom searches based on search strings or tags. dashlist is used on the new Grafana Home screen. It is included as a reference Panel and is useful to provide basic linking between Dashboards. ## Data Source proxy and admin views Data sources in Grafana v2.0 are no longer defined in a config file. Instead, they are added through the UI or the HTTP API. The backend can now proxy data from Data Sources, which means that it is a lot easier to get started using Grafana with Graphite or OpenTSDB without having to spend time with CORS (Cross origin resource sharing) work-arounds. In addition, connections to Data Sources can be better controlled and secured, and authentication information no longer needs to be exposed to the browser. ## Dashboard "now delay" A commonly reported problem has been graphs dipping to zero at the end, because metric data for the last interval has yet to be written to the Data Source. These graphs then "self correct" once the data comes in, but can look deceiving or alarming at times. You can avoid this problem by adding a `now delay` in `Dashboard Settings` > `Time Picker` tab. This new feature will cause Grafana to ignore the most recent data up to the set delay. ![](/img/docs/v2/timepicker_now_delay.jpg) The delay that may be necessary depends on how much latency you have in your collection pipeline. ## Dashboard overwrite protection Grafana v2.0 protects Users from accidentally overwriting each others Dashboard changes. Similar protections are in place if you try to create a new Dashboard with the same name as an existing one. ![](/img/docs/v2/overwrite_protection.jpg) These protections are only the first step; we will be building out additional capabilities around dashboard versioning and management in future versions of Grafana. ## User preferences If you open side menu (by clicking on the Grafana icon in the top header) you can access your Profile Page. Here you can update your user details, UI Theme, and change your password. ## Server-side Panel rendering Grafana now supports server-side PNG rendering. From the Panel share dialog you now have access to a link that will render a particular Panel to a PNG image. > **Note:** This requires that your Data Source is accessible from your Grafana instance. ![](/img/docs/v2/share_dialog_image_highlight.jpg)
docs/sources/whatsnew/whats-new-in-v2-0.md
0
https://github.com/grafana/grafana/commit/395d7eb74cdce7c2a405bba80738cd4a3d342784
[ 0.00019423908088356256, 0.00017241633031517267, 0.00016167030844371766, 0.0001725317124510184, 0.000007977421773830429 ]
{ "id": 7, "code_window": [ " }\n", "\n", " componentWillUnmount() {\n", " this.props.dashboard.off(CoreEvents.templateVariableValueUpdated, this.onVariableUpdated);\n", " }\n", "\n", " onVariableUpdated = () => {\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " if (this.sub) {\n", " this.sub.unsubscribe();\n", " }\n" ], "file_path": "public/app/features/dashboard/components/DashboardRow/DashboardRow.tsx", "type": "replace", "edit_start_line_idx": 28 }
import React from 'react'; import { mount } from 'enzyme'; import { DashboardRow } from './DashboardRow'; import { PanelModel } from '../../state/PanelModel'; describe('DashboardRow', () => { let wrapper: any, panel: PanelModel, dashboardMock: any; beforeEach(() => { dashboardMock = { toggleRow: jest.fn(), on: jest.fn(), meta: { canEdit: true, }, }; panel = new PanelModel({ collapsed: false }); wrapper = mount(<DashboardRow panel={panel} dashboard={dashboardMock} />); }); it('Should not have collapsed class when collaped is false', () => { expect(wrapper.find('.dashboard-row')).toHaveLength(1); expect(wrapper.find('.dashboard-row--collapsed')).toHaveLength(0); }); it('Should collapse after clicking title', () => { wrapper.find('.dashboard-row__title').simulate('click'); expect(wrapper.find('.dashboard-row--collapsed')).toHaveLength(1); expect(dashboardMock.toggleRow.mock.calls).toHaveLength(1); }); it('should have two actions as admin', () => { expect(wrapper.find('.dashboard-row__actions .pointer')).toHaveLength(2); }); it('should not show row drag handle when cannot edit', () => { dashboardMock.meta.canEdit = false; wrapper = mount(<DashboardRow panel={panel} dashboard={dashboardMock} />); expect(wrapper.find('.dashboard-row__drag')).toHaveLength(0); }); it('should have zero actions when cannot edit', () => { dashboardMock.meta.canEdit = false; panel = new PanelModel({ collapsed: false }); wrapper = mount(<DashboardRow panel={panel} dashboard={dashboardMock} />); expect(wrapper.find('.dashboard-row__actions .pointer')).toHaveLength(0); }); });
public/app/features/dashboard/components/DashboardRow/DashboardRow.test.tsx
1
https://github.com/grafana/grafana/commit/395d7eb74cdce7c2a405bba80738cd4a3d342784
[ 0.0012717508943751454, 0.0005382650415413082, 0.00016661670815665275, 0.00027042478905059397, 0.00045888530439697206 ]
{ "id": 7, "code_window": [ " }\n", "\n", " componentWillUnmount() {\n", " this.props.dashboard.off(CoreEvents.templateVariableValueUpdated, this.onVariableUpdated);\n", " }\n", "\n", " onVariableUpdated = () => {\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " if (this.sub) {\n", " this.sub.unsubscribe();\n", " }\n" ], "file_path": "public/app/features/dashboard/components/DashboardRow/DashboardRow.tsx", "type": "replace", "edit_start_line_idx": 28 }
import { defaults } from 'lodash'; import { Observable } from 'rxjs'; import { DataQueryRequest, DataQueryResponse, FieldType, CircularDataFrame, CSVReader, Field, LoadingState, StreamingDataFrame, DataFrameSchema, DataFrameData, } from '@grafana/data'; import { TestDataQuery, StreamingQuery } from './types'; import { getRandomLine } from './LogIpsum'; import { perf } from 'app/features/live/perf'; export const defaultStreamQuery: StreamingQuery = { type: 'signal', speed: 250, // ms spread: 3.5, noise: 2.2, bands: 1, }; export function runStream(target: TestDataQuery, req: DataQueryRequest<TestDataQuery>): Observable<DataQueryResponse> { const query = defaults(target.stream, defaultStreamQuery); if ('signal' === query.type) { return runSignalStream(target, query, req); } if ('logs' === query.type) { return runLogsStream(target, query, req); } if ('fetch' === query.type) { return runFetchStream(target, query, req); } throw new Error(`Unknown Stream Type: ${query.type}`); } export function runSignalStream( target: TestDataQuery, query: StreamingQuery, req: DataQueryRequest<TestDataQuery> ): Observable<DataQueryResponse> { return new Observable<DataQueryResponse>((subscriber) => { const streamId = `signal-${req.panelId}-${target.refId}`; const maxDataPoints = req.maxDataPoints || 1000; const schema: DataFrameSchema = { refId: target.refId, name: target.alias || 'Signal ' + target.refId, fields: [ { name: 'time', type: FieldType.time }, { name: 'value', type: FieldType.number }, ], }; const { spread, speed, bands = 0, noise } = query; for (let i = 0; i < bands; i++) { const suffix = bands > 1 ? ` ${i + 1}` : ''; schema.fields.push({ name: 'Min' + suffix, type: FieldType.number }); schema.fields.push({ name: 'Max' + suffix, type: FieldType.number }); } const frame = new StreamingDataFrame({ schema }, { maxLength: maxDataPoints }); let value = Math.random() * 100; let timeoutId: any = null; let lastSent = -1; const addNextRow = (time: number) => { value += (Math.random() - 0.5) * spread; const data: DataFrameData = { values: [[time], [value]], }; let min = value; let max = value; for (let i = 0; i < bands; i++) { min = min - Math.random() * noise; max = max + Math.random() * noise; data.values.push([min]); data.values.push([max]); } const event = { data }; return frame.push(event); }; // Fill the buffer on init if (true) { let time = Date.now() - maxDataPoints * speed; for (let i = 0; i < maxDataPoints; i++) { addNextRow(time); time += speed; } } const pushNextEvent = () => { addNextRow(Date.now()); const elapsed = perf.last - lastSent; if (elapsed > 1000 || perf.ok) { subscriber.next({ data: [frame], key: streamId, state: LoadingState.Streaming, }); lastSent = perf.last; } timeoutId = setTimeout(pushNextEvent, speed); }; // Send first event in 5ms setTimeout(pushNextEvent, 5); return () => { console.log('unsubscribing to stream ' + streamId); clearTimeout(timeoutId); }; }); } export function runLogsStream( target: TestDataQuery, query: StreamingQuery, req: DataQueryRequest<TestDataQuery> ): Observable<DataQueryResponse> { return new Observable<DataQueryResponse>((subscriber) => { const streamId = `logs-${req.panelId}-${target.refId}`; const maxDataPoints = req.maxDataPoints || 1000; const data = new CircularDataFrame({ append: 'tail', capacity: maxDataPoints, }); data.refId = target.refId; data.name = target.alias || 'Logs ' + target.refId; data.addField({ name: 'line', type: FieldType.string }); data.addField({ name: 'time', type: FieldType.time }); data.meta = { preferredVisualisationType: 'logs' }; const { speed } = query; let timeoutId: any = null; const pushNextEvent = () => { data.fields[0].values.add(Date.now()); data.fields[1].values.add(getRandomLine()); subscriber.next({ data: [data], key: streamId, }); timeoutId = setTimeout(pushNextEvent, speed); }; // Send first event in 5ms setTimeout(pushNextEvent, 5); return () => { console.log('unsubscribing to stream ' + streamId); clearTimeout(timeoutId); }; }); } export function runFetchStream( target: TestDataQuery, query: StreamingQuery, req: DataQueryRequest<TestDataQuery> ): Observable<DataQueryResponse> { return new Observable<DataQueryResponse>((subscriber) => { const streamId = `fetch-${req.panelId}-${target.refId}`; const maxDataPoints = req.maxDataPoints || 1000; let data = new CircularDataFrame({ append: 'tail', capacity: maxDataPoints, }); data.refId = target.refId; data.name = target.alias || 'Fetch ' + target.refId; let reader: ReadableStreamReader<Uint8Array>; const csv = new CSVReader({ callback: { onHeader: (fields: Field[]) => { // Clear any existing fields if (data.fields.length) { data = new CircularDataFrame({ append: 'tail', capacity: maxDataPoints, }); data.refId = target.refId; data.name = 'Fetch ' + target.refId; } for (const field of fields) { data.addField(field); } }, onRow: (row: any[]) => { data.add(row); }, }, }); const processChunk = (value: ReadableStreamDefaultReadResult<Uint8Array>): any => { if (value.value) { const text = new TextDecoder().decode(value.value); csv.readCSV(text); } subscriber.next({ data: [data], key: streamId, state: value.done ? LoadingState.Done : LoadingState.Streaming, }); if (value.done) { console.log('Finished stream'); subscriber.complete(); // necessary? return; } return reader.read().then(processChunk); }; if (!query.url) { throw new Error('query.url is not defined'); } fetch(new Request(query.url)).then((response) => { if (response.body) { reader = response.body.getReader(); reader.read().then(processChunk); } }); return () => { // Cancel fetch? console.log('unsubscribing to stream ' + streamId); }; }); }
public/app/plugins/datasource/testdata/runStreams.ts
0
https://github.com/grafana/grafana/commit/395d7eb74cdce7c2a405bba80738cd4a3d342784
[ 0.00017911316535901278, 0.00017233850667253137, 0.00016679870896041393, 0.0001725431066006422, 0.000003229664343962213 ]
{ "id": 7, "code_window": [ " }\n", "\n", " componentWillUnmount() {\n", " this.props.dashboard.off(CoreEvents.templateVariableValueUpdated, this.onVariableUpdated);\n", " }\n", "\n", " onVariableUpdated = () => {\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " if (this.sub) {\n", " this.sub.unsubscribe();\n", " }\n" ], "file_path": "public/app/features/dashboard/components/DashboardRow/DashboardRow.tsx", "type": "replace", "edit_start_line_idx": 28 }
package influxdb import ( "context" "io/ioutil" "net/url" "testing" "github.com/grafana/grafana/pkg/components/simplejson" "github.com/grafana/grafana/pkg/models" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestExecutor_createRequest(t *testing.T) { datasource := &models.DataSource{ Url: "http://awesome-influxdb:1337", Database: "awesome-db", JsonData: simplejson.New(), } query := "SELECT awesomeness FROM somewhere" e := &Executor{ QueryParser: &InfluxdbQueryParser{}, ResponseParser: &ResponseParser{}, } t.Run("createRequest with GET httpMode", func(t *testing.T) { req, err := e.createRequest(context.Background(), datasource, query) require.NoError(t, err) assert.Equal(t, "GET", req.Method) q := req.URL.Query().Get("q") assert.Equal(t, query, q) assert.Nil(t, req.Body) }) t.Run("createRequest with POST httpMode", func(t *testing.T) { datasource.JsonData.Set("httpMode", "POST") req, err := e.createRequest(context.Background(), datasource, query) require.NoError(t, err) assert.Equal(t, "POST", req.Method) q := req.URL.Query().Get("q") assert.Empty(t, q) body, err := ioutil.ReadAll(req.Body) require.NoError(t, err) testBodyValues := url.Values{} testBodyValues.Add("q", query) testBody := testBodyValues.Encode() assert.Equal(t, testBody, string(body)) }) t.Run("createRequest with PUT httpMode", func(t *testing.T) { datasource.JsonData.Set("httpMode", "PUT") _, err := e.createRequest(context.Background(), datasource, query) require.EqualError(t, err, ErrInvalidHttpMode.Error()) }) }
pkg/tsdb/influxdb/influxdb_test.go
0
https://github.com/grafana/grafana/commit/395d7eb74cdce7c2a405bba80738cd4a3d342784
[ 0.00017580256098881364, 0.00017395548638887703, 0.00017179384303744882, 0.00017425166151951998, 0.0000011963221595578943 ]
{ "id": 7, "code_window": [ " }\n", "\n", " componentWillUnmount() {\n", " this.props.dashboard.off(CoreEvents.templateVariableValueUpdated, this.onVariableUpdated);\n", " }\n", "\n", " onVariableUpdated = () => {\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " if (this.sub) {\n", " this.sub.unsubscribe();\n", " }\n" ], "file_path": "public/app/features/dashboard/components/DashboardRow/DashboardRow.tsx", "type": "replace", "edit_start_line_idx": 28 }
import React, { MouseEventHandler } from 'react'; import { GrafanaTheme2, isUnsignedPluginSignature, PanelPluginMeta, PluginState } from '@grafana/data'; import { Badge, BadgeProps, IconButton, PluginSignatureBadge, useStyles2 } from '@grafana/ui'; import { css, cx } from '@emotion/css'; import { selectors } from '@grafana/e2e-selectors'; interface Props { isCurrent: boolean; plugin: PanelPluginMeta; title: string; onClick: MouseEventHandler<HTMLDivElement>; onDelete?: () => void; disabled?: boolean; showBadge?: boolean; description?: string; } export const PanelTypeCard: React.FC<Props> = ({ isCurrent, title, plugin, onClick, onDelete, disabled, showBadge, description, children, }) => { const styles = useStyles2(getStyles); const cssClass = cx({ [styles.item]: true, [styles.disabled]: disabled || plugin.state === PluginState.deprecated, [styles.current]: isCurrent, }); return ( <div className={cssClass} aria-label={selectors.components.PluginVisualization.item(plugin.name)} onClick={disabled ? undefined : onClick} title={isCurrent ? 'Click again to close this section' : plugin.name} > <img className={styles.img} src={plugin.info.logos.small} /> <div className={styles.itemContent}> <div className={styles.name}>{title}</div> {description ? <span className={styles.description}>{description}</span> : null} {children} </div> {showBadge && ( <div className={cx(styles.badge, disabled && styles.disabled)}> <PanelPluginBadge plugin={plugin} /> </div> )} {onDelete && ( <IconButton name="trash-alt" onClick={(e) => { e.stopPropagation(); onDelete(); }} aria-label="Delete button on panel type card" /> )} </div> ); }; PanelTypeCard.displayName = 'PanelTypeCard'; const getStyles = (theme: GrafanaTheme2) => { return { item: css` position: relative; display: flex; flex-shrink: 0; cursor: pointer; background: ${theme.colors.background.secondary}; border-radius: ${theme.shape.borderRadius()}; box-shadow: ${theme.shadows.z1}; border: 1px solid ${theme.colors.background.secondary}; align-items: center; padding: 8px; width: 100%; position: relative; overflow: hidden; transition: ${theme.transitions.create(['background'], { duration: theme.transitions.duration.short, })}; &:hover { background: ${theme.colors.emphasize(theme.colors.background.secondary, 0.03)}; } `, itemContent: css` position: relative; width: 100%; padding: ${theme.spacing(0, 1)}; `, current: css` label: currentVisualizationItem; border: 1px solid ${theme.colors.primary.border}; background: ${theme.colors.action.selected}; `, disabled: css` opacity: 0.2; filter: grayscale(1); cursor: default; pointer-events: none; `, name: css` text-overflow: ellipsis; overflow: hidden; white-space: nowrap; font-size: ${theme.typography.size.sm}; font-weight: ${theme.typography.fontWeightMedium}; width: 100%; `, description: css` text-overflow: ellipsis; overflow: hidden; white-space: nowrap; color: ${theme.colors.text.secondary}; font-size: ${theme.typography.bodySmall.fontSize}; font-weight: ${theme.typography.fontWeightLight}; width: 100%; `, img: css` max-height: 38px; width: 38px; display: flex; align-items: center; `, badge: css` background: ${theme.colors.background.primary}; `, }; }; interface PanelPluginBadgeProps { plugin: PanelPluginMeta; } const PanelPluginBadge: React.FC<PanelPluginBadgeProps> = ({ plugin }) => { const display = getPanelStateBadgeDisplayModel(plugin); if (isUnsignedPluginSignature(plugin.signature)) { return <PluginSignatureBadge status={plugin.signature} />; } if (!display) { return null; } return <Badge color={display.color} text={display.text} icon={display.icon} tooltip={display.tooltip} />; }; function getPanelStateBadgeDisplayModel(panel: PanelPluginMeta): BadgeProps | null { switch (panel.state) { case PluginState.deprecated: return { text: 'Deprecated', color: 'red', tooltip: `${panel.name} Panel is deprecated`, }; case PluginState.alpha: return { text: 'Alpha', color: 'blue', tooltip: `${panel.name} Panel is experimental`, }; case PluginState.beta: return { text: 'Beta', color: 'blue', tooltip: `${panel.name} Panel is in beta`, }; default: return null; } } PanelPluginBadge.displayName = 'PanelPluginBadge';
public/app/features/dashboard/components/VizTypePicker/PanelTypeCard.tsx
0
https://github.com/grafana/grafana/commit/395d7eb74cdce7c2a405bba80738cd4a3d342784
[ 0.0001899840572150424, 0.00017335510347038507, 0.00016736618999857455, 0.0001726423215586692, 0.00000459718148704269 ]
{ "id": 0, "code_window": [ "\t\t\tenum: [TerminalCursorStyle.BLOCK, TerminalCursorStyle.LINE, TerminalCursorStyle.UNDERLINE],\n", "\t\t\tdefault: TerminalCursorStyle.BLOCK\n", "\t\t},\n", "\t\t'terminal.integrated.scrollback': {\n", "\t\t\tdescription: nls.localize('terminal.integrated.scrollback', \"Controls the maximum amount of lines the terminal keeps in its buffer.\"),\n", "\t\t\ttype: 'number',\n", "\t\t\tdefault: 1000\n", "\t\t},\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t'terminal.integrated.cursorBarWidth': {\n", "\t\t\tdescription: nls.localize('terminal.integrated.cursorBarWidth', \"Controls the width of terminal bar cursor.\"),\n", "\t\t\ttype: 'number',\n", "\t\t\tdefault: 1\n", "\t\t},\n" ], "file_path": "src/vs/workbench/contrib/terminal/browser/terminal.contribution.ts", "type": "add", "edit_start_line_idx": 208 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { KeyCode, KeyMod } from 'vs/base/common/keyCodes'; import * as platform from 'vs/base/common/platform'; import 'vs/css!./media/scrollbar'; import 'vs/css!./media/terminal'; import 'vs/css!./media/widgets'; import 'vs/css!./media/xterm'; import * as nls from 'vs/nls'; import { SyncActionDescriptor } from 'vs/platform/actions/common/actions'; import { CommandsRegistry } from 'vs/platform/commands/common/commands'; import { ContextKeyExpr } from 'vs/platform/contextkey/common/contextkey'; import { KeybindingWeight } from 'vs/platform/keybinding/common/keybindingsRegistry'; import { Registry } from 'vs/platform/registry/common/platform'; import { Extensions as ActionBarExtensions, IActionBarRegistry, Scope } from 'vs/workbench/browser/actions'; import * as panel from 'vs/workbench/browser/panel'; import { getQuickNavigateHandler } from 'vs/workbench/browser/parts/quickopen/quickopen'; import { Extensions as QuickOpenExtensions, IQuickOpenRegistry, QuickOpenHandlerDescriptor } from 'vs/workbench/browser/quickopen'; import { Extensions as ActionExtensions, IWorkbenchActionRegistry } from 'vs/workbench/common/actions'; import { ClearSelectionTerminalAction, ClearTerminalAction, CopyTerminalSelectionAction, CreateNewInActiveWorkspaceTerminalAction, CreateNewTerminalAction, DeleteToLineStartTerminalAction, DeleteWordLeftTerminalAction, DeleteWordRightTerminalAction, FindNext, FindPrevious, FocusActiveTerminalAction, FocusNextPaneTerminalAction, FocusNextTerminalAction, FocusPreviousPaneTerminalAction, FocusPreviousTerminalAction, FocusTerminalFindWidgetAction, HideTerminalFindWidgetAction, KillTerminalAction, MoveToLineEndTerminalAction, MoveToLineStartTerminalAction, QuickOpenActionTermContributor, QuickOpenTermAction, RenameTerminalAction, ResizePaneDownTerminalAction, ResizePaneLeftTerminalAction, ResizePaneRightTerminalAction, ResizePaneUpTerminalAction, RunActiveFileInTerminalAction, RunSelectedTextInTerminalAction, ScrollDownPageTerminalAction, ScrollDownTerminalAction, ScrollToBottomTerminalAction, ScrollToNextCommandAction, ScrollToPreviousCommandAction, ScrollToTopTerminalAction, ScrollUpPageTerminalAction, ScrollUpTerminalAction, SelectAllTerminalAction, SelectDefaultShellWindowsTerminalAction, SelectToNextCommandAction, SelectToNextLineAction, SelectToPreviousCommandAction, SelectToPreviousLineAction, SendSequenceTerminalCommand, SplitInActiveWorkspaceTerminalAction, SplitTerminalAction, TerminalPasteAction, TERMINAL_PICKER_PREFIX, ToggleCaseSensitiveCommand, ToggleEscapeSequenceLoggingAction, ToggleRegexCommand, ToggleTerminalAction, ToggleWholeWordCommand, NavigationModeFocusPreviousTerminalAction, NavigationModeFocusNextTerminalAction, NavigationModeExitTerminalAction, ManageWorkspaceShellPermissionsTerminalCommand, CreateNewWithCwdTerminalCommand, RenameWithArgTerminalCommand } from 'vs/workbench/contrib/terminal/browser/terminalActions'; import { TerminalPanel } from 'vs/workbench/contrib/terminal/browser/terminalPanel'; import { TerminalPickerHandler } from 'vs/workbench/contrib/terminal/browser/terminalQuickOpen'; import { KEYBINDING_CONTEXT_TERMINAL_FIND_WIDGET_FOCUSED, KEYBINDING_CONTEXT_TERMINAL_FIND_WIDGET_NOT_VISIBLE, KEYBINDING_CONTEXT_TERMINAL_FIND_WIDGET_VISIBLE, KEYBINDING_CONTEXT_TERMINAL_FOCUS, KEYBINDING_CONTEXT_TERMINAL_TEXT_SELECTED, TERMINAL_PANEL_ID, DEFAULT_LETTER_SPACING, DEFAULT_LINE_HEIGHT, TerminalCursorStyle, TERMINAL_ACTION_CATEGORY, KEYBINDING_CONTEXT_TERMINAL_A11Y_TREE_FOCUS, TERMINAL_COMMAND_ID } from 'vs/workbench/contrib/terminal/common/terminal'; import { registerColors } from 'vs/workbench/contrib/terminal/common/terminalColorRegistry'; import { setupTerminalCommands } from 'vs/workbench/contrib/terminal/browser/terminalCommands'; import { setupTerminalMenu } from 'vs/workbench/contrib/terminal/common/terminalMenu'; import { IConfigurationRegistry, Extensions } from 'vs/platform/configuration/common/configurationRegistry'; import { EDITOR_FONT_DEFAULTS } from 'vs/editor/common/config/editorOptions'; import { DEFAULT_COMMANDS_TO_SKIP_SHELL } from 'vs/workbench/contrib/terminal/browser/terminalInstance'; import { TerminalService } from 'vs/workbench/contrib/terminal/browser/terminalService'; import { registerSingleton } from 'vs/platform/instantiation/common/extensions'; import { registerShellConfiguration } from 'vs/workbench/contrib/terminal/common/terminalShellConfig'; import { CONTEXT_ACCESSIBILITY_MODE_ENABLED } from 'vs/platform/accessibility/common/accessibility'; import { ITerminalService } from 'vs/workbench/contrib/terminal/browser/terminal'; import { BrowserFeatures } from 'vs/base/browser/canIUse'; registerSingleton(ITerminalService, TerminalService, true); if (platform.isWeb) { registerShellConfiguration(); } const quickOpenRegistry = (Registry.as<IQuickOpenRegistry>(QuickOpenExtensions.Quickopen)); const inTerminalsPicker = 'inTerminalPicker'; quickOpenRegistry.registerQuickOpenHandler( QuickOpenHandlerDescriptor.create( TerminalPickerHandler, TerminalPickerHandler.ID, TERMINAL_PICKER_PREFIX, inTerminalsPicker, nls.localize('quickOpen.terminal', "Show All Opened Terminals") ) ); const quickOpenNavigateNextInTerminalPickerId = 'workbench.action.quickOpenNavigateNextInTerminalPicker'; CommandsRegistry.registerCommand( { id: quickOpenNavigateNextInTerminalPickerId, handler: getQuickNavigateHandler(quickOpenNavigateNextInTerminalPickerId, true) }); const quickOpenNavigatePreviousInTerminalPickerId = 'workbench.action.quickOpenNavigatePreviousInTerminalPicker'; CommandsRegistry.registerCommand( { id: quickOpenNavigatePreviousInTerminalPickerId, handler: getQuickNavigateHandler(quickOpenNavigatePreviousInTerminalPickerId, false) }); const configurationRegistry = Registry.as<IConfigurationRegistry>(Extensions.Configuration); configurationRegistry.registerConfiguration({ id: 'terminal', order: 100, title: nls.localize('terminalIntegratedConfigurationTitle', "Integrated Terminal"), type: 'object', properties: { 'terminal.integrated.automationShell.linux': { markdownDescription: nls.localize('terminal.integrated.automationShell.linux', "A path that when set will override {0} and ignore {1} values for automation-related terminal usage like tasks and debug.", '`terminal.integrated.shell.linux`', '`shellArgs`'), type: ['string', 'null'], default: null }, 'terminal.integrated.automationShell.osx': { markdownDescription: nls.localize('terminal.integrated.automationShell.osx', "A path that when set will override {0} and ignore {1} values for automation-related terminal usage like tasks and debug.", '`terminal.integrated.shell.osx`', '`shellArgs`'), type: ['string', 'null'], default: null }, 'terminal.integrated.automationShell.windows': { markdownDescription: nls.localize('terminal.integrated.automationShell.windows', "A path that when set will override {0} and ignore {1} values for automation-related terminal usage like tasks and debug.", '`terminal.integrated.shell.windows`', '`shellArgs`'), type: ['string', 'null'], default: null }, 'terminal.integrated.shellArgs.linux': { markdownDescription: nls.localize('terminal.integrated.shellArgs.linux', "The command line arguments to use when on the Linux terminal. [Read more about configuring the shell](https://code.visualstudio.com/docs/editor/integrated-terminal#_configuration)."), type: 'array', items: { type: 'string' }, default: [] }, 'terminal.integrated.shellArgs.osx': { markdownDescription: nls.localize('terminal.integrated.shellArgs.osx', "The command line arguments to use when on the macOS terminal. [Read more about configuring the shell](https://code.visualstudio.com/docs/editor/integrated-terminal#_configuration)."), type: 'array', items: { type: 'string' }, // Unlike on Linux, ~/.profile is not sourced when logging into a macOS session. This // is the reason terminals on macOS typically run login shells by default which set up // the environment. See http://unix.stackexchange.com/a/119675/115410 default: ['-l'] }, 'terminal.integrated.shellArgs.windows': { markdownDescription: nls.localize('terminal.integrated.shellArgs.windows', "The command line arguments to use when on the Windows terminal. [Read more about configuring the shell](https://code.visualstudio.com/docs/editor/integrated-terminal#_configuration)."), 'anyOf': [ { type: 'array', items: { type: 'string', markdownDescription: nls.localize('terminal.integrated.shellArgs.windows', "The command line arguments to use when on the Windows terminal. [Read more about configuring the shell](https://code.visualstudio.com/docs/editor/integrated-terminal#_configuration).") }, }, { type: 'string', markdownDescription: nls.localize('terminal.integrated.shellArgs.windows.string', "The command line arguments in [command-line format](https://msdn.microsoft.com/en-au/08dfcab2-eb6e-49a4-80eb-87d4076c98c6) to use when on the Windows terminal. [Read more about configuring the shell](https://code.visualstudio.com/docs/editor/integrated-terminal#_configuration).") } ], default: [] }, 'terminal.integrated.macOptionIsMeta': { description: nls.localize('terminal.integrated.macOptionIsMeta', "Controls whether to treat the option key as the meta key in the terminal on macOS."), type: 'boolean', default: false }, 'terminal.integrated.macOptionClickForcesSelection': { description: nls.localize('terminal.integrated.macOptionClickForcesSelection', "Controls whether to force selection when using Option+click on macOS. This will force a regular (line) selection and disallow the use of column selection mode. This enables copying and pasting using the regular terminal selection, for example, when mouse mode is enabled in tmux."), type: 'boolean', default: false }, 'terminal.integrated.copyOnSelection': { description: nls.localize('terminal.integrated.copyOnSelection', "Controls whether text selected in the terminal will be copied to the clipboard."), type: 'boolean', default: false }, 'terminal.integrated.drawBoldTextInBrightColors': { description: nls.localize('terminal.integrated.drawBoldTextInBrightColors', "Controls whether bold text in the terminal will always use the \"bright\" ANSI color variant."), type: 'boolean', default: true }, 'terminal.integrated.fontFamily': { markdownDescription: nls.localize('terminal.integrated.fontFamily', "Controls the font family of the terminal, this defaults to `#editor.fontFamily#`'s value."), type: 'string' }, // TODO: Support font ligatures // 'terminal.integrated.fontLigatures': { // 'description': nls.localize('terminal.integrated.fontLigatures', "Controls whether font ligatures are enabled in the terminal."), // 'type': 'boolean', // 'default': false // }, 'terminal.integrated.fontSize': { description: nls.localize('terminal.integrated.fontSize', "Controls the font size in pixels of the terminal."), type: 'number', default: EDITOR_FONT_DEFAULTS.fontSize }, 'terminal.integrated.letterSpacing': { description: nls.localize('terminal.integrated.letterSpacing', "Controls the letter spacing of the terminal, this is an integer value which represents the amount of additional pixels to add between characters."), type: 'number', default: DEFAULT_LETTER_SPACING }, 'terminal.integrated.lineHeight': { description: nls.localize('terminal.integrated.lineHeight', "Controls the line height of the terminal, this number is multiplied by the terminal font size to get the actual line-height in pixels."), type: 'number', default: DEFAULT_LINE_HEIGHT }, 'terminal.integrated.minimumContrastRatio': { markdownDescription: nls.localize('terminal.integrated.minimumContrastRatio', "When set the foreground color of each cell will change to try meet the contrast ratio specified. Example values:\n\n- 1: The default, do nothing.\n- 4.5: [WCAG AA compliance (minimum)](https://www.w3.org/TR/UNDERSTANDING-WCAG20/visual-audio-contrast-contrast.html).\n- 7: [WCAG AAA compliance (enhanced)](https://www.w3.org/TR/UNDERSTANDING-WCAG20/visual-audio-contrast7.html).\n- 21: White on black or black on white."), type: 'number', default: 1 }, 'terminal.integrated.fastScrollSensitivity': { markdownDescription: nls.localize('terminal.integrated.fastScrollSensitivity', "Scrolling speed multiplier when pressing `Alt`."), type: 'number', default: 5 }, 'terminal.integrated.mouseWheelScrollSensitivity': { markdownDescription: nls.localize('terminal.integrated.mouseWheelScrollSensitivity', "A multiplier to be used on the `deltaY` of mouse wheel scroll events."), type: 'number', default: 1 }, 'terminal.integrated.fontWeight': { type: 'string', enum: ['normal', 'bold', '100', '200', '300', '400', '500', '600', '700', '800', '900'], description: nls.localize('terminal.integrated.fontWeight', "The font weight to use within the terminal for non-bold text."), default: 'normal' }, 'terminal.integrated.fontWeightBold': { type: 'string', enum: ['normal', 'bold', '100', '200', '300', '400', '500', '600', '700', '800', '900'], description: nls.localize('terminal.integrated.fontWeightBold', "The font weight to use within the terminal for bold text."), default: 'bold' }, 'terminal.integrated.cursorBlinking': { description: nls.localize('terminal.integrated.cursorBlinking', "Controls whether the terminal cursor blinks."), type: 'boolean', default: false }, 'terminal.integrated.cursorStyle': { description: nls.localize('terminal.integrated.cursorStyle', "Controls the style of terminal cursor."), enum: [TerminalCursorStyle.BLOCK, TerminalCursorStyle.LINE, TerminalCursorStyle.UNDERLINE], default: TerminalCursorStyle.BLOCK }, 'terminal.integrated.scrollback': { description: nls.localize('terminal.integrated.scrollback', "Controls the maximum amount of lines the terminal keeps in its buffer."), type: 'number', default: 1000 }, 'terminal.integrated.detectLocale': { markdownDescription: nls.localize('terminal.integrated.detectLocale', "Controls whether to detect and set the `$LANG` environment variable to a UTF-8 compliant option since VS Code's terminal only supports UTF-8 encoded data coming from the shell."), type: 'string', enum: ['auto', 'off', 'on'], markdownEnumDescriptions: [ nls.localize('terminal.integrated.detectLocale.auto', "Set the `$LANG` environment variable if the existing variable does not exist or it does not end in `'.UTF-8'`."), nls.localize('terminal.integrated.detectLocale.off', "Do not set the `$LANG` environment variable."), nls.localize('terminal.integrated.detectLocale.on', "Always set the `$LANG` environment variable.") ], default: 'auto' }, 'terminal.integrated.rendererType': { type: 'string', enum: ['auto', 'canvas', 'dom', 'experimentalWebgl'], markdownEnumDescriptions: [ nls.localize('terminal.integrated.rendererType.auto', "Let VS Code guess which renderer to use."), nls.localize('terminal.integrated.rendererType.canvas', "Use the standard GPU/canvas-based renderer."), nls.localize('terminal.integrated.rendererType.dom', "Use the fallback DOM-based renderer."), nls.localize('terminal.integrated.rendererType.experimentalWebgl', "Use the experimental webgl-based renderer. Note that this has some [known issues](https://github.com/xtermjs/xterm.js/issues?q=is%3Aopen+is%3Aissue+label%3Aarea%2Faddon%2Fwebgl) and this will only be enabled for new terminals (not hot swappable like the other renderers).") ], default: 'auto', description: nls.localize('terminal.integrated.rendererType', "Controls how the terminal is rendered.") }, 'terminal.integrated.rightClickBehavior': { type: 'string', enum: ['default', 'copyPaste', 'paste', 'selectWord'], enumDescriptions: [ nls.localize('terminal.integrated.rightClickBehavior.default', "Show the context menu."), nls.localize('terminal.integrated.rightClickBehavior.copyPaste', "Copy when there is a selection, otherwise paste."), nls.localize('terminal.integrated.rightClickBehavior.paste', "Paste on right click."), nls.localize('terminal.integrated.rightClickBehavior.selectWord', "Select the word under the cursor and show the context menu.") ], default: platform.isMacintosh ? 'selectWord' : platform.isWindows ? 'copyPaste' : 'default', description: nls.localize('terminal.integrated.rightClickBehavior', "Controls how terminal reacts to right click.") }, 'terminal.integrated.cwd': { description: nls.localize('terminal.integrated.cwd', "An explicit start path where the terminal will be launched, this is used as the current working directory (cwd) for the shell process. This may be particularly useful in workspace settings if the root directory is not a convenient cwd."), type: 'string', default: undefined }, 'terminal.integrated.confirmOnExit': { description: nls.localize('terminal.integrated.confirmOnExit', "Controls whether to confirm on exit if there are active terminal sessions."), type: 'boolean', default: false }, 'terminal.integrated.enableBell': { description: nls.localize('terminal.integrated.enableBell', "Controls whether the terminal bell is enabled."), type: 'boolean', default: false }, 'terminal.integrated.commandsToSkipShell': { markdownDescription: nls.localize('terminal.integrated.commandsToSkipShell', "A set of command IDs whose keybindings will not be sent to the shell and instead always be handled by Code. This allows the use of keybindings that would normally be consumed by the shell to act the same as when the terminal is not focused, for example ctrl+p to launch Quick Open.\nDefault Skipped Commands:\n\n{0}", DEFAULT_COMMANDS_TO_SKIP_SHELL.sort().map(command => `- ${command}`).join('\n')), type: 'array', items: { type: 'string' }, default: [] }, 'terminal.integrated.allowChords': { markdownDescription: nls.localize('terminal.integrated.allowChords', "Whether or not to allow chord keybindings in the terminal. Note that when this is true and the keystroke results in a chord it will bypass `#terminal.integrated.commandsToSkipShell#`, setting this to false is particularly useful when you want ctrl+k to go to your shell (not VS Code)."), type: 'boolean', default: true }, 'terminal.integrated.inheritEnv': { markdownDescription: nls.localize('terminal.integrated.inheritEnv', "Whether new shells should inherit their environment from VS Code. This is not supported on Windows."), type: 'boolean', default: true }, 'terminal.integrated.env.osx': { markdownDescription: nls.localize('terminal.integrated.env.osx', "Object with environment variables that will be added to the VS Code process to be used by the terminal on macOS. Set to `null` to delete the environment variable."), type: 'object', additionalProperties: { type: ['string', 'null'] }, default: {} }, 'terminal.integrated.env.linux': { markdownDescription: nls.localize('terminal.integrated.env.linux', "Object with environment variables that will be added to the VS Code process to be used by the terminal on Linux. Set to `null` to delete the environment variable."), type: 'object', additionalProperties: { type: ['string', 'null'] }, default: {} }, 'terminal.integrated.env.windows': { markdownDescription: nls.localize('terminal.integrated.env.windows', "Object with environment variables that will be added to the VS Code process to be used by the terminal on Windows. Set to `null` to delete the environment variable."), type: 'object', additionalProperties: { type: ['string', 'null'] }, default: {} }, 'terminal.integrated.showExitAlert': { description: nls.localize('terminal.integrated.showExitAlert', "Controls whether to show the alert \"The terminal process terminated with exit code\" when exit code is non-zero."), type: 'boolean', default: true }, 'terminal.integrated.splitCwd': { description: nls.localize('terminal.integrated.splitCwd', "Controls the working directory a split terminal starts with."), type: 'string', enum: ['workspaceRoot', 'initial', 'inherited'], enumDescriptions: [ nls.localize('terminal.integrated.splitCwd.workspaceRoot', "A new split terminal will use the workspace root as the working directory. In a multi-root workspace a choice for which root folder to use is offered."), nls.localize('terminal.integrated.splitCwd.initial', "A new split terminal will use the working directory that the parent terminal started with."), nls.localize('terminal.integrated.splitCwd.inherited', "On macOS and Linux, a new split terminal will use the working directory of the parent terminal. On Windows, this behaves the same as initial."), ], default: 'inherited' }, 'terminal.integrated.windowsEnableConpty': { description: nls.localize('terminal.integrated.windowsEnableConpty', "Whether to use ConPTY for Windows terminal process communication (requires Windows 10 build number 18309+). Winpty will be used if this is false."), type: 'boolean', default: true }, 'terminal.integrated.experimentalRefreshOnResume': { description: nls.localize('terminal.integrated.experimentalRefreshOnResume', "An experimental setting that will refresh the terminal renderer when the system is resumed."), type: 'boolean', default: false }, 'terminal.integrated.experimentalUseTitleEvent': { description: nls.localize('terminal.integrated.experimentalUseTitleEvent', "An experimental setting that will use the terminal title event for the dropdown title. This setting will only apply to new terminals."), type: 'boolean', default: false }, 'terminal.integrated.enableFileLinks': { description: nls.localize('terminal.integrated.enableFileLinks', "Whether to enable file links in the terminal. Links can be slow when working on a network drive in particular because each file link is verified against the file system."), type: 'boolean', default: true } } }); const registry = Registry.as<IWorkbenchActionRegistry>(ActionExtensions.WorkbenchActions); registry.registerWorkbenchAction(SyncActionDescriptor.create(QuickOpenTermAction, QuickOpenTermAction.ID, QuickOpenTermAction.LABEL), 'Terminal: Switch Active Terminal', nls.localize('terminal', "Terminal")); const actionBarRegistry = Registry.as<IActionBarRegistry>(ActionBarExtensions.Actionbar); actionBarRegistry.registerActionBarContributor(Scope.VIEWER, QuickOpenActionTermContributor); (<panel.PanelRegistry>Registry.as(panel.Extensions.Panels)).registerPanel(panel.PanelDescriptor.create( TerminalPanel, TERMINAL_PANEL_ID, nls.localize('terminal', "Terminal"), 'terminal', 40, TERMINAL_COMMAND_ID.TOGGLE )); Registry.as<panel.PanelRegistry>(panel.Extensions.Panels).setDefaultPanelId(TERMINAL_PANEL_ID); // On mac cmd+` is reserved to cycle between windows, that's why the keybindings use WinCtrl const category = TERMINAL_ACTION_CATEGORY; const actionRegistry = Registry.as<IWorkbenchActionRegistry>(ActionExtensions.WorkbenchActions); actionRegistry.registerWorkbenchAction(SyncActionDescriptor.create(KillTerminalAction, KillTerminalAction.ID, KillTerminalAction.LABEL), 'Terminal: Kill the Active Terminal Instance', category); actionRegistry.registerWorkbenchAction(SyncActionDescriptor.create(CreateNewTerminalAction, CreateNewTerminalAction.ID, CreateNewTerminalAction.LABEL, { primary: KeyMod.CtrlCmd | KeyMod.Shift | KeyCode.US_BACKTICK, mac: { primary: KeyMod.WinCtrl | KeyMod.Shift | KeyCode.US_BACKTICK } }), 'Terminal: Create New Integrated Terminal', category); actionRegistry.registerWorkbenchAction(SyncActionDescriptor.create(ClearSelectionTerminalAction, ClearSelectionTerminalAction.ID, ClearSelectionTerminalAction.LABEL, { primary: KeyCode.Escape, linux: { primary: KeyCode.Escape } }, ContextKeyExpr.and(KEYBINDING_CONTEXT_TERMINAL_FOCUS, KEYBINDING_CONTEXT_TERMINAL_TEXT_SELECTED, KEYBINDING_CONTEXT_TERMINAL_FIND_WIDGET_NOT_VISIBLE)), 'Terminal: Clear Selection', category); actionRegistry.registerWorkbenchAction(SyncActionDescriptor.create(CreateNewInActiveWorkspaceTerminalAction, CreateNewInActiveWorkspaceTerminalAction.ID, CreateNewInActiveWorkspaceTerminalAction.LABEL), 'Terminal: Create New Integrated Terminal (In Active Workspace)', category); actionRegistry.registerWorkbenchAction(SyncActionDescriptor.create(FocusActiveTerminalAction, FocusActiveTerminalAction.ID, FocusActiveTerminalAction.LABEL), 'Terminal: Focus Terminal', category); actionRegistry.registerWorkbenchAction(SyncActionDescriptor.create(FocusNextTerminalAction, FocusNextTerminalAction.ID, FocusNextTerminalAction.LABEL), 'Terminal: Focus Next Terminal', category); actionRegistry.registerWorkbenchAction(SyncActionDescriptor.create(FocusPreviousTerminalAction, FocusPreviousTerminalAction.ID, FocusPreviousTerminalAction.LABEL), 'Terminal: Focus Previous Terminal', category); actionRegistry.registerWorkbenchAction(SyncActionDescriptor.create(SelectAllTerminalAction, SelectAllTerminalAction.ID, SelectAllTerminalAction.LABEL, { // Don't use ctrl+a by default as that would override the common go to start // of prompt shell binding primary: 0, // Technically this doesn't need to be here as it will fall back to this // behavior anyway when handed to xterm.js, having this handled by VS Code // makes it easier for users to see how it works though. mac: { primary: KeyMod.CtrlCmd | KeyCode.KEY_A } }, KEYBINDING_CONTEXT_TERMINAL_FOCUS), 'Terminal: Select All', category); actionRegistry.registerWorkbenchAction(SyncActionDescriptor.create(RunSelectedTextInTerminalAction, RunSelectedTextInTerminalAction.ID, RunSelectedTextInTerminalAction.LABEL), 'Terminal: Run Selected Text In Active Terminal', category); actionRegistry.registerWorkbenchAction(SyncActionDescriptor.create(RunActiveFileInTerminalAction, RunActiveFileInTerminalAction.ID, RunActiveFileInTerminalAction.LABEL), 'Terminal: Run Active File In Active Terminal', category); actionRegistry.registerWorkbenchAction(SyncActionDescriptor.create(ToggleTerminalAction, ToggleTerminalAction.ID, ToggleTerminalAction.LABEL, { primary: KeyMod.CtrlCmd | KeyCode.US_BACKTICK, mac: { primary: KeyMod.WinCtrl | KeyCode.US_BACKTICK } }), 'View: Toggle Integrated Terminal', nls.localize('viewCategory', "View")); actionRegistry.registerWorkbenchAction(SyncActionDescriptor.create(ScrollDownTerminalAction, ScrollDownTerminalAction.ID, ScrollDownTerminalAction.LABEL, { primary: KeyMod.CtrlCmd | KeyMod.Alt | KeyCode.PageDown, linux: { primary: KeyMod.CtrlCmd | KeyMod.Shift | KeyCode.DownArrow } }, KEYBINDING_CONTEXT_TERMINAL_FOCUS), 'Terminal: Scroll Down (Line)', category); actionRegistry.registerWorkbenchAction(SyncActionDescriptor.create(ScrollDownPageTerminalAction, ScrollDownPageTerminalAction.ID, ScrollDownPageTerminalAction.LABEL, { primary: KeyMod.Shift | KeyCode.PageDown, mac: { primary: KeyCode.PageDown } }, KEYBINDING_CONTEXT_TERMINAL_FOCUS), 'Terminal: Scroll Down (Page)', category); actionRegistry.registerWorkbenchAction(SyncActionDescriptor.create(ScrollToBottomTerminalAction, ScrollToBottomTerminalAction.ID, ScrollToBottomTerminalAction.LABEL, { primary: KeyMod.CtrlCmd | KeyCode.End, linux: { primary: KeyMod.Shift | KeyCode.End } }, KEYBINDING_CONTEXT_TERMINAL_FOCUS), 'Terminal: Scroll to Bottom', category); actionRegistry.registerWorkbenchAction(SyncActionDescriptor.create(ScrollUpTerminalAction, ScrollUpTerminalAction.ID, ScrollUpTerminalAction.LABEL, { primary: KeyMod.CtrlCmd | KeyMod.Alt | KeyCode.PageUp, linux: { primary: KeyMod.CtrlCmd | KeyMod.Shift | KeyCode.UpArrow }, }, KEYBINDING_CONTEXT_TERMINAL_FOCUS), 'Terminal: Scroll Up (Line)', category); actionRegistry.registerWorkbenchAction(SyncActionDescriptor.create(ScrollUpPageTerminalAction, ScrollUpPageTerminalAction.ID, ScrollUpPageTerminalAction.LABEL, { primary: KeyMod.Shift | KeyCode.PageUp, mac: { primary: KeyCode.PageUp } }, KEYBINDING_CONTEXT_TERMINAL_FOCUS), 'Terminal: Scroll Up (Page)', category); actionRegistry.registerWorkbenchAction(SyncActionDescriptor.create(ScrollToTopTerminalAction, ScrollToTopTerminalAction.ID, ScrollToTopTerminalAction.LABEL, { primary: KeyMod.CtrlCmd | KeyCode.Home, linux: { primary: KeyMod.Shift | KeyCode.Home } }, KEYBINDING_CONTEXT_TERMINAL_FOCUS), 'Terminal: Scroll to Top', category); actionRegistry.registerWorkbenchAction(SyncActionDescriptor.create(ClearTerminalAction, ClearTerminalAction.ID, ClearTerminalAction.LABEL, { primary: 0, mac: { primary: KeyMod.CtrlCmd | KeyCode.KEY_K } }, KEYBINDING_CONTEXT_TERMINAL_FOCUS, KeybindingWeight.WorkbenchContrib + 1), 'Terminal: Clear', category); actionRegistry.registerWorkbenchAction(SyncActionDescriptor.create(SelectDefaultShellWindowsTerminalAction, SelectDefaultShellWindowsTerminalAction.ID, SelectDefaultShellWindowsTerminalAction.LABEL), 'Terminal: Select Default Shell', category); actionRegistry.registerWorkbenchAction(SyncActionDescriptor.create(ManageWorkspaceShellPermissionsTerminalCommand, ManageWorkspaceShellPermissionsTerminalCommand.ID, ManageWorkspaceShellPermissionsTerminalCommand.LABEL), 'Terminal: Manage Workspace Shell Permissions', category); actionRegistry.registerWorkbenchAction(SyncActionDescriptor.create(RenameTerminalAction, RenameTerminalAction.ID, RenameTerminalAction.LABEL), 'Terminal: Rename', category); actionRegistry.registerWorkbenchAction(SyncActionDescriptor.create(FocusTerminalFindWidgetAction, FocusTerminalFindWidgetAction.ID, FocusTerminalFindWidgetAction.LABEL, { primary: KeyMod.CtrlCmd | KeyCode.KEY_F }, KEYBINDING_CONTEXT_TERMINAL_FOCUS), 'Terminal: Focus Find Widget', category); actionRegistry.registerWorkbenchAction(SyncActionDescriptor.create(FocusTerminalFindWidgetAction, FocusTerminalFindWidgetAction.ID, FocusTerminalFindWidgetAction.LABEL, { primary: KeyMod.CtrlCmd | KeyCode.KEY_F }, KEYBINDING_CONTEXT_TERMINAL_FIND_WIDGET_FOCUSED), 'Terminal: Focus Find Widget', category); actionRegistry.registerWorkbenchAction(SyncActionDescriptor.create(HideTerminalFindWidgetAction, HideTerminalFindWidgetAction.ID, HideTerminalFindWidgetAction.LABEL, { primary: KeyCode.Escape, secondary: [KeyMod.Shift | KeyCode.Escape] }, ContextKeyExpr.and(KEYBINDING_CONTEXT_TERMINAL_FOCUS, KEYBINDING_CONTEXT_TERMINAL_FIND_WIDGET_VISIBLE)), 'Terminal: Hide Find Widget', category); actionRegistry.registerWorkbenchAction(SyncActionDescriptor.create(DeleteWordLeftTerminalAction, DeleteWordLeftTerminalAction.ID, DeleteWordLeftTerminalAction.LABEL, { primary: KeyMod.CtrlCmd | KeyCode.Backspace, mac: { primary: KeyMod.Alt | KeyCode.Backspace } }, KEYBINDING_CONTEXT_TERMINAL_FOCUS), 'Terminal: Delete Word Left', category); actionRegistry.registerWorkbenchAction(SyncActionDescriptor.create(DeleteWordRightTerminalAction, DeleteWordRightTerminalAction.ID, DeleteWordRightTerminalAction.LABEL, { primary: KeyMod.CtrlCmd | KeyCode.Delete, mac: { primary: KeyMod.Alt | KeyCode.Delete } }, KEYBINDING_CONTEXT_TERMINAL_FOCUS), 'Terminal: Delete Word Right', category); actionRegistry.registerWorkbenchAction(SyncActionDescriptor.create(DeleteToLineStartTerminalAction, DeleteToLineStartTerminalAction.ID, DeleteToLineStartTerminalAction.LABEL, { primary: 0, mac: { primary: KeyMod.CtrlCmd | KeyCode.Backspace } }, KEYBINDING_CONTEXT_TERMINAL_FOCUS), 'Terminal: Delete To Line Start', category); actionRegistry.registerWorkbenchAction(SyncActionDescriptor.create(MoveToLineStartTerminalAction, MoveToLineStartTerminalAction.ID, MoveToLineStartTerminalAction.LABEL, { primary: 0, mac: { primary: KeyMod.CtrlCmd | KeyCode.LeftArrow } }, KEYBINDING_CONTEXT_TERMINAL_FOCUS), 'Terminal: Move To Line Start', category); actionRegistry.registerWorkbenchAction(SyncActionDescriptor.create(MoveToLineEndTerminalAction, MoveToLineEndTerminalAction.ID, MoveToLineEndTerminalAction.LABEL, { primary: 0, mac: { primary: KeyMod.CtrlCmd | KeyCode.RightArrow } }, KEYBINDING_CONTEXT_TERMINAL_FOCUS), 'Terminal: Move To Line End', category); actionRegistry.registerWorkbenchAction(SyncActionDescriptor.create(SplitTerminalAction, SplitTerminalAction.ID, SplitTerminalAction.LABEL, { primary: KeyMod.CtrlCmd | KeyMod.Shift | KeyCode.KEY_5, mac: { primary: KeyMod.CtrlCmd | KeyCode.US_BACKSLASH, secondary: [KeyMod.WinCtrl | KeyMod.Shift | KeyCode.KEY_5] } }, KEYBINDING_CONTEXT_TERMINAL_FOCUS), 'Terminal: Split Terminal', category); actionRegistry.registerWorkbenchAction(SyncActionDescriptor.create(SplitInActiveWorkspaceTerminalAction, SplitInActiveWorkspaceTerminalAction.ID, SplitInActiveWorkspaceTerminalAction.LABEL), 'Terminal: Split Terminal (In Active Workspace)', category); actionRegistry.registerWorkbenchAction(SyncActionDescriptor.create(FocusPreviousPaneTerminalAction, FocusPreviousPaneTerminalAction.ID, FocusPreviousPaneTerminalAction.LABEL, { primary: KeyMod.Alt | KeyCode.LeftArrow, secondary: [KeyMod.Alt | KeyCode.UpArrow], mac: { primary: KeyMod.Alt | KeyMod.CtrlCmd | KeyCode.LeftArrow, secondary: [KeyMod.Alt | KeyMod.CtrlCmd | KeyCode.UpArrow] } }, KEYBINDING_CONTEXT_TERMINAL_FOCUS), 'Terminal: Focus Previous Pane', category); actionRegistry.registerWorkbenchAction(SyncActionDescriptor.create(FocusNextPaneTerminalAction, FocusNextPaneTerminalAction.ID, FocusNextPaneTerminalAction.LABEL, { primary: KeyMod.Alt | KeyCode.RightArrow, secondary: [KeyMod.Alt | KeyCode.DownArrow], mac: { primary: KeyMod.Alt | KeyMod.CtrlCmd | KeyCode.RightArrow, secondary: [KeyMod.Alt | KeyMod.CtrlCmd | KeyCode.DownArrow] } }, KEYBINDING_CONTEXT_TERMINAL_FOCUS), 'Terminal: Focus Next Pane', category); actionRegistry.registerWorkbenchAction(SyncActionDescriptor.create(ResizePaneLeftTerminalAction, ResizePaneLeftTerminalAction.ID, ResizePaneLeftTerminalAction.LABEL, { primary: 0, linux: { primary: KeyMod.CtrlCmd | KeyMod.Shift | KeyCode.LeftArrow }, mac: { primary: KeyMod.CtrlCmd | KeyMod.WinCtrl | KeyCode.LeftArrow } }, KEYBINDING_CONTEXT_TERMINAL_FOCUS), 'Terminal: Resize Pane Left', category); actionRegistry.registerWorkbenchAction(SyncActionDescriptor.create(ResizePaneRightTerminalAction, ResizePaneRightTerminalAction.ID, ResizePaneRightTerminalAction.LABEL, { primary: 0, linux: { primary: KeyMod.CtrlCmd | KeyMod.Shift | KeyCode.RightArrow }, mac: { primary: KeyMod.CtrlCmd | KeyMod.WinCtrl | KeyCode.RightArrow } }, KEYBINDING_CONTEXT_TERMINAL_FOCUS), 'Terminal: Resize Pane Right', category); actionRegistry.registerWorkbenchAction(SyncActionDescriptor.create(ResizePaneUpTerminalAction, ResizePaneUpTerminalAction.ID, ResizePaneUpTerminalAction.LABEL, { primary: 0, mac: { primary: KeyMod.CtrlCmd | KeyMod.WinCtrl | KeyCode.UpArrow } }, KEYBINDING_CONTEXT_TERMINAL_FOCUS), 'Terminal: Resize Pane Up', category); actionRegistry.registerWorkbenchAction(SyncActionDescriptor.create(ResizePaneDownTerminalAction, ResizePaneDownTerminalAction.ID, ResizePaneDownTerminalAction.LABEL, { primary: 0, mac: { primary: KeyMod.CtrlCmd | KeyMod.WinCtrl | KeyCode.DownArrow } }, KEYBINDING_CONTEXT_TERMINAL_FOCUS), 'Terminal: Resize Pane Down', category); actionRegistry.registerWorkbenchAction(SyncActionDescriptor.create(ScrollToPreviousCommandAction, ScrollToPreviousCommandAction.ID, ScrollToPreviousCommandAction.LABEL, { primary: 0, mac: { primary: KeyMod.CtrlCmd | KeyCode.UpArrow } }, ContextKeyExpr.and(KEYBINDING_CONTEXT_TERMINAL_FOCUS, CONTEXT_ACCESSIBILITY_MODE_ENABLED.negate())), 'Terminal: Scroll To Previous Command', category); actionRegistry.registerWorkbenchAction(SyncActionDescriptor.create(ScrollToNextCommandAction, ScrollToNextCommandAction.ID, ScrollToNextCommandAction.LABEL, { primary: 0, mac: { primary: KeyMod.CtrlCmd | KeyCode.DownArrow } }, ContextKeyExpr.and(KEYBINDING_CONTEXT_TERMINAL_FOCUS, CONTEXT_ACCESSIBILITY_MODE_ENABLED.negate())), 'Terminal: Scroll To Next Command', category); actionRegistry.registerWorkbenchAction(SyncActionDescriptor.create(SelectToPreviousCommandAction, SelectToPreviousCommandAction.ID, SelectToPreviousCommandAction.LABEL, { primary: 0, mac: { primary: KeyMod.CtrlCmd | KeyMod.Shift | KeyCode.UpArrow } }, KEYBINDING_CONTEXT_TERMINAL_FOCUS), 'Terminal: Select To Previous Command', category); actionRegistry.registerWorkbenchAction(SyncActionDescriptor.create(SelectToNextCommandAction, SelectToNextCommandAction.ID, SelectToNextCommandAction.LABEL, { primary: 0, mac: { primary: KeyMod.CtrlCmd | KeyMod.Shift | KeyCode.DownArrow } }, KEYBINDING_CONTEXT_TERMINAL_FOCUS), 'Terminal: Select To Next Command', category); actionRegistry.registerWorkbenchAction(SyncActionDescriptor.create(NavigationModeExitTerminalAction, NavigationModeExitTerminalAction.ID, NavigationModeExitTerminalAction.LABEL, { primary: KeyCode.Escape }, ContextKeyExpr.and(KEYBINDING_CONTEXT_TERMINAL_A11Y_TREE_FOCUS, CONTEXT_ACCESSIBILITY_MODE_ENABLED)), 'Terminal: Exit Navigation Mode', category); actionRegistry.registerWorkbenchAction(SyncActionDescriptor.create(NavigationModeFocusPreviousTerminalAction, NavigationModeFocusPreviousTerminalAction.ID, NavigationModeFocusPreviousTerminalAction.LABEL, { primary: KeyMod.CtrlCmd | KeyCode.UpArrow }, ContextKeyExpr.and(KEYBINDING_CONTEXT_TERMINAL_FOCUS, CONTEXT_ACCESSIBILITY_MODE_ENABLED)), 'Terminal: Focus Previous Line (Navigation Mode)', category); actionRegistry.registerWorkbenchAction(SyncActionDescriptor.create(NavigationModeFocusPreviousTerminalAction, NavigationModeFocusPreviousTerminalAction.ID, NavigationModeFocusPreviousTerminalAction.LABEL, { primary: KeyMod.CtrlCmd | KeyCode.UpArrow }, ContextKeyExpr.and(KEYBINDING_CONTEXT_TERMINAL_A11Y_TREE_FOCUS, CONTEXT_ACCESSIBILITY_MODE_ENABLED)), 'Terminal: Focus Previous Line (Navigation Mode)', category); actionRegistry.registerWorkbenchAction(SyncActionDescriptor.create(NavigationModeFocusNextTerminalAction, NavigationModeFocusNextTerminalAction.ID, NavigationModeFocusNextTerminalAction.LABEL, { primary: KeyMod.CtrlCmd | KeyCode.DownArrow }, ContextKeyExpr.and(KEYBINDING_CONTEXT_TERMINAL_FOCUS, CONTEXT_ACCESSIBILITY_MODE_ENABLED)), 'Terminal: Focus Next Line (Navigation Mode)', category); actionRegistry.registerWorkbenchAction(SyncActionDescriptor.create(NavigationModeFocusNextTerminalAction, NavigationModeFocusNextTerminalAction.ID, NavigationModeFocusNextTerminalAction.LABEL, { primary: KeyMod.CtrlCmd | KeyCode.DownArrow }, ContextKeyExpr.and(KEYBINDING_CONTEXT_TERMINAL_A11Y_TREE_FOCUS, CONTEXT_ACCESSIBILITY_MODE_ENABLED)), 'Terminal: Focus Next Line (Navigation Mode)', category); actionRegistry.registerWorkbenchAction(SyncActionDescriptor.create(SelectToPreviousLineAction, SelectToPreviousLineAction.ID, SelectToPreviousLineAction.LABEL), 'Terminal: Select To Previous Line', category); actionRegistry.registerWorkbenchAction(SyncActionDescriptor.create(SelectToNextLineAction, SelectToNextLineAction.ID, SelectToNextLineAction.LABEL), 'Terminal: Select To Next Line', category); actionRegistry.registerWorkbenchAction(SyncActionDescriptor.create(ToggleEscapeSequenceLoggingAction, ToggleEscapeSequenceLoggingAction.ID, ToggleEscapeSequenceLoggingAction.LABEL), 'Terminal: Toggle Escape Sequence Logging', category); actionRegistry.registerWorkbenchAction(SyncActionDescriptor.create(ToggleRegexCommand, ToggleRegexCommand.ID, ToggleRegexCommand.LABEL, { primary: KeyMod.Alt | KeyCode.KEY_R, mac: { primary: KeyMod.CtrlCmd | KeyMod.Alt | KeyCode.KEY_R } }, KEYBINDING_CONTEXT_TERMINAL_FIND_WIDGET_FOCUSED), 'Terminal: Toggle find using regex', category); actionRegistry.registerWorkbenchAction(SyncActionDescriptor.create(ToggleRegexCommand, ToggleRegexCommand.ID, ToggleRegexCommand.LABEL, { primary: KeyMod.Alt | KeyCode.KEY_R, mac: { primary: KeyMod.CtrlCmd | KeyMod.Alt | KeyCode.KEY_R } }, KEYBINDING_CONTEXT_TERMINAL_FOCUS), 'Terminal: Toggle find using regex', category); actionRegistry.registerWorkbenchAction(SyncActionDescriptor.create(ToggleWholeWordCommand, ToggleWholeWordCommand.ID, ToggleWholeWordCommand.LABEL, { primary: KeyMod.Alt | KeyCode.KEY_W, mac: { primary: KeyMod.CtrlCmd | KeyMod.Alt | KeyCode.KEY_W } }, KEYBINDING_CONTEXT_TERMINAL_FIND_WIDGET_FOCUSED), 'Terminal: Toggle find using whole word', category); actionRegistry.registerWorkbenchAction(SyncActionDescriptor.create(ToggleWholeWordCommand, ToggleWholeWordCommand.ID, ToggleWholeWordCommand.LABEL, { primary: KeyMod.Alt | KeyCode.KEY_W, mac: { primary: KeyMod.CtrlCmd | KeyMod.Alt | KeyCode.KEY_W } }, KEYBINDING_CONTEXT_TERMINAL_FOCUS), 'Terminal: Toggle find using whole word', category); actionRegistry.registerWorkbenchAction(SyncActionDescriptor.create(ToggleCaseSensitiveCommand, ToggleCaseSensitiveCommand.ID, ToggleCaseSensitiveCommand.LABEL, { primary: KeyMod.Alt | KeyCode.KEY_C, mac: { primary: KeyMod.CtrlCmd | KeyMod.Alt | KeyCode.KEY_C } }, KEYBINDING_CONTEXT_TERMINAL_FIND_WIDGET_FOCUSED), 'Terminal: Toggle find using case sensitive', category); actionRegistry.registerWorkbenchAction(SyncActionDescriptor.create(ToggleCaseSensitiveCommand, ToggleCaseSensitiveCommand.ID, ToggleCaseSensitiveCommand.LABEL, { primary: KeyMod.Alt | KeyCode.KEY_C, mac: { primary: KeyMod.CtrlCmd | KeyMod.Alt | KeyCode.KEY_C } }, KEYBINDING_CONTEXT_TERMINAL_FOCUS), 'Terminal: Toggle find using case sensitive', category); actionRegistry.registerWorkbenchAction(SyncActionDescriptor.create(FindNext, FindNext.ID, FindNext.LABEL, { primary: KeyCode.F3, mac: { primary: KeyMod.CtrlCmd | KeyCode.KEY_G, secondary: [KeyCode.F3] } }, KEYBINDING_CONTEXT_TERMINAL_FOCUS), 'Terminal: Find next', category); actionRegistry.registerWorkbenchAction(SyncActionDescriptor.create(FindNext, FindNext.ID, FindNext.LABEL, { primary: KeyCode.F3, secondary: [KeyMod.Shift | KeyCode.Enter], mac: { primary: KeyMod.CtrlCmd | KeyCode.KEY_G, secondary: [KeyCode.F3, KeyMod.Shift | KeyCode.Enter] } }, KEYBINDING_CONTEXT_TERMINAL_FIND_WIDGET_FOCUSED), 'Terminal: Find next', category); actionRegistry.registerWorkbenchAction(SyncActionDescriptor.create(FindPrevious, FindPrevious.ID, FindPrevious.LABEL, { primary: KeyMod.Shift | KeyCode.F3, mac: { primary: KeyMod.CtrlCmd | KeyMod.Shift | KeyCode.KEY_G, secondary: [KeyMod.Shift | KeyCode.F3] }, }, KEYBINDING_CONTEXT_TERMINAL_FOCUS), 'Terminal: Find previous', category); actionRegistry.registerWorkbenchAction(SyncActionDescriptor.create(FindPrevious, FindPrevious.ID, FindPrevious.LABEL, { primary: KeyMod.Shift | KeyCode.F3, secondary: [KeyCode.Enter], mac: { primary: KeyMod.CtrlCmd | KeyMod.Shift | KeyCode.KEY_G, secondary: [KeyMod.Shift | KeyCode.F3, KeyCode.Enter] }, }, KEYBINDING_CONTEXT_TERMINAL_FIND_WIDGET_FOCUSED), 'Terminal: Find previous', category); // Commands might be affected by Web restrictons if (BrowserFeatures.clipboard.writeText) { actionRegistry.registerWorkbenchAction(SyncActionDescriptor.create(CopyTerminalSelectionAction, CopyTerminalSelectionAction.ID, CopyTerminalSelectionAction.LABEL, { primary: KeyMod.CtrlCmd | KeyCode.KEY_C, win: { primary: KeyMod.CtrlCmd | KeyCode.KEY_C, secondary: [KeyMod.CtrlCmd | KeyMod.Shift | KeyCode.KEY_C] }, linux: { primary: KeyMod.CtrlCmd | KeyMod.Shift | KeyCode.KEY_C } }, ContextKeyExpr.and(KEYBINDING_CONTEXT_TERMINAL_TEXT_SELECTED, KEYBINDING_CONTEXT_TERMINAL_FOCUS)), 'Terminal: Copy Selection', category); } if (BrowserFeatures.clipboard.readText) { actionRegistry.registerWorkbenchAction(SyncActionDescriptor.create(TerminalPasteAction, TerminalPasteAction.ID, TerminalPasteAction.LABEL, { primary: KeyMod.CtrlCmd | KeyCode.KEY_V, win: { primary: KeyMod.CtrlCmd | KeyCode.KEY_V, secondary: [KeyMod.CtrlCmd | KeyMod.Shift | KeyCode.KEY_V] }, linux: { primary: KeyMod.CtrlCmd | KeyMod.Shift | KeyCode.KEY_V } }, KEYBINDING_CONTEXT_TERMINAL_FOCUS), 'Terminal: Paste into Active Terminal', category); } (new SendSequenceTerminalCommand({ id: SendSequenceTerminalCommand.ID, precondition: undefined, description: { description: SendSequenceTerminalCommand.LABEL, args: [{ name: 'args', schema: { type: 'object', required: ['text'], properties: { text: { type: 'string' } }, } }] } })).register(); (new CreateNewWithCwdTerminalCommand({ id: CreateNewWithCwdTerminalCommand.ID, precondition: undefined, description: { description: CreateNewWithCwdTerminalCommand.LABEL, args: [{ name: 'args', schema: { type: 'object', required: ['cwd'], properties: { cwd: { description: CreateNewWithCwdTerminalCommand.CWD_ARG_LABEL, type: 'string' } }, } }] } })).register(); (new RenameWithArgTerminalCommand({ id: RenameWithArgTerminalCommand.ID, precondition: undefined, description: { description: RenameWithArgTerminalCommand.LABEL, args: [{ name: 'args', schema: { type: 'object', required: ['name'], properties: { name: { description: RenameWithArgTerminalCommand.NAME_ARG_LABEL, type: 'string', minLength: 1 } } } }] } })).register(); setupTerminalCommands(); setupTerminalMenu(); registerColors();
src/vs/workbench/contrib/terminal/browser/terminal.contribution.ts
1
https://github.com/microsoft/vscode/commit/afc57a083c0c4e20ae87cf52b97820f1b43acfc5
[ 0.027184272184967995, 0.0007608350133523345, 0.00016433425480499864, 0.00017342471983283758, 0.003300509648397565 ]
{ "id": 0, "code_window": [ "\t\t\tenum: [TerminalCursorStyle.BLOCK, TerminalCursorStyle.LINE, TerminalCursorStyle.UNDERLINE],\n", "\t\t\tdefault: TerminalCursorStyle.BLOCK\n", "\t\t},\n", "\t\t'terminal.integrated.scrollback': {\n", "\t\t\tdescription: nls.localize('terminal.integrated.scrollback', \"Controls the maximum amount of lines the terminal keeps in its buffer.\"),\n", "\t\t\ttype: 'number',\n", "\t\t\tdefault: 1000\n", "\t\t},\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t'terminal.integrated.cursorBarWidth': {\n", "\t\t\tdescription: nls.localize('terminal.integrated.cursorBarWidth', \"Controls the width of terminal bar cursor.\"),\n", "\t\t\ttype: 'number',\n", "\t\t\tdefault: 1\n", "\t\t},\n" ], "file_path": "src/vs/workbench/contrib/terminal/browser/terminal.contribution.ts", "type": "add", "edit_start_line_idx": 208 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as assert from 'assert'; import { Disposable } from 'vs/base/common/lifecycle'; import { ITextAreaWrapper, PagedScreenReaderStrategy, TextAreaState } from 'vs/editor/browser/controller/textAreaState'; import { Position } from 'vs/editor/common/core/position'; import { Selection } from 'vs/editor/common/core/selection'; import { TextModel } from 'vs/editor/common/model/textModel'; export class MockTextAreaWrapper extends Disposable implements ITextAreaWrapper { public _value: string; public _selectionStart: number; public _selectionEnd: number; constructor() { super(); this._value = ''; this._selectionStart = 0; this._selectionEnd = 0; } public getValue(): string { return this._value; } public setValue(reason: string, value: string): void { this._value = value; this._selectionStart = this._value.length; this._selectionEnd = this._value.length; } public getSelectionStart(): number { return this._selectionStart; } public getSelectionEnd(): number { return this._selectionEnd; } public setSelectionRange(reason: string, selectionStart: number, selectionEnd: number): void { if (selectionStart < 0) { selectionStart = 0; } if (selectionStart > this._value.length) { selectionStart = this._value.length; } if (selectionEnd < 0) { selectionEnd = 0; } if (selectionEnd > this._value.length) { selectionEnd = this._value.length; } this._selectionStart = selectionStart; this._selectionEnd = selectionEnd; } } function equalsTextAreaState(a: TextAreaState, b: TextAreaState): boolean { return ( a.value === b.value && a.selectionStart === b.selectionStart && a.selectionEnd === b.selectionEnd && Position.equals(a.selectionStartPosition, b.selectionStartPosition) && Position.equals(a.selectionEndPosition, b.selectionEndPosition) ); } suite('TextAreaState', () => { function assertTextAreaState(actual: TextAreaState, value: string, selectionStart: number, selectionEnd: number): void { let desired = new TextAreaState(value, selectionStart, selectionEnd, null, null); assert.ok(equalsTextAreaState(desired, actual), desired.toString() + ' == ' + actual.toString()); } test('fromTextArea', () => { let textArea = new MockTextAreaWrapper(); textArea._value = 'Hello world!'; textArea._selectionStart = 1; textArea._selectionEnd = 12; let actual = TextAreaState.readFromTextArea(textArea); assertTextAreaState(actual, 'Hello world!', 1, 12); assert.equal(actual.value, 'Hello world!'); assert.equal(actual.selectionStart, 1); actual = actual.collapseSelection(); assertTextAreaState(actual, 'Hello world!', 12, 12); textArea.dispose(); }); test('applyToTextArea', () => { let textArea = new MockTextAreaWrapper(); textArea._value = 'Hello world!'; textArea._selectionStart = 1; textArea._selectionEnd = 12; let state = new TextAreaState('Hi world!', 2, 2, null, null); state.writeToTextArea('test', textArea, false); assert.equal(textArea._value, 'Hi world!'); assert.equal(textArea._selectionStart, 9); assert.equal(textArea._selectionEnd, 9); state = new TextAreaState('Hi world!', 3, 3, null, null); state.writeToTextArea('test', textArea, false); assert.equal(textArea._value, 'Hi world!'); assert.equal(textArea._selectionStart, 9); assert.equal(textArea._selectionEnd, 9); state = new TextAreaState('Hi world!', 0, 2, null, null); state.writeToTextArea('test', textArea, true); assert.equal(textArea._value, 'Hi world!'); assert.equal(textArea._selectionStart, 0); assert.equal(textArea._selectionEnd, 2); textArea.dispose(); }); function testDeduceInput(prevState: TextAreaState | null, value: string, selectionStart: number, selectionEnd: number, couldBeEmojiInput: boolean, couldBeTypingAtOffset0: boolean, expected: string, expectedCharReplaceCnt: number): void { prevState = prevState || TextAreaState.EMPTY; let textArea = new MockTextAreaWrapper(); textArea._value = value; textArea._selectionStart = selectionStart; textArea._selectionEnd = selectionEnd; let newState = TextAreaState.readFromTextArea(textArea); let actual = TextAreaState.deduceInput(prevState, newState, couldBeEmojiInput, couldBeTypingAtOffset0); assert.equal(actual.text, expected); assert.equal(actual.replaceCharCnt, expectedCharReplaceCnt); textArea.dispose(); } test('deduceInput - Japanese typing sennsei and accepting', () => { // manual test: // - choose keyboard layout: Japanese -> Hiragama // - type sennsei // - accept with Enter // - expected: せんせい // s // PREVIOUS STATE: [ <>, selectionStart: 0, selectionEnd: 0, selectionToken: 0] // CURRENT STATE: [ <s>, selectionStart: 0, selectionEnd: 1, selectionToken: 0] testDeduceInput( TextAreaState.EMPTY, 's', 0, 1, true, false, 's', 0 ); // e // PREVIOUS STATE: [ <s>, selectionStart: 0, selectionEnd: 1, selectionToken: 0] // CURRENT STATE: [ <せ>, selectionStart: 0, selectionEnd: 1, selectionToken: 0] testDeduceInput( new TextAreaState('s', 0, 1, null, null), 'せ', 0, 1, true, false, 'せ', 1 ); // n // PREVIOUS STATE: [ <せ>, selectionStart: 0, selectionEnd: 1, selectionToken: 0] // CURRENT STATE: [ <せn>, selectionStart: 0, selectionEnd: 2, selectionToken: 0] testDeduceInput( new TextAreaState('せ', 0, 1, null, null), 'せn', 0, 2, true, false, 'せn', 1 ); // n // PREVIOUS STATE: [ <せn>, selectionStart: 0, selectionEnd: 2, selectionToken: 0] // CURRENT STATE: [ <せん>, selectionStart: 0, selectionEnd: 2, selectionToken: 0] testDeduceInput( new TextAreaState('せn', 0, 2, null, null), 'せん', 0, 2, true, false, 'せん', 2 ); // s // PREVIOUS STATE: [ <せん>, selectionStart: 0, selectionEnd: 2, selectionToken: 0] // CURRENT STATE: [ <せんs>, selectionStart: 0, selectionEnd: 3, selectionToken: 0] testDeduceInput( new TextAreaState('せん', 0, 2, null, null), 'せんs', 0, 3, true, false, 'せんs', 2 ); // e // PREVIOUS STATE: [ <せんs>, selectionStart: 0, selectionEnd: 3, selectionToken: 0] // CURRENT STATE: [ <せんせ>, selectionStart: 0, selectionEnd: 3, selectionToken: 0] testDeduceInput( new TextAreaState('せんs', 0, 3, null, null), 'せんせ', 0, 3, true, false, 'せんせ', 3 ); // no-op? [was recorded] // PREVIOUS STATE: [ <せんせ>, selectionStart: 0, selectionEnd: 3, selectionToken: 0] // CURRENT STATE: [ <せんせ>, selectionStart: 0, selectionEnd: 3, selectionToken: 0] testDeduceInput( new TextAreaState('せんせ', 0, 3, null, null), 'せんせ', 0, 3, true, false, 'せんせ', 3 ); // i // PREVIOUS STATE: [ <せんせ>, selectionStart: 0, selectionEnd: 3, selectionToken: 0] // CURRENT STATE: [ <せんせい>, selectionStart: 0, selectionEnd: 4, selectionToken: 0] testDeduceInput( new TextAreaState('せんせ', 0, 3, null, null), 'せんせい', 0, 4, true, false, 'せんせい', 3 ); // ENTER (accept) // PREVIOUS STATE: [ <せんせい>, selectionStart: 0, selectionEnd: 4, selectionToken: 0] // CURRENT STATE: [ <せんせい>, selectionStart: 4, selectionEnd: 4, selectionToken: 0] testDeduceInput( new TextAreaState('せんせい', 0, 4, null, null), 'せんせい', 4, 4, true, false, '', 0 ); }); test('deduceInput - Japanese typing sennsei and choosing different suggestion', () => { // manual test: // - choose keyboard layout: Japanese -> Hiragama // - type sennsei // - arrow down (choose next suggestion) // - accept with Enter // - expected: せんせい // sennsei // PREVIOUS STATE: [ <せんせい>, selectionStart: 0, selectionEnd: 4, selectionToken: 0] // CURRENT STATE: [ <せんせい>, selectionStart: 0, selectionEnd: 4, selectionToken: 0] testDeduceInput( new TextAreaState('せんせい', 0, 4, null, null), 'せんせい', 0, 4, true, false, 'せんせい', 4 ); // arrow down // CURRENT STATE: [ <先生>, selectionStart: 0, selectionEnd: 2, selectionToken: 0] // PREVIOUS STATE: [ <せんせい>, selectionStart: 0, selectionEnd: 4, selectionToken: 0] testDeduceInput( new TextAreaState('せんせい', 0, 4, null, null), '先生', 0, 2, true, false, '先生', 4 ); // ENTER (accept) // PREVIOUS STATE: [ <先生>, selectionStart: 0, selectionEnd: 2, selectionToken: 0] // CURRENT STATE: [ <先生>, selectionStart: 2, selectionEnd: 2, selectionToken: 0] testDeduceInput( new TextAreaState('先生', 0, 2, null, null), '先生', 2, 2, true, false, '', 0 ); }); test('extractNewText - no previous state with selection', () => { testDeduceInput( null, 'a', 0, 1, true, false, 'a', 0 ); }); test('issue #2586: Replacing selected end-of-line with newline locks up the document', () => { testDeduceInput( new TextAreaState(']\n', 1, 2, null, null), ']\n', 2, 2, true, false, '\n', 0 ); }); test('extractNewText - no previous state without selection', () => { testDeduceInput( null, 'a', 1, 1, true, false, 'a', 0 ); }); test('extractNewText - typing does not cause a selection', () => { testDeduceInput( TextAreaState.EMPTY, 'a', 0, 1, true, false, 'a', 0 ); }); test('extractNewText - had the textarea empty', () => { testDeduceInput( TextAreaState.EMPTY, 'a', 1, 1, true, false, 'a', 0 ); }); test('extractNewText - had the entire line selected', () => { testDeduceInput( new TextAreaState('Hello world!', 0, 12, null, null), 'H', 1, 1, true, false, 'H', 0 ); }); test('extractNewText - had previous text 1', () => { testDeduceInput( new TextAreaState('Hello world!', 12, 12, null, null), 'Hello world!a', 13, 13, true, false, 'a', 0 ); }); test('extractNewText - had previous text 2', () => { testDeduceInput( new TextAreaState('Hello world!', 0, 0, null, null), 'aHello world!', 1, 1, true, false, 'a', 0 ); }); test('extractNewText - had previous text 3', () => { testDeduceInput( new TextAreaState('Hello world!', 6, 11, null, null), 'Hello other!', 11, 11, true, false, 'other', 0 ); }); test('extractNewText - IME', () => { testDeduceInput( TextAreaState.EMPTY, 'これは', 3, 3, true, false, 'これは', 0 ); }); test('extractNewText - isInOverwriteMode', () => { testDeduceInput( new TextAreaState('Hello world!', 0, 0, null, null), 'Aello world!', 1, 1, true, false, 'A', 0 ); }); test('extractMacReplacedText - does nothing if there is selection', () => { testDeduceInput( new TextAreaState('Hello world!', 5, 5, null, null), 'Hellö world!', 4, 5, true, false, 'ö', 0 ); }); test('extractMacReplacedText - does nothing if there is more than one extra char', () => { testDeduceInput( new TextAreaState('Hello world!', 5, 5, null, null), 'Hellöö world!', 5, 5, true, false, 'öö', 1 ); }); test('extractMacReplacedText - does nothing if there is more than one changed char', () => { testDeduceInput( new TextAreaState('Hello world!', 5, 5, null, null), 'Helöö world!', 5, 5, true, false, 'öö', 2 ); }); test('extractMacReplacedText', () => { testDeduceInput( new TextAreaState('Hello world!', 5, 5, null, null), 'Hellö world!', 5, 5, true, false, 'ö', 1 ); }); test('issue #25101 - First key press ignored', () => { testDeduceInput( new TextAreaState('a', 0, 1, null, null), 'a', 1, 1, true, false, 'a', 0 ); }); test('issue #16520 - Cmd-d of single character followed by typing same character as has no effect', () => { testDeduceInput( new TextAreaState('x x', 0, 1, null, null), 'x x', 1, 1, true, false, 'x', 0 ); }); test('issue #4271 (example 1) - When inserting an emoji on OSX, it is placed two spaces left of the cursor', () => { // The OSX emoji inserter inserts emojis at random positions in the text, unrelated to where the cursor is. testDeduceInput( new TextAreaState( [ 'some1 text', 'some2 text', 'some3 text', 'some4 text', // cursor is here in the middle of the two spaces 'some5 text', 'some6 text', 'some7 text' ].join('\n'), 42, 42, null, null ), [ 'so📅me1 text', 'some2 text', 'some3 text', 'some4 text', 'some5 text', 'some6 text', 'some7 text' ].join('\n'), 4, 4, true, false, '📅', 0 ); }); test('issue #4271 (example 2) - When inserting an emoji on OSX, it is placed two spaces left of the cursor', () => { // The OSX emoji inserter inserts emojis at random positions in the text, unrelated to where the cursor is. testDeduceInput( new TextAreaState( 'some1 text', 6, 6, null, null ), 'some💊1 text', 6, 6, true, false, '💊', 0 ); }); test('issue #4271 (example 3) - When inserting an emoji on OSX, it is placed two spaces left of the cursor', () => { // The OSX emoji inserter inserts emojis at random positions in the text, unrelated to where the cursor is. testDeduceInput( new TextAreaState( 'qwertyu\nasdfghj\nzxcvbnm', 12, 12, null, null ), 'qwertyu\nasdfghj\nzxcvbnm🎈', 25, 25, true, false, '🎈', 0 ); }); // an example of an emoji missed by the regex but which has the FE0F variant 16 hint test('issue #4271 (example 4) - When inserting an emoji on OSX, it is placed two spaces left of the cursor', () => { // The OSX emoji inserter inserts emojis at random positions in the text, unrelated to where the cursor is. testDeduceInput( new TextAreaState( 'some1 text', 6, 6, null, null ), 'some⌨️1 text', 6, 6, true, false, '⌨️', 0 ); }); test('issue #42251: Minor issue, character swapped when typing', () => { // Typing on OSX occurs at offset 0 after moving the window using the custom (non-native) titlebar. testDeduceInput( new TextAreaState( 'ab', 2, 2, null, null ), 'cab', 1, 1, true, true, 'c', 0 ); }); test('issue #49480: Double curly braces inserted', () => { // Characters get doubled testDeduceInput( new TextAreaState( 'aa', 2, 2, null, null ), 'aaa', 3, 3, true, true, 'a', 0 ); }); suite('PagedScreenReaderStrategy', () => { function testPagedScreenReaderStrategy(lines: string[], selection: Selection, expected: TextAreaState): void { const model = TextModel.createFromString(lines.join('\n')); const actual = PagedScreenReaderStrategy.fromEditorSelection(TextAreaState.EMPTY, model, selection, 10, true); assert.ok(equalsTextAreaState(actual, expected)); model.dispose(); } test('simple', () => { testPagedScreenReaderStrategy( [ 'Hello world!' ], new Selection(1, 13, 1, 13), new TextAreaState('Hello world!', 12, 12, new Position(1, 13), new Position(1, 13)) ); testPagedScreenReaderStrategy( [ 'Hello world!' ], new Selection(1, 1, 1, 1), new TextAreaState('Hello world!', 0, 0, new Position(1, 1), new Position(1, 1)) ); testPagedScreenReaderStrategy( [ 'Hello world!' ], new Selection(1, 1, 1, 6), new TextAreaState('Hello world!', 0, 5, new Position(1, 1), new Position(1, 6)) ); }); test('multiline', () => { testPagedScreenReaderStrategy( [ 'Hello world!', 'How are you?' ], new Selection(1, 1, 1, 1), new TextAreaState('Hello world!\nHow are you?', 0, 0, new Position(1, 1), new Position(1, 1)) ); testPagedScreenReaderStrategy( [ 'Hello world!', 'How are you?' ], new Selection(2, 1, 2, 1), new TextAreaState('Hello world!\nHow are you?', 13, 13, new Position(2, 1), new Position(2, 1)) ); }); test('page', () => { testPagedScreenReaderStrategy( [ 'L1\nL2\nL3\nL4\nL5\nL6\nL7\nL8\nL9\nL10\nL11\nL12\nL13\nL14\nL15\nL16\nL17\nL18\nL19\nL20\nL21' ], new Selection(1, 1, 1, 1), new TextAreaState('L1\nL2\nL3\nL4\nL5\nL6\nL7\nL8\nL9\nL10\n', 0, 0, new Position(1, 1), new Position(1, 1)) ); testPagedScreenReaderStrategy( [ 'L1\nL2\nL3\nL4\nL5\nL6\nL7\nL8\nL9\nL10\nL11\nL12\nL13\nL14\nL15\nL16\nL17\nL18\nL19\nL20\nL21' ], new Selection(11, 1, 11, 1), new TextAreaState('L11\nL12\nL13\nL14\nL15\nL16\nL17\nL18\nL19\nL20\n', 0, 0, new Position(11, 1), new Position(11, 1)) ); testPagedScreenReaderStrategy( [ 'L1\nL2\nL3\nL4\nL5\nL6\nL7\nL8\nL9\nL10\nL11\nL12\nL13\nL14\nL15\nL16\nL17\nL18\nL19\nL20\nL21' ], new Selection(12, 1, 12, 1), new TextAreaState('L11\nL12\nL13\nL14\nL15\nL16\nL17\nL18\nL19\nL20\n', 4, 4, new Position(12, 1), new Position(12, 1)) ); testPagedScreenReaderStrategy( [ 'L1\nL2\nL3\nL4\nL5\nL6\nL7\nL8\nL9\nL10\nL11\nL12\nL13\nL14\nL15\nL16\nL17\nL18\nL19\nL20\nL21' ], new Selection(21, 1, 21, 1), new TextAreaState('L21', 0, 0, new Position(21, 1), new Position(21, 1)) ); }); }); });
src/vs/editor/test/browser/controller/textAreaState.test.ts
0
https://github.com/microsoft/vscode/commit/afc57a083c0c4e20ae87cf52b97820f1b43acfc5
[ 0.0001760343584464863, 0.00017163006123155355, 0.00016611986211501062, 0.00017193164967466146, 0.0000025846795779216336 ]
{ "id": 0, "code_window": [ "\t\t\tenum: [TerminalCursorStyle.BLOCK, TerminalCursorStyle.LINE, TerminalCursorStyle.UNDERLINE],\n", "\t\t\tdefault: TerminalCursorStyle.BLOCK\n", "\t\t},\n", "\t\t'terminal.integrated.scrollback': {\n", "\t\t\tdescription: nls.localize('terminal.integrated.scrollback', \"Controls the maximum amount of lines the terminal keeps in its buffer.\"),\n", "\t\t\ttype: 'number',\n", "\t\t\tdefault: 1000\n", "\t\t},\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t'terminal.integrated.cursorBarWidth': {\n", "\t\t\tdescription: nls.localize('terminal.integrated.cursorBarWidth', \"Controls the width of terminal bar cursor.\"),\n", "\t\t\ttype: 'number',\n", "\t\t\tdefault: 1\n", "\t\t},\n" ], "file_path": "src/vs/workbench/contrib/terminal/browser/terminal.contribution.ts", "type": "add", "edit_start_line_idx": 208 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { SQLiteStorageDatabase, ISQLiteStorageDatabaseOptions } from 'vs/base/parts/storage/node/storage'; import { Storage, IStorageDatabase, IStorageItemsChangeEvent } from 'vs/base/parts/storage/common/storage'; import { generateUuid } from 'vs/base/common/uuid'; import { join } from 'vs/base/common/path'; import { tmpdir } from 'os'; import { equal, ok } from 'assert'; import { mkdirp, writeFile, exists, unlink, rimraf, RimRafMode } from 'vs/base/node/pfs'; import { timeout } from 'vs/base/common/async'; import { Event, Emitter } from 'vs/base/common/event'; import { isWindows } from 'vs/base/common/platform'; suite('Storage Library', () => { function uniqueStorageDir(): string { const id = generateUuid(); return join(tmpdir(), 'vsctests', id, 'storage2', id); } test('basics', async () => { const storageDir = uniqueStorageDir(); await mkdirp(storageDir); const storage = new Storage(new SQLiteStorageDatabase(join(storageDir, 'storage.db'))); await storage.init(); // Empty fallbacks equal(storage.get('foo', 'bar'), 'bar'); equal(storage.getNumber('foo', 55), 55); equal(storage.getBoolean('foo', true), true); let changes = new Set<string>(); storage.onDidChangeStorage(key => { changes.add(key); }); // Simple updates const set1Promise = storage.set('bar', 'foo'); const set2Promise = storage.set('barNumber', 55); const set3Promise = storage.set('barBoolean', true); equal(storage.get('bar'), 'foo'); equal(storage.getNumber('barNumber'), 55); equal(storage.getBoolean('barBoolean'), true); equal(changes.size, 3); ok(changes.has('bar')); ok(changes.has('barNumber')); ok(changes.has('barBoolean')); let setPromiseResolved = false; await Promise.all([set1Promise, set2Promise, set3Promise]).then(() => setPromiseResolved = true); equal(setPromiseResolved, true); changes = new Set<string>(); // Does not trigger events for same update values storage.set('bar', 'foo'); storage.set('barNumber', 55); storage.set('barBoolean', true); equal(changes.size, 0); // Simple deletes const delete1Promise = storage.delete('bar'); const delete2Promise = storage.delete('barNumber'); const delete3Promise = storage.delete('barBoolean'); ok(!storage.get('bar')); ok(!storage.getNumber('barNumber')); ok(!storage.getBoolean('barBoolean')); equal(changes.size, 3); ok(changes.has('bar')); ok(changes.has('barNumber')); ok(changes.has('barBoolean')); changes = new Set<string>(); // Does not trigger events for same delete values storage.delete('bar'); storage.delete('barNumber'); storage.delete('barBoolean'); equal(changes.size, 0); let deletePromiseResolved = false; await Promise.all([delete1Promise, delete2Promise, delete3Promise]).then(() => deletePromiseResolved = true); equal(deletePromiseResolved, true); await storage.close(); await rimraf(storageDir, RimRafMode.MOVE); }); test('external changes', async () => { const storageDir = uniqueStorageDir(); await mkdirp(storageDir); class TestSQLiteStorageDatabase extends SQLiteStorageDatabase { private readonly _onDidChangeItemsExternal = new Emitter<IStorageItemsChangeEvent>(); get onDidChangeItemsExternal(): Event<IStorageItemsChangeEvent> { return this._onDidChangeItemsExternal.event; } fireDidChangeItemsExternal(event: IStorageItemsChangeEvent): void { this._onDidChangeItemsExternal.fire(event); } } const database = new TestSQLiteStorageDatabase(join(storageDir, 'storage.db')); const storage = new Storage(database); let changes = new Set<string>(); storage.onDidChangeStorage(key => { changes.add(key); }); await storage.init(); await storage.set('foo', 'bar'); ok(changes.has('foo')); changes.clear(); // Nothing happens if changing to same value const change = new Map<string, string>(); change.set('foo', 'bar'); database.fireDidChangeItemsExternal({ items: change }); equal(changes.size, 0); // Change is accepted if valid change.set('foo', 'bar1'); database.fireDidChangeItemsExternal({ items: change }); ok(changes.has('foo')); equal(storage.get('foo'), 'bar1'); changes.clear(); // Delete is accepted change.set('foo', undefined); database.fireDidChangeItemsExternal({ items: change }); ok(changes.has('foo')); equal(storage.get('foo', null!), null); changes.clear(); // Nothing happens if changing to same value change.set('foo', undefined); database.fireDidChangeItemsExternal({ items: change }); equal(changes.size, 0); await storage.close(); await rimraf(storageDir, RimRafMode.MOVE); }); test('close flushes data', async () => { const storageDir = uniqueStorageDir(); await mkdirp(storageDir); let storage = new Storage(new SQLiteStorageDatabase(join(storageDir, 'storage.db'))); await storage.init(); const set1Promise = storage.set('foo', 'bar'); const set2Promise = storage.set('bar', 'foo'); equal(storage.get('foo'), 'bar'); equal(storage.get('bar'), 'foo'); let setPromiseResolved = false; Promise.all([set1Promise, set2Promise]).then(() => setPromiseResolved = true); await storage.close(); equal(setPromiseResolved, true); storage = new Storage(new SQLiteStorageDatabase(join(storageDir, 'storage.db'))); await storage.init(); equal(storage.get('foo'), 'bar'); equal(storage.get('bar'), 'foo'); await storage.close(); storage = new Storage(new SQLiteStorageDatabase(join(storageDir, 'storage.db'))); await storage.init(); const delete1Promise = storage.delete('foo'); const delete2Promise = storage.delete('bar'); ok(!storage.get('foo')); ok(!storage.get('bar')); let deletePromiseResolved = false; Promise.all([delete1Promise, delete2Promise]).then(() => deletePromiseResolved = true); await storage.close(); equal(deletePromiseResolved, true); storage = new Storage(new SQLiteStorageDatabase(join(storageDir, 'storage.db'))); await storage.init(); ok(!storage.get('foo')); ok(!storage.get('bar')); await storage.close(); await rimraf(storageDir, RimRafMode.MOVE); }); test('conflicting updates', async () => { const storageDir = uniqueStorageDir(); await mkdirp(storageDir); let storage = new Storage(new SQLiteStorageDatabase(join(storageDir, 'storage.db'))); await storage.init(); let changes = new Set<string>(); storage.onDidChangeStorage(key => { changes.add(key); }); const set1Promise = storage.set('foo', 'bar1'); const set2Promise = storage.set('foo', 'bar2'); const set3Promise = storage.set('foo', 'bar3'); equal(storage.get('foo'), 'bar3'); equal(changes.size, 1); ok(changes.has('foo')); let setPromiseResolved = false; await Promise.all([set1Promise, set2Promise, set3Promise]).then(() => setPromiseResolved = true); ok(setPromiseResolved); changes = new Set<string>(); const set4Promise = storage.set('bar', 'foo'); const delete1Promise = storage.delete('bar'); ok(!storage.get('bar')); equal(changes.size, 1); ok(changes.has('bar')); let setAndDeletePromiseResolved = false; await Promise.all([set4Promise, delete1Promise]).then(() => setAndDeletePromiseResolved = true); ok(setAndDeletePromiseResolved); await storage.close(); await rimraf(storageDir, RimRafMode.MOVE); }); test('corrupt DB recovers', async () => { const storageDir = uniqueStorageDir(); await mkdirp(storageDir); const storageFile = join(storageDir, 'storage.db'); let storage = new Storage(new SQLiteStorageDatabase(storageFile)); await storage.init(); await storage.set('bar', 'foo'); await writeFile(storageFile, 'This is a broken DB'); await storage.set('foo', 'bar'); equal(storage.get('bar'), 'foo'); equal(storage.get('foo'), 'bar'); await storage.close(); storage = new Storage(new SQLiteStorageDatabase(storageFile)); await storage.init(); equal(storage.get('bar'), 'foo'); equal(storage.get('foo'), 'bar'); await storage.close(); await rimraf(storageDir, RimRafMode.MOVE); }); }); suite('SQLite Storage Library', () => { function uniqueStorageDir(): string { const id = generateUuid(); return join(tmpdir(), 'vsctests', id, 'storage', id); } function toSet(elements: string[]): Set<string> { const set = new Set<string>(); elements.forEach(element => set.add(element)); return set; } async function testDBBasics(path: string, logError?: (error: Error | string) => void) { let options!: ISQLiteStorageDatabaseOptions; if (logError) { options = { logging: { logError } }; } const storage = new SQLiteStorageDatabase(path, options); const items = new Map<string, string>(); items.set('foo', 'bar'); items.set('some/foo/path', 'some/bar/path'); items.set(JSON.stringify({ foo: 'bar' }), JSON.stringify({ bar: 'foo' })); let storedItems = await storage.getItems(); equal(storedItems.size, 0); await storage.updateItems({ insert: items }); storedItems = await storage.getItems(); equal(storedItems.size, items.size); equal(storedItems.get('foo'), 'bar'); equal(storedItems.get('some/foo/path'), 'some/bar/path'); equal(storedItems.get(JSON.stringify({ foo: 'bar' })), JSON.stringify({ bar: 'foo' })); await storage.updateItems({ delete: toSet(['foo']) }); storedItems = await storage.getItems(); equal(storedItems.size, items.size - 1); ok(!storedItems.has('foo')); equal(storedItems.get('some/foo/path'), 'some/bar/path'); equal(storedItems.get(JSON.stringify({ foo: 'bar' })), JSON.stringify({ bar: 'foo' })); await storage.updateItems({ insert: items }); storedItems = await storage.getItems(); equal(storedItems.size, items.size); equal(storedItems.get('foo'), 'bar'); equal(storedItems.get('some/foo/path'), 'some/bar/path'); equal(storedItems.get(JSON.stringify({ foo: 'bar' })), JSON.stringify({ bar: 'foo' })); const itemsChange = new Map<string, string>(); itemsChange.set('foo', 'otherbar'); await storage.updateItems({ insert: itemsChange }); storedItems = await storage.getItems(); equal(storedItems.get('foo'), 'otherbar'); await storage.updateItems({ delete: toSet(['foo', 'bar', 'some/foo/path', JSON.stringify({ foo: 'bar' })]) }); storedItems = await storage.getItems(); equal(storedItems.size, 0); await storage.updateItems({ insert: items, delete: toSet(['foo', 'some/foo/path', 'other']) }); storedItems = await storage.getItems(); equal(storedItems.size, 1); equal(storedItems.get(JSON.stringify({ foo: 'bar' })), JSON.stringify({ bar: 'foo' })); await storage.updateItems({ delete: toSet([JSON.stringify({ foo: 'bar' })]) }); storedItems = await storage.getItems(); equal(storedItems.size, 0); let recoveryCalled = false; await storage.close(() => { recoveryCalled = true; return new Map(); }); equal(recoveryCalled, false); } test('basics', async () => { const storageDir = uniqueStorageDir(); await mkdirp(storageDir); await testDBBasics(join(storageDir, 'storage.db')); await rimraf(storageDir, RimRafMode.MOVE); }); test('basics (open multiple times)', async () => { const storageDir = uniqueStorageDir(); await mkdirp(storageDir); await testDBBasics(join(storageDir, 'storage.db')); await testDBBasics(join(storageDir, 'storage.db')); await rimraf(storageDir, RimRafMode.MOVE); }); test('basics (corrupt DB falls back to empty DB)', async () => { const storageDir = uniqueStorageDir(); await mkdirp(storageDir); const corruptDBPath = join(storageDir, 'broken.db'); await writeFile(corruptDBPath, 'This is a broken DB'); let expectedError: any; await testDBBasics(corruptDBPath, error => { expectedError = error; }); ok(expectedError); await rimraf(storageDir, RimRafMode.MOVE); }); test('basics (corrupt DB restores from previous backup)', async () => { const storageDir = uniqueStorageDir(); await mkdirp(storageDir); const storagePath = join(storageDir, 'storage.db'); let storage = new SQLiteStorageDatabase(storagePath); const items = new Map<string, string>(); items.set('foo', 'bar'); items.set('some/foo/path', 'some/bar/path'); items.set(JSON.stringify({ foo: 'bar' }), JSON.stringify({ bar: 'foo' })); await storage.updateItems({ insert: items }); await storage.close(); await writeFile(storagePath, 'This is now a broken DB'); storage = new SQLiteStorageDatabase(storagePath); const storedItems = await storage.getItems(); equal(storedItems.size, items.size); equal(storedItems.get('foo'), 'bar'); equal(storedItems.get('some/foo/path'), 'some/bar/path'); equal(storedItems.get(JSON.stringify({ foo: 'bar' })), JSON.stringify({ bar: 'foo' })); let recoveryCalled = false; await storage.close(() => { recoveryCalled = true; return new Map(); }); equal(recoveryCalled, false); await rimraf(storageDir, RimRafMode.MOVE); }); test('basics (corrupt DB falls back to empty DB if backup is corrupt)', async () => { const storageDir = uniqueStorageDir(); await mkdirp(storageDir); const storagePath = join(storageDir, 'storage.db'); let storage = new SQLiteStorageDatabase(storagePath); const items = new Map<string, string>(); items.set('foo', 'bar'); items.set('some/foo/path', 'some/bar/path'); items.set(JSON.stringify({ foo: 'bar' }), JSON.stringify({ bar: 'foo' })); await storage.updateItems({ insert: items }); await storage.close(); await writeFile(storagePath, 'This is now a broken DB'); await writeFile(`${storagePath}.backup`, 'This is now also a broken DB'); storage = new SQLiteStorageDatabase(storagePath); const storedItems = await storage.getItems(); equal(storedItems.size, 0); await testDBBasics(storagePath); await rimraf(storageDir, RimRafMode.MOVE); }); test('basics (DB that becomes corrupt during runtime stores all state from cache on close)', async () => { if (isWindows) { await Promise.resolve(); // Windows will fail to write to open DB due to locking return; } const storageDir = uniqueStorageDir(); await mkdirp(storageDir); const storagePath = join(storageDir, 'storage.db'); let storage = new SQLiteStorageDatabase(storagePath); const items = new Map<string, string>(); items.set('foo', 'bar'); items.set('some/foo/path', 'some/bar/path'); items.set(JSON.stringify({ foo: 'bar' }), JSON.stringify({ bar: 'foo' })); await storage.updateItems({ insert: items }); await storage.close(); const backupPath = `${storagePath}.backup`; equal(await exists(backupPath), true); storage = new SQLiteStorageDatabase(storagePath); await storage.getItems(); await writeFile(storagePath, 'This is now a broken DB'); // we still need to trigger a check to the DB so that we get to know that // the DB is corrupt. We have no extra code on shutdown that checks for the // health of the DB. This is an optimization to not perform too many tasks // on shutdown. await storage.checkIntegrity(true).then(null, error => { } /* error is expected here but we do not want to fail */); await unlink(backupPath); // also test that the recovery DB is backed up properly let recoveryCalled = false; await storage.close(() => { recoveryCalled = true; return items; }); equal(recoveryCalled, true); equal(await exists(backupPath), true); storage = new SQLiteStorageDatabase(storagePath); const storedItems = await storage.getItems(); equal(storedItems.size, items.size); equal(storedItems.get('foo'), 'bar'); equal(storedItems.get('some/foo/path'), 'some/bar/path'); equal(storedItems.get(JSON.stringify({ foo: 'bar' })), JSON.stringify({ bar: 'foo' })); recoveryCalled = false; await storage.close(() => { recoveryCalled = true; return new Map(); }); equal(recoveryCalled, false); await rimraf(storageDir, RimRafMode.MOVE); }); test('real world example', async function () { this.timeout(20000); const storageDir = uniqueStorageDir(); await mkdirp(storageDir); let storage = new SQLiteStorageDatabase(join(storageDir, 'storage.db')); const items1 = new Map<string, string>(); items1.set('colorthemedata', '{"id":"vs vscode-theme-defaults-themes-light_plus-json","label":"Light+ (default light)","settingsId":"Default Light+","selector":"vs.vscode-theme-defaults-themes-light_plus-json","themeTokenColors":[{"settings":{"foreground":"#000000ff","background":"#ffffffff"}},{"scope":["meta.embedded","source.groovy.embedded"],"settings":{"foreground":"#000000ff"}},{"scope":"emphasis","settings":{"fontStyle":"italic"}},{"scope":"strong","settings":{"fontStyle":"bold"}},{"scope":"meta.diff.header","settings":{"foreground":"#000080"}},{"scope":"comment","settings":{"foreground":"#008000"}},{"scope":"constant.language","settings":{"foreground":"#0000ff"}},{"scope":["constant.numeric"],"settings":{"foreground":"#09885a"}},{"scope":"constant.regexp","settings":{"foreground":"#811f3f"}},{"name":"css tags in selectors, xml tags","scope":"entity.name.tag","settings":{"foreground":"#800000"}},{"scope":"entity.name.selector","settings":{"foreground":"#800000"}},{"scope":"entity.other.attribute-name","settings":{"foreground":"#ff0000"}},{"scope":["entity.other.attribute-name.class.css","entity.other.attribute-name.class.mixin.css","entity.other.attribute-name.id.css","entity.other.attribute-name.parent-selector.css","entity.other.attribute-name.pseudo-class.css","entity.other.attribute-name.pseudo-element.css","source.css.less entity.other.attribute-name.id","entity.other.attribute-name.attribute.scss","entity.other.attribute-name.scss"],"settings":{"foreground":"#800000"}},{"scope":"invalid","settings":{"foreground":"#cd3131"}},{"scope":"markup.underline","settings":{"fontStyle":"underline"}},{"scope":"markup.bold","settings":{"fontStyle":"bold","foreground":"#000080"}},{"scope":"markup.heading","settings":{"fontStyle":"bold","foreground":"#800000"}},{"scope":"markup.italic","settings":{"fontStyle":"italic"}},{"scope":"markup.inserted","settings":{"foreground":"#09885a"}},{"scope":"markup.deleted","settings":{"foreground":"#a31515"}},{"scope":"markup.changed","settings":{"foreground":"#0451a5"}},{"scope":["punctuation.definition.quote.begin.markdown","punctuation.definition.list.begin.markdown"],"settings":{"foreground":"#0451a5"}},{"scope":"markup.inline.raw","settings":{"foreground":"#800000"}},{"name":"brackets of XML/HTML tags","scope":"punctuation.definition.tag","settings":{"foreground":"#800000"}},{"scope":"meta.preprocessor","settings":{"foreground":"#0000ff"}},{"scope":"meta.preprocessor.string","settings":{"foreground":"#a31515"}},{"scope":"meta.preprocessor.numeric","settings":{"foreground":"#09885a"}},{"scope":"meta.structure.dictionary.key.python","settings":{"foreground":"#0451a5"}},{"scope":"storage","settings":{"foreground":"#0000ff"}},{"scope":"storage.type","settings":{"foreground":"#0000ff"}},{"scope":"storage.modifier","settings":{"foreground":"#0000ff"}},{"scope":"string","settings":{"foreground":"#a31515"}},{"scope":["string.comment.buffered.block.pug","string.quoted.pug","string.interpolated.pug","string.unquoted.plain.in.yaml","string.unquoted.plain.out.yaml","string.unquoted.block.yaml","string.quoted.single.yaml","string.quoted.double.xml","string.quoted.single.xml","string.unquoted.cdata.xml","string.quoted.double.html","string.quoted.single.html","string.unquoted.html","string.quoted.single.handlebars","string.quoted.double.handlebars"],"settings":{"foreground":"#0000ff"}},{"scope":"string.regexp","settings":{"foreground":"#811f3f"}},{"name":"String interpolation","scope":["punctuation.definition.template-expression.begin","punctuation.definition.template-expression.end","punctuation.section.embedded"],"settings":{"foreground":"#0000ff"}},{"name":"Reset JavaScript string interpolation expression","scope":["meta.template.expression"],"settings":{"foreground":"#000000"}},{"scope":["support.constant.property-value","support.constant.font-name","support.constant.media-type","support.constant.media","constant.other.color.rgb-value","constant.other.rgb-value","support.constant.color"],"settings":{"foreground":"#0451a5"}},{"scope":["support.type.vendored.property-name","support.type.property-name","variable.css","variable.scss","variable.other.less","source.coffee.embedded"],"settings":{"foreground":"#ff0000"}},{"scope":["support.type.property-name.json"],"settings":{"foreground":"#0451a5"}},{"scope":"keyword","settings":{"foreground":"#0000ff"}},{"scope":"keyword.control","settings":{"foreground":"#0000ff"}},{"scope":"keyword.operator","settings":{"foreground":"#000000"}},{"scope":["keyword.operator.new","keyword.operator.expression","keyword.operator.cast","keyword.operator.sizeof","keyword.operator.instanceof","keyword.operator.logical.python"],"settings":{"foreground":"#0000ff"}},{"scope":"keyword.other.unit","settings":{"foreground":"#09885a"}},{"scope":["punctuation.section.embedded.begin.php","punctuation.section.embedded.end.php"],"settings":{"foreground":"#800000"}},{"scope":"support.function.git-rebase","settings":{"foreground":"#0451a5"}},{"scope":"constant.sha.git-rebase","settings":{"foreground":"#09885a"}},{"name":"coloring of the Java import and package identifiers","scope":["storage.modifier.import.java","variable.language.wildcard.java","storage.modifier.package.java"],"settings":{"foreground":"#000000"}},{"name":"this.self","scope":"variable.language","settings":{"foreground":"#0000ff"}},{"name":"Function declarations","scope":["entity.name.function","support.function","support.constant.handlebars"],"settings":{"foreground":"#795E26"}},{"name":"Types declaration and references","scope":["meta.return-type","support.class","support.type","entity.name.type","entity.name.class","storage.type.numeric.go","storage.type.byte.go","storage.type.boolean.go","storage.type.string.go","storage.type.uintptr.go","storage.type.error.go","storage.type.rune.go","storage.type.cs","storage.type.generic.cs","storage.type.modifier.cs","storage.type.variable.cs","storage.type.annotation.java","storage.type.generic.java","storage.type.java","storage.type.object.array.java","storage.type.primitive.array.java","storage.type.primitive.java","storage.type.token.java","storage.type.groovy","storage.type.annotation.groovy","storage.type.parameters.groovy","storage.type.generic.groovy","storage.type.object.array.groovy","storage.type.primitive.array.groovy","storage.type.primitive.groovy"],"settings":{"foreground":"#267f99"}},{"name":"Types declaration and references, TS grammar specific","scope":["meta.type.cast.expr","meta.type.new.expr","support.constant.math","support.constant.dom","support.constant.json","entity.other.inherited-class"],"settings":{"foreground":"#267f99"}},{"name":"Control flow keywords","scope":"keyword.control","settings":{"foreground":"#AF00DB"}},{"name":"Variable and parameter name","scope":["variable","meta.definition.variable.name","support.variable","entity.name.variable"],"settings":{"foreground":"#001080"}},{"name":"Object keys, TS grammar specific","scope":["meta.object-literal.key"],"settings":{"foreground":"#001080"}},{"name":"CSS property value","scope":["support.constant.property-value","support.constant.font-name","support.constant.media-type","support.constant.media","constant.other.color.rgb-value","constant.other.rgb-value","support.constant.color"],"settings":{"foreground":"#0451a5"}},{"name":"Regular expression groups","scope":["punctuation.definition.group.regexp","punctuation.definition.group.assertion.regexp","punctuation.definition.character-class.regexp","punctuation.character.set.begin.regexp","punctuation.character.set.end.regexp","keyword.operator.negation.regexp","support.other.parenthesis.regexp"],"settings":{"foreground":"#d16969"}},{"scope":["constant.character.character-class.regexp","constant.other.character-class.set.regexp","constant.other.character-class.regexp","constant.character.set.regexp"],"settings":{"foreground":"#811f3f"}},{"scope":"keyword.operator.quantifier.regexp","settings":{"foreground":"#000000"}},{"scope":["keyword.operator.or.regexp","keyword.control.anchor.regexp"],"settings":{"foreground":"#ff0000"}},{"scope":"constant.character","settings":{"foreground":"#0000ff"}},{"scope":"constant.character.escape","settings":{"foreground":"#ff0000"}},{"scope":"token.info-token","settings":{"foreground":"#316bcd"}},{"scope":"token.warn-token","settings":{"foreground":"#cd9731"}},{"scope":"token.error-token","settings":{"foreground":"#cd3131"}},{"scope":"token.debug-token","settings":{"foreground":"#800080"}}],"extensionData":{"extensionId":"vscode.theme-defaults","extensionPublisher":"vscode","extensionName":"theme-defaults","extensionIsBuiltin":true},"colorMap":{"editor.background":"#ffffff","editor.foreground":"#000000","editor.inactiveSelectionBackground":"#e5ebf1","editorIndentGuide.background":"#d3d3d3","editorIndentGuide.activeBackground":"#939393","editor.selectionHighlightBackground":"#add6ff4d","editorSuggestWidget.background":"#f3f3f3","activityBarBadge.background":"#007acc","sideBarTitle.foreground":"#6f6f6f","list.hoverBackground":"#e8e8e8","input.placeholderForeground":"#767676","settings.textInputBorder":"#cecece","settings.numberInputBorder":"#cecece"}}'); items1.set('commandpalette.mru.cache', '{"usesLRU":true,"entries":[{"key":"revealFileInOS","value":3},{"key":"extension.openInGitHub","value":4},{"key":"workbench.extensions.action.openExtensionsFolder","value":11},{"key":"workbench.action.showRuntimeExtensions","value":14},{"key":"workbench.action.toggleTabsVisibility","value":15},{"key":"extension.liveServerPreview.open","value":16},{"key":"workbench.action.openIssueReporter","value":18},{"key":"workbench.action.openProcessExplorer","value":19},{"key":"workbench.action.toggleSharedProcess","value":20},{"key":"workbench.action.configureLocale","value":21},{"key":"workbench.action.appPerf","value":22},{"key":"workbench.action.reportPerformanceIssueUsingReporter","value":23},{"key":"workbench.action.openGlobalKeybindings","value":25},{"key":"workbench.action.output.toggleOutput","value":27},{"key":"extension.sayHello","value":29}]}'); items1.set('cpp.1.lastsessiondate', 'Fri Oct 05 2018'); items1.set('debug.actionswidgetposition', '0.6880952380952381'); const items2 = new Map<string, string>(); items2.set('workbench.editors.files.textfileeditor', '{"textEditorViewState":[["file:///Users/dummy/Documents/ticino-playground/play.htm",{"0":{"cursorState":[{"inSelectionMode":false,"selectionStart":{"lineNumber":6,"column":16},"position":{"lineNumber":6,"column":16}}],"viewState":{"scrollLeft":0,"firstPosition":{"lineNumber":1,"column":1},"firstPositionDeltaTop":0},"contributionsState":{"editor.contrib.folding":{},"editor.contrib.wordHighlighter":false}}}],["file:///Users/dummy/Documents/ticino-playground/nakefile.js",{"0":{"cursorState":[{"inSelectionMode":false,"selectionStart":{"lineNumber":7,"column":81},"position":{"lineNumber":7,"column":81}}],"viewState":{"scrollLeft":0,"firstPosition":{"lineNumber":1,"column":1},"firstPositionDeltaTop":20},"contributionsState":{"editor.contrib.folding":{},"editor.contrib.wordHighlighter":false}}}],["file:///Users/dummy/Desktop/vscode2/.gitattributes",{"0":{"cursorState":[{"inSelectionMode":false,"selectionStart":{"lineNumber":9,"column":12},"position":{"lineNumber":9,"column":12}}],"viewState":{"scrollLeft":0,"firstPosition":{"lineNumber":1,"column":1},"firstPositionDeltaTop":20},"contributionsState":{"editor.contrib.folding":{},"editor.contrib.wordHighlighter":false}}}],["file:///Users/dummy/Desktop/vscode2/src/vs/workbench/contrib/search/browser/openAnythingHandler.ts",{"0":{"cursorState":[{"inSelectionMode":false,"selectionStart":{"lineNumber":1,"column":1},"position":{"lineNumber":1,"column":1}}],"viewState":{"scrollLeft":0,"firstPosition":{"lineNumber":1,"column":1},"firstPositionDeltaTop":0},"contributionsState":{"editor.contrib.folding":{},"editor.contrib.wordHighlighter":false}}}]]}'); const items3 = new Map<string, string>(); items3.set('nps/iscandidate', 'false'); items3.set('telemetry.instanceid', 'd52bfcd4-4be6-476b-a38f-d44c717c41d6'); items3.set('workbench.activity.pinnedviewlets', '[{"id":"workbench.view.explorer","pinned":true,"order":0,"visible":true},{"id":"workbench.view.search","pinned":true,"order":1,"visible":true},{"id":"workbench.view.scm","pinned":true,"order":2,"visible":true},{"id":"workbench.view.debug","pinned":true,"order":3,"visible":true},{"id":"workbench.view.extensions","pinned":true,"order":4,"visible":true},{"id":"workbench.view.extension.gitlens","pinned":true,"order":7,"visible":true},{"id":"workbench.view.extension.test","pinned":false,"visible":false}]'); items3.set('workbench.panel.height', '419'); items3.set('very.long.key.very.long.key.very.long.key.very.long.key.very.long.key.very.long.key.very.long.key.very.long.key.very.long.key.very.long.key.very.long.key.very.long.key.very.long.key.very.long.key.very.long.key.very.long.key.very.long.key.very.long.key.very.long.key.very.long.key.very.long.key.very.long.key.very.long.key.very.long.key.very.long.key.very.long.key.very.long.key.very.long.key.very.long.key.very.long.key.very.long.key.very.long.key.very.long.key.very.long.key.very.long.key.', 'is long'); let storedItems = await storage.getItems(); equal(storedItems.size, 0); await Promise.all([ await storage.updateItems({ insert: items1 }), await storage.updateItems({ insert: items2 }), await storage.updateItems({ insert: items3 }) ]); equal(await storage.checkIntegrity(true), 'ok'); equal(await storage.checkIntegrity(false), 'ok'); storedItems = await storage.getItems(); equal(storedItems.size, items1.size + items2.size + items3.size); const items1Keys: string[] = []; items1.forEach((value, key) => { items1Keys.push(key); equal(storedItems.get(key), value); }); const items2Keys: string[] = []; items2.forEach((value, key) => { items2Keys.push(key); equal(storedItems.get(key), value); }); const items3Keys: string[] = []; items3.forEach((value, key) => { items3Keys.push(key); equal(storedItems.get(key), value); }); await Promise.all([ await storage.updateItems({ delete: toSet(items1Keys) }), await storage.updateItems({ delete: toSet(items2Keys) }), await storage.updateItems({ delete: toSet(items3Keys) }) ]); storedItems = await storage.getItems(); equal(storedItems.size, 0); await Promise.all([ await storage.updateItems({ insert: items1 }), await storage.getItems(), await storage.updateItems({ insert: items2 }), await storage.getItems(), await storage.updateItems({ insert: items3 }), await storage.getItems(), ]); storedItems = await storage.getItems(); equal(storedItems.size, items1.size + items2.size + items3.size); await storage.close(); storage = new SQLiteStorageDatabase(join(storageDir, 'storage.db')); storedItems = await storage.getItems(); equal(storedItems.size, items1.size + items2.size + items3.size); await storage.close(); await rimraf(storageDir, RimRafMode.MOVE); }); test('very large item value', async function () { this.timeout(20000); const storageDir = uniqueStorageDir(); await mkdirp(storageDir); let storage = new SQLiteStorageDatabase(join(storageDir, 'storage.db')); const items = new Map<string, string>(); items.set('colorthemedata', '{"id":"vs vscode-theme-defaults-themes-light_plus-json","label":"Light+ (default light)","settingsId":"Default Light+","selector":"vs.vscode-theme-defaults-themes-light_plus-json","themeTokenColors":[{"settings":{"foreground":"#000000ff","background":"#ffffffff"}},{"scope":["meta.embedded","source.groovy.embedded"],"settings":{"foreground":"#000000ff"}},{"scope":"emphasis","settings":{"fontStyle":"italic"}},{"scope":"strong","settings":{"fontStyle":"bold"}},{"scope":"meta.diff.header","settings":{"foreground":"#000080"}},{"scope":"comment","settings":{"foreground":"#008000"}},{"scope":"constant.language","settings":{"foreground":"#0000ff"}},{"scope":["constant.numeric"],"settings":{"foreground":"#09885a"}},{"scope":"constant.regexp","settings":{"foreground":"#811f3f"}},{"name":"css tags in selectors, xml tags","scope":"entity.name.tag","settings":{"foreground":"#800000"}},{"scope":"entity.name.selector","settings":{"foreground":"#800000"}},{"scope":"entity.other.attribute-name","settings":{"foreground":"#ff0000"}},{"scope":["entity.other.attribute-name.class.css","entity.other.attribute-name.class.mixin.css","entity.other.attribute-name.id.css","entity.other.attribute-name.parent-selector.css","entity.other.attribute-name.pseudo-class.css","entity.other.attribute-name.pseudo-element.css","source.css.less entity.other.attribute-name.id","entity.other.attribute-name.attribute.scss","entity.other.attribute-name.scss"],"settings":{"foreground":"#800000"}},{"scope":"invalid","settings":{"foreground":"#cd3131"}},{"scope":"markup.underline","settings":{"fontStyle":"underline"}},{"scope":"markup.bold","settings":{"fontStyle":"bold","foreground":"#000080"}},{"scope":"markup.heading","settings":{"fontStyle":"bold","foreground":"#800000"}},{"scope":"markup.italic","settings":{"fontStyle":"italic"}},{"scope":"markup.inserted","settings":{"foreground":"#09885a"}},{"scope":"markup.deleted","settings":{"foreground":"#a31515"}},{"scope":"markup.changed","settings":{"foreground":"#0451a5"}},{"scope":["punctuation.definition.quote.begin.markdown","punctuation.definition.list.begin.markdown"],"settings":{"foreground":"#0451a5"}},{"scope":"markup.inline.raw","settings":{"foreground":"#800000"}},{"name":"brackets of XML/HTML tags","scope":"punctuation.definition.tag","settings":{"foreground":"#800000"}},{"scope":"meta.preprocessor","settings":{"foreground":"#0000ff"}},{"scope":"meta.preprocessor.string","settings":{"foreground":"#a31515"}},{"scope":"meta.preprocessor.numeric","settings":{"foreground":"#09885a"}},{"scope":"meta.structure.dictionary.key.python","settings":{"foreground":"#0451a5"}},{"scope":"storage","settings":{"foreground":"#0000ff"}},{"scope":"storage.type","settings":{"foreground":"#0000ff"}},{"scope":"storage.modifier","settings":{"foreground":"#0000ff"}},{"scope":"string","settings":{"foreground":"#a31515"}},{"scope":["string.comment.buffered.block.pug","string.quoted.pug","string.interpolated.pug","string.unquoted.plain.in.yaml","string.unquoted.plain.out.yaml","string.unquoted.block.yaml","string.quoted.single.yaml","string.quoted.double.xml","string.quoted.single.xml","string.unquoted.cdata.xml","string.quoted.double.html","string.quoted.single.html","string.unquoted.html","string.quoted.single.handlebars","string.quoted.double.handlebars"],"settings":{"foreground":"#0000ff"}},{"scope":"string.regexp","settings":{"foreground":"#811f3f"}},{"name":"String interpolation","scope":["punctuation.definition.template-expression.begin","punctuation.definition.template-expression.end","punctuation.section.embedded"],"settings":{"foreground":"#0000ff"}},{"name":"Reset JavaScript string interpolation expression","scope":["meta.template.expression"],"settings":{"foreground":"#000000"}},{"scope":["support.constant.property-value","support.constant.font-name","support.constant.media-type","support.constant.media","constant.other.color.rgb-value","constant.other.rgb-value","support.constant.color"],"settings":{"foreground":"#0451a5"}},{"scope":["support.type.vendored.property-name","support.type.property-name","variable.css","variable.scss","variable.other.less","source.coffee.embedded"],"settings":{"foreground":"#ff0000"}},{"scope":["support.type.property-name.json"],"settings":{"foreground":"#0451a5"}},{"scope":"keyword","settings":{"foreground":"#0000ff"}},{"scope":"keyword.control","settings":{"foreground":"#0000ff"}},{"scope":"keyword.operator","settings":{"foreground":"#000000"}},{"scope":["keyword.operator.new","keyword.operator.expression","keyword.operator.cast","keyword.operator.sizeof","keyword.operator.instanceof","keyword.operator.logical.python"],"settings":{"foreground":"#0000ff"}},{"scope":"keyword.other.unit","settings":{"foreground":"#09885a"}},{"scope":["punctuation.section.embedded.begin.php","punctuation.section.embedded.end.php"],"settings":{"foreground":"#800000"}},{"scope":"support.function.git-rebase","settings":{"foreground":"#0451a5"}},{"scope":"constant.sha.git-rebase","settings":{"foreground":"#09885a"}},{"name":"coloring of the Java import and package identifiers","scope":["storage.modifier.import.java","variable.language.wildcard.java","storage.modifier.package.java"],"settings":{"foreground":"#000000"}},{"name":"this.self","scope":"variable.language","settings":{"foreground":"#0000ff"}},{"name":"Function declarations","scope":["entity.name.function","support.function","support.constant.handlebars"],"settings":{"foreground":"#795E26"}},{"name":"Types declaration and references","scope":["meta.return-type","support.class","support.type","entity.name.type","entity.name.class","storage.type.numeric.go","storage.type.byte.go","storage.type.boolean.go","storage.type.string.go","storage.type.uintptr.go","storage.type.error.go","storage.type.rune.go","storage.type.cs","storage.type.generic.cs","storage.type.modifier.cs","storage.type.variable.cs","storage.type.annotation.java","storage.type.generic.java","storage.type.java","storage.type.object.array.java","storage.type.primitive.array.java","storage.type.primitive.java","storage.type.token.java","storage.type.groovy","storage.type.annotation.groovy","storage.type.parameters.groovy","storage.type.generic.groovy","storage.type.object.array.groovy","storage.type.primitive.array.groovy","storage.type.primitive.groovy"],"settings":{"foreground":"#267f99"}},{"name":"Types declaration and references, TS grammar specific","scope":["meta.type.cast.expr","meta.type.new.expr","support.constant.math","support.constant.dom","support.constant.json","entity.other.inherited-class"],"settings":{"foreground":"#267f99"}},{"name":"Control flow keywords","scope":"keyword.control","settings":{"foreground":"#AF00DB"}},{"name":"Variable and parameter name","scope":["variable","meta.definition.variable.name","support.variable","entity.name.variable"],"settings":{"foreground":"#001080"}},{"name":"Object keys, TS grammar specific","scope":["meta.object-literal.key"],"settings":{"foreground":"#001080"}},{"name":"CSS property value","scope":["support.constant.property-value","support.constant.font-name","support.constant.media-type","support.constant.media","constant.other.color.rgb-value","constant.other.rgb-value","support.constant.color"],"settings":{"foreground":"#0451a5"}},{"name":"Regular expression groups","scope":["punctuation.definition.group.regexp","punctuation.definition.group.assertion.regexp","punctuation.definition.character-class.regexp","punctuation.character.set.begin.regexp","punctuation.character.set.end.regexp","keyword.operator.negation.regexp","support.other.parenthesis.regexp"],"settings":{"foreground":"#d16969"}},{"scope":["constant.character.character-class.regexp","constant.other.character-class.set.regexp","constant.other.character-class.regexp","constant.character.set.regexp"],"settings":{"foreground":"#811f3f"}},{"scope":"keyword.operator.quantifier.regexp","settings":{"foreground":"#000000"}},{"scope":["keyword.operator.or.regexp","keyword.control.anchor.regexp"],"settings":{"foreground":"#ff0000"}},{"scope":"constant.character","settings":{"foreground":"#0000ff"}},{"scope":"constant.character.escape","settings":{"foreground":"#ff0000"}},{"scope":"token.info-token","settings":{"foreground":"#316bcd"}},{"scope":"token.warn-token","settings":{"foreground":"#cd9731"}},{"scope":"token.error-token","settings":{"foreground":"#cd3131"}},{"scope":"token.debug-token","settings":{"foreground":"#800080"}}],"extensionData":{"extensionId":"vscode.theme-defaults","extensionPublisher":"vscode","extensionName":"theme-defaults","extensionIsBuiltin":true},"colorMap":{"editor.background":"#ffffff","editor.foreground":"#000000","editor.inactiveSelectionBackground":"#e5ebf1","editorIndentGuide.background":"#d3d3d3","editorIndentGuide.activeBackground":"#939393","editor.selectionHighlightBackground":"#add6ff4d","editorSuggestWidget.background":"#f3f3f3","activityBarBadge.background":"#007acc","sideBarTitle.foreground":"#6f6f6f","list.hoverBackground":"#e8e8e8","input.placeholderForeground":"#767676","settings.textInputBorder":"#cecece","settings.numberInputBorder":"#cecece"}}'); items.set('commandpalette.mru.cache', '{"usesLRU":true,"entries":[{"key":"revealFileInOS","value":3},{"key":"extension.openInGitHub","value":4},{"key":"workbench.extensions.action.openExtensionsFolder","value":11},{"key":"workbench.action.showRuntimeExtensions","value":14},{"key":"workbench.action.toggleTabsVisibility","value":15},{"key":"extension.liveServerPreview.open","value":16},{"key":"workbench.action.openIssueReporter","value":18},{"key":"workbench.action.openProcessExplorer","value":19},{"key":"workbench.action.toggleSharedProcess","value":20},{"key":"workbench.action.configureLocale","value":21},{"key":"workbench.action.appPerf","value":22},{"key":"workbench.action.reportPerformanceIssueUsingReporter","value":23},{"key":"workbench.action.openGlobalKeybindings","value":25},{"key":"workbench.action.output.toggleOutput","value":27},{"key":"extension.sayHello","value":29}]}'); let uuid = generateUuid(); let value: string[] = []; for (let i = 0; i < 100000; i++) { value.push(uuid); } items.set('super.large.string', value.join()); // 3.6MB await storage.updateItems({ insert: items }); let storedItems = await storage.getItems(); equal(items.get('colorthemedata'), storedItems.get('colorthemedata')); equal(items.get('commandpalette.mru.cache'), storedItems.get('commandpalette.mru.cache')); equal(items.get('super.large.string'), storedItems.get('super.large.string')); uuid = generateUuid(); value = []; for (let i = 0; i < 100000; i++) { value.push(uuid); } items.set('super.large.string', value.join()); // 3.6MB await storage.updateItems({ insert: items }); storedItems = await storage.getItems(); equal(items.get('colorthemedata'), storedItems.get('colorthemedata')); equal(items.get('commandpalette.mru.cache'), storedItems.get('commandpalette.mru.cache')); equal(items.get('super.large.string'), storedItems.get('super.large.string')); const toDelete = new Set<string>(); toDelete.add('super.large.string'); await storage.updateItems({ delete: toDelete }); storedItems = await storage.getItems(); equal(items.get('colorthemedata'), storedItems.get('colorthemedata')); equal(items.get('commandpalette.mru.cache'), storedItems.get('commandpalette.mru.cache')); ok(!storedItems.get('super.large.string')); await storage.close(); await rimraf(storageDir, RimRafMode.MOVE); }); test('multiple concurrent writes execute in sequence', async () => { const storageDir = uniqueStorageDir(); await mkdirp(storageDir); class TestStorage extends Storage { getStorage(): IStorageDatabase { return this.database; } } const storage = new TestStorage(new SQLiteStorageDatabase(join(storageDir, 'storage.db'))); await storage.init(); storage.set('foo', 'bar'); storage.set('some/foo/path', 'some/bar/path'); await timeout(10); storage.set('foo1', 'bar'); storage.set('some/foo1/path', 'some/bar/path'); await timeout(10); storage.set('foo2', 'bar'); storage.set('some/foo2/path', 'some/bar/path'); await timeout(10); storage.delete('foo1'); storage.delete('some/foo1/path'); await timeout(10); storage.delete('foo4'); storage.delete('some/foo4/path'); await timeout(70); storage.set('foo3', 'bar'); await storage.set('some/foo3/path', 'some/bar/path'); const items = await storage.getStorage().getItems(); equal(items.get('foo'), 'bar'); equal(items.get('some/foo/path'), 'some/bar/path'); equal(items.has('foo1'), false); equal(items.has('some/foo1/path'), false); equal(items.get('foo2'), 'bar'); equal(items.get('some/foo2/path'), 'some/bar/path'); equal(items.get('foo3'), 'bar'); equal(items.get('some/foo3/path'), 'some/bar/path'); await storage.close(); await rimraf(storageDir, RimRafMode.MOVE); }); test('lots of INSERT & DELETE (below inline max)', async () => { const storageDir = uniqueStorageDir(); await mkdirp(storageDir); const storage = new SQLiteStorageDatabase(join(storageDir, 'storage.db')); const items = new Map<string, string>(); const keys: Set<string> = new Set<string>(); for (let i = 0; i < 200; i++) { const uuid = generateUuid(); const key = `key: ${uuid}`; items.set(key, `value: ${uuid}`); keys.add(key); } await storage.updateItems({ insert: items }); let storedItems = await storage.getItems(); equal(storedItems.size, items.size); await storage.updateItems({ delete: keys }); storedItems = await storage.getItems(); equal(storedItems.size, 0); await storage.close(); await rimraf(storageDir, RimRafMode.MOVE); }); test('lots of INSERT & DELETE (above inline max)', async () => { const storageDir = uniqueStorageDir(); await mkdirp(storageDir); const storage = new SQLiteStorageDatabase(join(storageDir, 'storage.db')); const items = new Map<string, string>(); const keys: Set<string> = new Set<string>(); for (let i = 0; i < 400; i++) { const uuid = generateUuid(); const key = `key: ${uuid}`; items.set(key, `value: ${uuid}`); keys.add(key); } await storage.updateItems({ insert: items }); let storedItems = await storage.getItems(); equal(storedItems.size, items.size); await storage.updateItems({ delete: keys }); storedItems = await storage.getItems(); equal(storedItems.size, 0); await storage.close(); await rimraf(storageDir, RimRafMode.MOVE); }); });
src/vs/base/parts/storage/test/node/storage.test.ts
0
https://github.com/microsoft/vscode/commit/afc57a083c0c4e20ae87cf52b97820f1b43acfc5
[ 0.00017700485477689654, 0.00017330526316072792, 0.00016377204156015068, 0.0001736995909595862, 0.0000024789803774183383 ]
{ "id": 0, "code_window": [ "\t\t\tenum: [TerminalCursorStyle.BLOCK, TerminalCursorStyle.LINE, TerminalCursorStyle.UNDERLINE],\n", "\t\t\tdefault: TerminalCursorStyle.BLOCK\n", "\t\t},\n", "\t\t'terminal.integrated.scrollback': {\n", "\t\t\tdescription: nls.localize('terminal.integrated.scrollback', \"Controls the maximum amount of lines the terminal keeps in its buffer.\"),\n", "\t\t\ttype: 'number',\n", "\t\t\tdefault: 1000\n", "\t\t},\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t'terminal.integrated.cursorBarWidth': {\n", "\t\t\tdescription: nls.localize('terminal.integrated.cursorBarWidth', \"Controls the width of terminal bar cursor.\"),\n", "\t\t\ttype: 'number',\n", "\t\t\tdefault: 1\n", "\t\t},\n" ], "file_path": "src/vs/workbench/contrib/terminal/browser/terminal.contribution.ts", "type": "add", "edit_start_line_idx": 208 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as assert from 'assert'; import { ChordKeybinding, KeyCode, SimpleKeybinding } from 'vs/base/common/keyCodes'; import { OperatingSystem } from 'vs/base/common/platform'; import { refactorCommandId, organizeImportsCommandId } from 'vs/editor/contrib/codeAction/codeAction'; import { CodeActionKind } from 'vs/editor/contrib/codeAction/types'; import { CodeActionKeybindingResolver } from 'vs/editor/contrib/codeAction/codeActionMenu'; import { ResolvedKeybindingItem } from 'vs/platform/keybinding/common/resolvedKeybindingItem'; import { USLayoutResolvedKeybinding } from 'vs/platform/keybinding/common/usLayoutResolvedKeybinding'; suite('CodeActionKeybindingResolver', () => { const refactorKeybinding = createCodeActionKeybinding( KeyCode.KEY_A, refactorCommandId, { kind: CodeActionKind.Refactor.value }); const refactorExtractKeybinding = createCodeActionKeybinding( KeyCode.KEY_B, refactorCommandId, { kind: CodeActionKind.Refactor.append('extract').value }); const organizeImportsKeybinding = createCodeActionKeybinding( KeyCode.KEY_C, organizeImportsCommandId, undefined); test('Should match refactor keybindings', async function () { const resolver = new CodeActionKeybindingResolver({ getKeybindings: (): readonly ResolvedKeybindingItem[] => { return [refactorKeybinding]; }, }).getResolver(); assert.equal( resolver({ title: '' }), undefined); assert.equal( resolver({ title: '', kind: CodeActionKind.Refactor.value }), refactorKeybinding.resolvedKeybinding); assert.equal( resolver({ title: '', kind: CodeActionKind.Refactor.append('extract').value }), refactorKeybinding.resolvedKeybinding); assert.equal( resolver({ title: '', kind: CodeActionKind.QuickFix.value }), undefined); }); test('Should prefer most specific keybinding', async function () { const resolver = new CodeActionKeybindingResolver({ getKeybindings: (): readonly ResolvedKeybindingItem[] => { return [refactorKeybinding, refactorExtractKeybinding, organizeImportsKeybinding]; }, }).getResolver(); assert.equal( resolver({ title: '', kind: CodeActionKind.Refactor.value }), refactorKeybinding.resolvedKeybinding); assert.equal( resolver({ title: '', kind: CodeActionKind.Refactor.append('extract').value }), refactorExtractKeybinding.resolvedKeybinding); }); test('Organize imports should still return a keybinding even though it does not have args', async function () { const resolver = new CodeActionKeybindingResolver({ getKeybindings: (): readonly ResolvedKeybindingItem[] => { return [refactorKeybinding, refactorExtractKeybinding, organizeImportsKeybinding]; }, }).getResolver(); assert.equal( resolver({ title: '', kind: CodeActionKind.SourceOrganizeImports.value }), organizeImportsKeybinding.resolvedKeybinding); }); }); function createCodeActionKeybinding(keycode: KeyCode, command: string, commandArgs: any) { return new ResolvedKeybindingItem( new USLayoutResolvedKeybinding( new ChordKeybinding([new SimpleKeybinding(false, true, false, false, keycode)]), OperatingSystem.Linux), command, commandArgs, undefined, false); }
src/vs/editor/contrib/codeAction/test/codeActionKeybindingResolver.test.ts
0
https://github.com/microsoft/vscode/commit/afc57a083c0c4e20ae87cf52b97820f1b43acfc5
[ 0.00017611529619898647, 0.00017349442350678146, 0.00016947359836194664, 0.00017344081425108016, 0.0000018984433154400904 ]
{ "id": 1, "code_window": [ "\t\tconst config = this._configHelper.config;\n", "\t\tthis._setCursorBlink(config.cursorBlinking);\n", "\t\tthis._setCursorStyle(config.cursorStyle);\n", "\t\tthis._setCommandsToSkipShell(config.commandsToSkipShell);\n", "\t\tthis._setEnableBell(config.enableBell);\n", "\t\tthis._safeSetOption('scrollback', config.scrollback);\n", "\t\tthis._safeSetOption('minimumContrastRatio', config.minimumContrastRatio);\n", "\t\tthis._safeSetOption('fastScrollSensitivity', config.fastScrollSensitivity);\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tthis._setCursorBarWidth(config.cursorBarWidth);\n" ], "file_path": "src/vs/workbench/contrib/terminal/browser/terminalInstance.ts", "type": "add", "edit_start_line_idx": 1000 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as nls from 'vs/nls'; import { Event } from 'vs/base/common/event'; import { IDisposable } from 'vs/base/common/lifecycle'; import { RawContextKey, ContextKeyExpr } from 'vs/platform/contextkey/common/contextkey'; import { createDecorator } from 'vs/platform/instantiation/common/instantiation'; import { URI } from 'vs/base/common/uri'; import { OperatingSystem } from 'vs/base/common/platform'; import { IOpenFileRequest } from 'vs/platform/windows/common/windows'; export const TERMINAL_PANEL_ID = 'workbench.panel.terminal'; /** A context key that is set when there is at least one opened integrated terminal. */ export const KEYBINDING_CONTEXT_TERMINAL_IS_OPEN = new RawContextKey<boolean>('terminalIsOpen', false); /** A context key that is set when the integrated terminal has focus. */ export const KEYBINDING_CONTEXT_TERMINAL_FOCUS = new RawContextKey<boolean>('terminalFocus', false); /** A context key that is set when the integrated terminal does not have focus. */ export const KEYBINDING_CONTEXT_TERMINAL_NOT_FOCUSED: ContextKeyExpr = KEYBINDING_CONTEXT_TERMINAL_FOCUS.toNegated(); /** A context key that is set when the user is navigating the accessibility tree */ export const KEYBINDING_CONTEXT_TERMINAL_A11Y_TREE_FOCUS = new RawContextKey<boolean>('terminalA11yTreeFocus', false); /** A keybinding context key that is set when the integrated terminal has text selected. */ export const KEYBINDING_CONTEXT_TERMINAL_TEXT_SELECTED = new RawContextKey<boolean>('terminalTextSelected', false); /** A keybinding context key that is set when the integrated terminal does not have text selected. */ export const KEYBINDING_CONTEXT_TERMINAL_TEXT_NOT_SELECTED: ContextKeyExpr = KEYBINDING_CONTEXT_TERMINAL_TEXT_SELECTED.toNegated(); /** A context key that is set when the find widget in integrated terminal is visible. */ export const KEYBINDING_CONTEXT_TERMINAL_FIND_WIDGET_VISIBLE = new RawContextKey<boolean>('terminalFindWidgetVisible', false); /** A context key that is set when the find widget in integrated terminal is not visible. */ export const KEYBINDING_CONTEXT_TERMINAL_FIND_WIDGET_NOT_VISIBLE: ContextKeyExpr = KEYBINDING_CONTEXT_TERMINAL_FIND_WIDGET_VISIBLE.toNegated(); /** A context key that is set when the find widget find input in integrated terminal is focused. */ export const KEYBINDING_CONTEXT_TERMINAL_FIND_WIDGET_INPUT_FOCUSED = new RawContextKey<boolean>('terminalFindWidgetInputFocused', false); /** A context key that is set when the find widget in integrated terminal is focused. */ export const KEYBINDING_CONTEXT_TERMINAL_FIND_WIDGET_FOCUSED = new RawContextKey<boolean>('terminalFindWidgetFocused', false); /** A context key that is set when the find widget find input in integrated terminal is not focused. */ export const KEYBINDING_CONTEXT_TERMINAL_FIND_WIDGET_INPUT_NOT_FOCUSED: ContextKeyExpr = KEYBINDING_CONTEXT_TERMINAL_FIND_WIDGET_INPUT_FOCUSED.toNegated(); export const IS_WORKSPACE_SHELL_ALLOWED_STORAGE_KEY = 'terminal.integrated.isWorkspaceShellAllowed'; export const NEVER_MEASURE_RENDER_TIME_STORAGE_KEY = 'terminal.integrated.neverMeasureRenderTime'; // The creation of extension host terminals is delayed by this value (milliseconds). The purpose of // this delay is to allow the terminal instance to initialize correctly and have its ID set before // trying to create the corressponding object on the ext host. export const EXT_HOST_CREATION_DELAY = 100; export const ITerminalNativeService = createDecorator<ITerminalNativeService>('terminalNativeService'); export const TerminalCursorStyle = { BLOCK: 'block', LINE: 'line', UNDERLINE: 'underline' }; export const TERMINAL_CONFIG_SECTION = 'terminal.integrated'; export const TERMINAL_ACTION_CATEGORY = nls.localize('terminalCategory', "Terminal"); export const DEFAULT_LETTER_SPACING = 0; export const MINIMUM_LETTER_SPACING = -5; export const DEFAULT_LINE_HEIGHT = 1; export const SHELL_PATH_INVALID_EXIT_CODE = -1; export const SHELL_PATH_DIRECTORY_EXIT_CODE = -2; export const SHELL_CWD_INVALID_EXIT_CODE = -3; export const LEGACY_CONSOLE_MODE_EXIT_CODE = 3221225786; // microsoft/vscode#73790 export type FontWeight = 'normal' | 'bold' | '100' | '200' | '300' | '400' | '500' | '600' | '700' | '800' | '900'; export interface ITerminalConfiguration { shell: { linux: string | null; osx: string | null; windows: string | null; }; automationShell: { linux: string | null; osx: string | null; windows: string | null; }; shellArgs: { linux: string[]; osx: string[]; windows: string[]; }; macOptionIsMeta: boolean; macOptionClickForcesSelection: boolean; rendererType: 'auto' | 'canvas' | 'dom' | 'experimentalWebgl'; rightClickBehavior: 'default' | 'copyPaste' | 'paste' | 'selectWord'; cursorBlinking: boolean; cursorStyle: string; drawBoldTextInBrightColors: boolean; fastScrollSensitivity: number; fontFamily: string; fontWeight: FontWeight; fontWeightBold: FontWeight; minimumContrastRatio: number; mouseWheelScrollSensitivity: number; // fontLigatures: boolean; fontSize: number; letterSpacing: number; lineHeight: number; detectLocale: 'auto' | 'off' | 'on'; scrollback: number; commandsToSkipShell: string[]; allowChords: boolean; cwd: string; confirmOnExit: boolean; enableBell: boolean; inheritEnv: boolean; env: { linux: { [key: string]: string }; osx: { [key: string]: string }; windows: { [key: string]: string }; }; showExitAlert: boolean; splitCwd: 'workspaceRoot' | 'initial' | 'inherited'; windowsEnableConpty: boolean; experimentalRefreshOnResume: boolean; experimentalUseTitleEvent: boolean; enableFileLinks: boolean; } export interface ITerminalConfigHelper { config: ITerminalConfiguration; onWorkspacePermissionsChanged: Event<boolean>; configFontIsMonospace(): boolean; getFont(): ITerminalFont; /** Sets whether a workspace shell configuration is allowed or not */ setWorkspaceShellAllowed(isAllowed: boolean): void; checkWorkspaceShellPermissions(osOverride?: OperatingSystem): boolean; showRecommendations(shellLaunchConfig: IShellLaunchConfig): void; } export interface ITerminalFont { fontFamily: string; fontSize: number; letterSpacing: number; lineHeight: number; charWidth?: number; charHeight?: number; } export interface ITerminalEnvironment { [key: string]: string | null; } export interface IShellLaunchConfig { /** * The name of the terminal, if this is not set the name of the process will be used. */ name?: string; /** * The shell executable (bash, cmd, etc.). */ executable?: string; /** * The CLI arguments to use with executable, a string[] is in argv format and will be escaped, * a string is in "CommandLine" pre-escaped format and will be used as is. The string option is * only supported on Windows and will throw an exception if used on macOS or Linux. */ args?: string[] | string; /** * The current working directory of the terminal, this overrides the `terminal.integrated.cwd` * settings key. */ cwd?: string | URI; /** * A custom environment for the terminal, if this is not set the environment will be inherited * from the VS Code process. */ env?: ITerminalEnvironment; /** * Whether to ignore a custom cwd from the `terminal.integrated.cwd` settings key (e.g. if the * shell is being launched by an extension). */ ignoreConfigurationCwd?: boolean; /** Whether to wait for a key press before closing the terminal. */ waitOnExit?: boolean | string; /** * A string including ANSI escape sequences that will be written to the terminal emulator * _before_ the terminal process has launched, a trailing \n is added at the end of the string. * This allows for example the terminal instance to display a styled message as the first line * of the terminal. Use \x1b over \033 or \e for the escape control character. */ initialText?: string; /** * Whether an extension is controlling the terminal via a `vscode.Pseudoterminal`. */ isExtensionTerminal?: boolean; /** * Whether the terminal process environment should be exactly as provided in * `TerminalOptions.env`. When this is false (default), the environment will be based on the * window's environment and also apply configured platform settings like * `terminal.integrated.windows.env` on top. When this is true, the complete environment must be * provided as nothing will be inherited from the process or any configuration. */ strictEnv?: boolean; /** * When enabled the terminal will run the process as normal but not be surfaced to the user * until `Terminal.show` is called. The typical usage for this is when you need to run * something that may need interactivity but only want to tell the user about it when * interaction is needed. Note that the terminals will still be exposed to all extensions * as normal. */ hideFromUser?: boolean; } /** * Provides access to native or electron APIs to other terminal services. */ export interface ITerminalNativeService { _serviceBrand: undefined; readonly linuxDistro: LinuxDistro; readonly onOpenFileRequest: Event<IOpenFileRequest>; readonly onOsResume: Event<void>; getWindowsBuildNumber(): number; whenFileDeleted(path: URI): Promise<void>; getWslPath(path: string): Promise<string>; } export interface IShellDefinition { label: string; path: string; } export interface ITerminalDimensions { /** * The columns of the terminal. */ readonly cols: number; /** * The rows of the terminal. */ readonly rows: number; } export interface ICommandTracker { scrollToPreviousCommand(): void; scrollToNextCommand(): void; selectToPreviousCommand(): void; selectToNextCommand(): void; selectToPreviousLine(): void; selectToNextLine(): void; } export interface INavigationMode { exitNavigationMode(): void; focusPreviousLine(): void; focusNextLine(): void; } export interface IBeforeProcessDataEvent { /** * The data of the event, this can be modified by the event listener to change what gets sent * to the terminal. */ data: string; } export interface ITerminalProcessManager extends IDisposable { readonly processState: ProcessState; readonly ptyProcessReady: Promise<void>; readonly shellProcessId: number | undefined; readonly remoteAuthority: string | undefined; readonly os: OperatingSystem | undefined; readonly userHome: string | undefined; readonly onProcessReady: Event<void>; readonly onBeforeProcessData: Event<IBeforeProcessDataEvent>; readonly onProcessData: Event<string>; readonly onProcessTitle: Event<string>; readonly onProcessExit: Event<number | undefined>; readonly onProcessOverrideDimensions: Event<ITerminalDimensions | undefined>; readonly onProcessResolvedShellLaunchConfig: Event<IShellLaunchConfig>; dispose(immediate?: boolean): void; createProcess(shellLaunchConfig: IShellLaunchConfig, cols: number, rows: number, isScreenReaderModeEnabled: boolean): Promise<void>; write(data: string): void; setDimensions(cols: number, rows: number): void; getInitialCwd(): Promise<string>; getCwd(): Promise<string>; getLatency(): Promise<number>; } export const enum ProcessState { // The process has not been initialized yet. UNINITIALIZED, // The process is currently launching, the process is marked as launching // for a short duration after being created and is helpful to indicate // whether the process died as a result of bad shell and args. LAUNCHING, // The process is running normally. RUNNING, // The process was killed during launch, likely as a result of bad shell and // args. KILLED_DURING_LAUNCH, // The process was killed by the user (the event originated from VS Code). KILLED_BY_USER, // The process was killed by itself, for example the shell crashed or `exit` // was run. KILLED_BY_PROCESS } export interface ITerminalProcessExtHostProxy extends IDisposable { readonly terminalId: number; emitData(data: string): void; emitTitle(title: string): void; emitReady(pid: number, cwd: string): void; emitExit(exitCode: number | undefined): void; emitOverrideDimensions(dimensions: ITerminalDimensions | undefined): void; emitResolvedShellLaunchConfig(shellLaunchConfig: IShellLaunchConfig): void; emitInitialCwd(initialCwd: string): void; emitCwd(cwd: string): void; emitLatency(latency: number): void; onInput: Event<string>; onResize: Event<{ cols: number, rows: number }>; onShutdown: Event<boolean>; onRequestInitialCwd: Event<void>; onRequestCwd: Event<void>; onRequestLatency: Event<void>; } export interface ISpawnExtHostProcessRequest { proxy: ITerminalProcessExtHostProxy; shellLaunchConfig: IShellLaunchConfig; activeWorkspaceRootUri: URI | undefined; cols: number; rows: number; isWorkspaceShellAllowed: boolean; } export interface IStartExtensionTerminalRequest { proxy: ITerminalProcessExtHostProxy; cols: number; rows: number; } export interface IAvailableShellsRequest { (shells: IShellDefinition[]): void; } export interface IDefaultShellAndArgsRequest { useAutomationShell: boolean; callback: (shell: string, args: string[] | string | undefined) => void; } export enum LinuxDistro { Fedora, Ubuntu, Unknown } export enum TitleEventSource { /** From the API or the rename command that overrides any other type */ Api, /** From the process name property*/ Process, /** From the VT sequence */ Sequence } export interface IWindowsShellHelper extends IDisposable { getShellName(): Promise<string>; } /** * An interface representing a raw terminal child process, this contains a subset of the * child_process.ChildProcess node.js interface. */ export interface ITerminalChildProcess { onProcessData: Event<string>; onProcessExit: Event<number | undefined>; onProcessReady: Event<{ pid: number, cwd: string }>; onProcessTitleChanged: Event<string>; onProcessOverrideDimensions?: Event<ITerminalDimensions | undefined>; onProcessResolvedShellLaunchConfig?: Event<IShellLaunchConfig>; /** * Shutdown the terminal process. * * @param immediate When true the process will be killed immediately, otherwise the process will * be given some time to make sure no additional data comes through. */ shutdown(immediate: boolean): void; input(data: string): void; resize(cols: number, rows: number): void; getInitialCwd(): Promise<string>; getCwd(): Promise<string>; getLatency(): Promise<number>; } export const enum TERMINAL_COMMAND_ID { FIND_NEXT = 'workbench.action.terminal.findNext', FIND_PREVIOUS = 'workbench.action.terminal.findPrevious', TOGGLE = 'workbench.action.terminal.toggleTerminal', KILL = 'workbench.action.terminal.kill', QUICK_KILL = 'workbench.action.terminal.quickKill', COPY_SELECTION = 'workbench.action.terminal.copySelection', SELECT_ALL = 'workbench.action.terminal.selectAll', DELETE_WORD_LEFT = 'workbench.action.terminal.deleteWordLeft', DELETE_WORD_RIGHT = 'workbench.action.terminal.deleteWordRight', DELETE_TO_LINE_START = 'workbench.action.terminal.deleteToLineStart', MOVE_TO_LINE_START = 'workbench.action.terminal.moveToLineStart', MOVE_TO_LINE_END = 'workbench.action.terminal.moveToLineEnd', NEW = 'workbench.action.terminal.new', NEW_WITH_CWD = 'workbench.action.terminal.newWithCwd', NEW_LOCAL = 'workbench.action.terminal.newLocal', NEW_IN_ACTIVE_WORKSPACE = 'workbench.action.terminal.newInActiveWorkspace', SPLIT = 'workbench.action.terminal.split', SPLIT_IN_ACTIVE_WORKSPACE = 'workbench.action.terminal.splitInActiveWorkspace', FOCUS_PREVIOUS_PANE = 'workbench.action.terminal.focusPreviousPane', FOCUS_NEXT_PANE = 'workbench.action.terminal.focusNextPane', RESIZE_PANE_LEFT = 'workbench.action.terminal.resizePaneLeft', RESIZE_PANE_RIGHT = 'workbench.action.terminal.resizePaneRight', RESIZE_PANE_UP = 'workbench.action.terminal.resizePaneUp', RESIZE_PANE_DOWN = 'workbench.action.terminal.resizePaneDown', FOCUS = 'workbench.action.terminal.focus', FOCUS_NEXT = 'workbench.action.terminal.focusNext', FOCUS_PREVIOUS = 'workbench.action.terminal.focusPrevious', PASTE = 'workbench.action.terminal.paste', SELECT_DEFAULT_SHELL = 'workbench.action.terminal.selectDefaultShell', RUN_SELECTED_TEXT = 'workbench.action.terminal.runSelectedText', RUN_ACTIVE_FILE = 'workbench.action.terminal.runActiveFile', SWITCH_TERMINAL = 'workbench.action.terminal.switchTerminal', SCROLL_DOWN_LINE = 'workbench.action.terminal.scrollDown', SCROLL_DOWN_PAGE = 'workbench.action.terminal.scrollDownPage', SCROLL_TO_BOTTOM = 'workbench.action.terminal.scrollToBottom', SCROLL_UP_LINE = 'workbench.action.terminal.scrollUp', SCROLL_UP_PAGE = 'workbench.action.terminal.scrollUpPage', SCROLL_TO_TOP = 'workbench.action.terminal.scrollToTop', CLEAR = 'workbench.action.terminal.clear', CLEAR_SELECTION = 'workbench.action.terminal.clearSelection', MANAGE_WORKSPACE_SHELL_PERMISSIONS = 'workbench.action.terminal.manageWorkspaceShellPermissions', RENAME = 'workbench.action.terminal.rename', RENAME_WITH_ARG = 'workbench.action.terminal.renameWithArg', FIND_WIDGET_FOCUS = 'workbench.action.terminal.focusFindWidget', FIND_WIDGET_HIDE = 'workbench.action.terminal.hideFindWidget', QUICK_OPEN_TERM = 'workbench.action.quickOpenTerm', SCROLL_TO_PREVIOUS_COMMAND = 'workbench.action.terminal.scrollToPreviousCommand', SCROLL_TO_NEXT_COMMAND = 'workbench.action.terminal.scrollToNextCommand', SELECT_TO_PREVIOUS_COMMAND = 'workbench.action.terminal.selectToPreviousCommand', SELECT_TO_NEXT_COMMAND = 'workbench.action.terminal.selectToNextCommand', SELECT_TO_PREVIOUS_LINE = 'workbench.action.terminal.selectToPreviousLine', SELECT_TO_NEXT_LINE = 'workbench.action.terminal.selectToNextLine', TOGGLE_ESCAPE_SEQUENCE_LOGGING = 'toggleEscapeSequenceLogging', SEND_SEQUENCE = 'workbench.action.terminal.sendSequence', TOGGLE_FIND_REGEX = 'workbench.action.terminal.toggleFindRegex', TOGGLE_FIND_WHOLE_WORD = 'workbench.action.terminal.toggleFindWholeWord', TOGGLE_FIND_CASE_SENSITIVE = 'workbench.action.terminal.toggleFindCaseSensitive', NAVIGATION_MODE_EXIT = 'workbench.action.terminal.navigationModeExit', NAVIGATION_MODE_FOCUS_NEXT = 'workbench.action.terminal.navigationModeFocusNext', NAVIGATION_MODE_FOCUS_PREVIOUS = 'workbench.action.terminal.navigationModeFocusPrevious' }
src/vs/workbench/contrib/terminal/common/terminal.ts
1
https://github.com/microsoft/vscode/commit/afc57a083c0c4e20ae87cf52b97820f1b43acfc5
[ 0.008866853080689907, 0.0007963352836668491, 0.00016112643061205745, 0.00017139079864136875, 0.0018934122053906322 ]
{ "id": 1, "code_window": [ "\t\tconst config = this._configHelper.config;\n", "\t\tthis._setCursorBlink(config.cursorBlinking);\n", "\t\tthis._setCursorStyle(config.cursorStyle);\n", "\t\tthis._setCommandsToSkipShell(config.commandsToSkipShell);\n", "\t\tthis._setEnableBell(config.enableBell);\n", "\t\tthis._safeSetOption('scrollback', config.scrollback);\n", "\t\tthis._safeSetOption('minimumContrastRatio', config.minimumContrastRatio);\n", "\t\tthis._safeSetOption('fastScrollSensitivity', config.fastScrollSensitivity);\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tthis._setCursorBarWidth(config.cursorBarWidth);\n" ], "file_path": "src/vs/workbench/contrib/terminal/browser/terminalInstance.ts", "type": "add", "edit_start_line_idx": 1000 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { equal } from 'assert'; import { FileStorageDatabase } from 'vs/platform/storage/browser/storageService'; import { generateUuid } from 'vs/base/common/uuid'; import { join } from 'vs/base/common/path'; import { tmpdir } from 'os'; import { rimraf, RimRafMode } from 'vs/base/node/pfs'; import { NullLogService } from 'vs/platform/log/common/log'; import { Storage } from 'vs/base/parts/storage/common/storage'; import { URI } from 'vs/base/common/uri'; import { FileService } from 'vs/platform/files/common/fileService'; import { getRandomTestPath } from 'vs/base/test/node/testUtils'; import { DiskFileSystemProvider } from 'vs/platform/files/node/diskFileSystemProvider'; import { DisposableStore } from 'vs/base/common/lifecycle'; import { Schemas } from 'vs/base/common/network'; suite('Storage', () => { const parentDir = getRandomTestPath(tmpdir(), 'vsctests', 'storageservice'); let fileService: FileService; let fileProvider: DiskFileSystemProvider; let testDir: string; const disposables = new DisposableStore(); setup(async () => { const logService = new NullLogService(); fileService = new FileService(logService); disposables.add(fileService); fileProvider = new DiskFileSystemProvider(logService); disposables.add(fileService.registerProvider(Schemas.file, fileProvider)); disposables.add(fileProvider); const id = generateUuid(); testDir = join(parentDir, id); }); teardown(async () => { disposables.clear(); await rimraf(parentDir, RimRafMode.MOVE); }); test('File Based Storage', async () => { let storage = new Storage(new FileStorageDatabase(URI.file(join(testDir, 'storage.json')), false, fileService)); await storage.init(); storage.set('bar', 'foo'); storage.set('barNumber', 55); storage.set('barBoolean', true); equal(storage.get('bar'), 'foo'); equal(storage.get('barNumber'), '55'); equal(storage.get('barBoolean'), 'true'); await storage.close(); storage = new Storage(new FileStorageDatabase(URI.file(join(testDir, 'storage.json')), false, fileService)); await storage.init(); equal(storage.get('bar'), 'foo'); equal(storage.get('barNumber'), '55'); equal(storage.get('barBoolean'), 'true'); storage.delete('bar'); storage.delete('barNumber'); storage.delete('barBoolean'); equal(storage.get('bar', 'undefined'), 'undefined'); equal(storage.get('barNumber', 'undefinedNumber'), 'undefinedNumber'); equal(storage.get('barBoolean', 'undefinedBoolean'), 'undefinedBoolean'); await storage.close(); storage = new Storage(new FileStorageDatabase(URI.file(join(testDir, 'storage.json')), false, fileService)); await storage.init(); equal(storage.get('bar', 'undefined'), 'undefined'); equal(storage.get('barNumber', 'undefinedNumber'), 'undefinedNumber'); equal(storage.get('barBoolean', 'undefinedBoolean'), 'undefinedBoolean'); }); });
src/vs/platform/storage/test/electron-browser/storage.test.ts
0
https://github.com/microsoft/vscode/commit/afc57a083c0c4e20ae87cf52b97820f1b43acfc5
[ 0.00017561424465384334, 0.00017390995344612747, 0.00017205630138050765, 0.00017413382011000067, 0.0000011734771305782488 ]
{ "id": 1, "code_window": [ "\t\tconst config = this._configHelper.config;\n", "\t\tthis._setCursorBlink(config.cursorBlinking);\n", "\t\tthis._setCursorStyle(config.cursorStyle);\n", "\t\tthis._setCommandsToSkipShell(config.commandsToSkipShell);\n", "\t\tthis._setEnableBell(config.enableBell);\n", "\t\tthis._safeSetOption('scrollback', config.scrollback);\n", "\t\tthis._safeSetOption('minimumContrastRatio', config.minimumContrastRatio);\n", "\t\tthis._safeSetOption('fastScrollSensitivity', config.fastScrollSensitivity);\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tthis._setCursorBarWidth(config.cursorBarWidth);\n" ], "file_path": "src/vs/workbench/contrib/terminal/browser/terminalInstance.ts", "type": "add", "edit_start_line_idx": 1000 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { append, $, addClass, removeClass, toggleClass } from 'vs/base/browser/dom'; import { IDisposable, dispose, combinedDisposable } from 'vs/base/common/lifecycle'; import { Action } from 'vs/base/common/actions'; import { ActionBar } from 'vs/base/browser/ui/actionbar/actionbar'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { IListVirtualDelegate } from 'vs/base/browser/ui/list/list'; import { IPagedRenderer } from 'vs/base/browser/ui/list/listPaging'; import { Event } from 'vs/base/common/event'; import { domEvent } from 'vs/base/browser/event'; import { IExtension, ExtensionContainers, ExtensionState, IExtensionsWorkbenchService } from 'vs/workbench/contrib/extensions/common/extensions'; import { InstallAction, UpdateAction, ManageExtensionAction, ReloadAction, MaliciousStatusLabelAction, ExtensionActionViewItem, StatusLabelAction, RemoteInstallAction, SystemDisabledWarningAction, ExtensionToolTipAction, LocalInstallAction } from 'vs/workbench/contrib/extensions/browser/extensionsActions'; import { areSameExtensions } from 'vs/platform/extensionManagement/common/extensionManagementUtil'; import { Label, RatingsWidget, InstallCountWidget, RecommendationWidget, RemoteBadgeWidget, TooltipWidget } from 'vs/workbench/contrib/extensions/browser/extensionsWidgets'; import { IExtensionService } from 'vs/workbench/services/extensions/common/extensions'; import { IExtensionManagementServerService } from 'vs/workbench/services/extensionManagement/common/extensionManagement'; import { INotificationService } from 'vs/platform/notification/common/notification'; import { isLanguagePackExtension } from 'vs/platform/extensions/common/extensions'; export interface IExtensionsViewState { onFocus: Event<IExtension>; onBlur: Event<IExtension>; } export interface ITemplateData { root: HTMLElement; element: HTMLElement; icon: HTMLImageElement; name: HTMLElement; installCount: HTMLElement; ratings: HTMLElement; author: HTMLElement; description: HTMLElement; extension: IExtension | null; disposables: IDisposable[]; extensionDisposables: IDisposable[]; actionbar: ActionBar; } export class Delegate implements IListVirtualDelegate<IExtension> { getHeight() { return 62; } getTemplateId() { return 'extension'; } } const actionOptions = { icon: true, label: true, tabOnlyOnFocus: true }; export class Renderer implements IPagedRenderer<IExtension, ITemplateData> { constructor( private extensionViewState: IExtensionsViewState, @IInstantiationService private readonly instantiationService: IInstantiationService, @INotificationService private readonly notificationService: INotificationService, @IExtensionService private readonly extensionService: IExtensionService, @IExtensionManagementServerService private readonly extensionManagementServerService: IExtensionManagementServerService, @IExtensionsWorkbenchService private readonly extensionsWorkbenchService: IExtensionsWorkbenchService ) { } get templateId() { return 'extension'; } renderTemplate(root: HTMLElement): ITemplateData { const recommendationWidget = this.instantiationService.createInstance(RecommendationWidget, root); const element = append(root, $('.extension')); const iconContainer = append(element, $('.icon-container')); const icon = append(iconContainer, $<HTMLImageElement>('img.icon')); const iconRemoteBadgeWidget = this.instantiationService.createInstance(RemoteBadgeWidget, iconContainer, false); const details = append(element, $('.details')); const headerContainer = append(details, $('.header-container')); const header = append(headerContainer, $('.header')); const name = append(header, $('span.name')); const version = append(header, $('span.version')); const installCount = append(header, $('span.install-count')); const ratings = append(header, $('span.ratings')); const headerRemoteBadgeWidget = this.instantiationService.createInstance(RemoteBadgeWidget, header, false); const description = append(details, $('.description.ellipsis')); const footer = append(details, $('.footer')); const author = append(footer, $('.author.ellipsis')); const actionbar = new ActionBar(footer, { animated: false, actionViewItemProvider: (action: Action) => { if (action.id === ManageExtensionAction.ID) { return (<ManageExtensionAction>action).createActionViewItem(); } return new ExtensionActionViewItem(null, action, actionOptions); } }); actionbar.onDidRun(({ error }) => error && this.notificationService.error(error)); const systemDisabledWarningAction = this.instantiationService.createInstance(SystemDisabledWarningAction); const reloadAction = this.instantiationService.createInstance(ReloadAction); const actions = [ this.instantiationService.createInstance(StatusLabelAction), this.instantiationService.createInstance(UpdateAction), reloadAction, this.instantiationService.createInstance(InstallAction), this.instantiationService.createInstance(RemoteInstallAction), this.instantiationService.createInstance(LocalInstallAction), this.instantiationService.createInstance(MaliciousStatusLabelAction, false), systemDisabledWarningAction, this.instantiationService.createInstance(ManageExtensionAction) ]; const extensionTooltipAction = this.instantiationService.createInstance(ExtensionToolTipAction, systemDisabledWarningAction, reloadAction); const tooltipWidget = this.instantiationService.createInstance(TooltipWidget, root, extensionTooltipAction, recommendationWidget); const widgets = [ recommendationWidget, iconRemoteBadgeWidget, headerRemoteBadgeWidget, tooltipWidget, this.instantiationService.createInstance(Label, version, (e: IExtension) => e.version), this.instantiationService.createInstance(InstallCountWidget, installCount, true), this.instantiationService.createInstance(RatingsWidget, ratings, true) ]; const extensionContainers: ExtensionContainers = this.instantiationService.createInstance(ExtensionContainers, [...actions, ...widgets, extensionTooltipAction]); actionbar.push(actions, actionOptions); const disposables = combinedDisposable(...actions, ...widgets, actionbar, extensionContainers, extensionTooltipAction); return { root, element, icon, name, installCount, ratings, author, description, disposables: [disposables], actionbar, extensionDisposables: [], set extension(extension: IExtension) { extensionContainers.extension = extension; } }; } renderPlaceholder(index: number, data: ITemplateData): void { addClass(data.element, 'loading'); data.root.removeAttribute('aria-label'); data.extensionDisposables = dispose(data.extensionDisposables); data.icon.src = ''; data.name.textContent = ''; data.author.textContent = ''; data.description.textContent = ''; data.installCount.style.display = 'none'; data.ratings.style.display = 'none'; data.extension = null; } renderElement(extension: IExtension, index: number, data: ITemplateData): void { removeClass(data.element, 'loading'); if (extension.state !== ExtensionState.Uninstalled && !extension.server) { // Get the extension if it is installed and has no server information extension = this.extensionsWorkbenchService.local.filter(e => e.server === extension.server && areSameExtensions(e.identifier, extension.identifier))[0] || extension; } data.extensionDisposables = dispose(data.extensionDisposables); const updateEnablement = async () => { const runningExtensions = await this.extensionService.getExtensions(); if (extension.local && !isLanguagePackExtension(extension.local.manifest)) { const runningExtension = runningExtensions.filter(e => areSameExtensions({ id: e.identifier.value, uuid: e.uuid }, extension.identifier))[0]; const isSameExtensionRunning = runningExtension && extension.server === this.extensionManagementServerService.getExtensionManagementServer(runningExtension.extensionLocation); toggleClass(data.root, 'disabled', !isSameExtensionRunning); } else { removeClass(data.root, 'disabled'); } }; updateEnablement(); this.extensionService.onDidChangeExtensions(() => updateEnablement(), this, data.extensionDisposables); const onError = Event.once(domEvent(data.icon, 'error')); onError(() => data.icon.src = extension.iconUrlFallback, null, data.extensionDisposables); data.icon.src = extension.iconUrl; if (!data.icon.complete) { data.icon.style.visibility = 'hidden'; data.icon.onload = () => data.icon.style.visibility = 'inherit'; } else { data.icon.style.visibility = 'inherit'; } data.name.textContent = extension.displayName; data.author.textContent = extension.publisherDisplayName; data.description.textContent = extension.description; data.installCount.style.display = ''; data.ratings.style.display = ''; data.extension = extension; if (extension.gallery && extension.gallery.properties && extension.gallery.properties.localizedLanguages && extension.gallery.properties.localizedLanguages.length) { data.description.textContent = extension.gallery.properties.localizedLanguages.map(name => name[0].toLocaleUpperCase() + name.slice(1)).join(', '); } this.extensionViewState.onFocus(e => { if (areSameExtensions(extension.identifier, e.identifier)) { data.actionbar.viewItems.forEach(item => (<ExtensionActionViewItem>item).setFocus(true)); } }, this, data.extensionDisposables); this.extensionViewState.onBlur(e => { if (areSameExtensions(extension.identifier, e.identifier)) { data.actionbar.viewItems.forEach(item => (<ExtensionActionViewItem>item).setFocus(false)); } }, this, data.extensionDisposables); } disposeTemplate(data: ITemplateData): void { data.disposables = dispose(data.disposables); } }
src/vs/workbench/contrib/extensions/browser/extensionsList.ts
0
https://github.com/microsoft/vscode/commit/afc57a083c0c4e20ae87cf52b97820f1b43acfc5
[ 0.00017848866991698742, 0.00017358982586301863, 0.00016843674529809505, 0.00017376485629938543, 0.0000022894105313753244 ]
{ "id": 1, "code_window": [ "\t\tconst config = this._configHelper.config;\n", "\t\tthis._setCursorBlink(config.cursorBlinking);\n", "\t\tthis._setCursorStyle(config.cursorStyle);\n", "\t\tthis._setCommandsToSkipShell(config.commandsToSkipShell);\n", "\t\tthis._setEnableBell(config.enableBell);\n", "\t\tthis._safeSetOption('scrollback', config.scrollback);\n", "\t\tthis._safeSetOption('minimumContrastRatio', config.minimumContrastRatio);\n", "\t\tthis._safeSetOption('fastScrollSensitivity', config.fastScrollSensitivity);\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tthis._setCursorBarWidth(config.cursorBarWidth);\n" ], "file_path": "src/vs/workbench/contrib/terminal/browser/terminalInstance.ts", "type": "add", "edit_start_line_idx": 1000 }
{ "registrations": [ { "component": { "type": "git", "git": { "name": "Colorsublime-Themes", "repositoryUrl": "https://github.com/Colorsublime/Colorsublime-Themes", "commitHash": "c10fdd8b144486b7a4f3cb4e2251c66df222a825" } }, "version": "0.1.0" } ], "version": 1 }
extensions/theme-solarized-light/cgmanifest.json
0
https://github.com/microsoft/vscode/commit/afc57a083c0c4e20ae87cf52b97820f1b43acfc5
[ 0.0001731679221848026, 0.0001724375761114061, 0.00017170723003800958, 0.0001724375761114061, 7.303460733965039e-7 ]
{ "id": 2, "code_window": [ "\t\t}\n", "\t}\n", "\n", "\tprivate _setCommandsToSkipShell(commands: string[]): void {\n", "\t\tconst excludeCommands = commands.filter(command => command[0] === '-').map(command => command.slice(1));\n", "\t\tthis._skipTerminalCommands = DEFAULT_COMMANDS_TO_SKIP_SHELL.filter(defaultCommand => {\n", "\t\t\treturn excludeCommands.indexOf(defaultCommand) === -1;\n", "\t\t}).concat(commands);\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tprivate _setCursorBarWidth(width: number): void {\n", "\t\tconsole.log('option', width);\n", "\t\tif (this._xterm && this._xterm.getOption('cursorWidth') !== width) {\n", "\t\t\tconsole.log('set option', width);\n", "\t\t\tthis._xterm.setOption('cursorWidth', width);\n", "\t\t}\n", "\t}\n", "\n" ], "file_path": "src/vs/workbench/contrib/terminal/browser/terminalInstance.ts", "type": "add", "edit_start_line_idx": 1042 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as path from 'vs/base/common/path'; import * as dom from 'vs/base/browser/dom'; import { StandardKeyboardEvent } from 'vs/base/browser/keyboardEvent'; import { debounce } from 'vs/base/common/decorators'; import { Emitter, Event } from 'vs/base/common/event'; import { KeyCode } from 'vs/base/common/keyCodes'; import { IDisposable, dispose, Disposable } from 'vs/base/common/lifecycle'; import * as platform from 'vs/base/common/platform'; import { TabFocus } from 'vs/editor/common/config/commonEditorConfig'; import * as nls from 'vs/nls'; import { IClipboardService } from 'vs/platform/clipboard/common/clipboardService'; import { ConfigurationTarget, IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { IContextKey, IContextKeyService } from 'vs/platform/contextkey/common/contextkey'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding'; import { ILogService } from 'vs/platform/log/common/log'; import { INotificationService, IPromptChoice, Severity } from 'vs/platform/notification/common/notification'; import { IStorageService, StorageScope } from 'vs/platform/storage/common/storage'; import { activeContrastBorder, scrollbarSliderActiveBackground, scrollbarSliderBackground, scrollbarSliderHoverBackground } from 'vs/platform/theme/common/colorRegistry'; import { ICssStyleCollector, ITheme, IThemeService, registerThemingParticipant } from 'vs/platform/theme/common/themeService'; import { PANEL_BACKGROUND } from 'vs/workbench/common/theme'; import { TerminalWidgetManager } from 'vs/workbench/contrib/terminal/browser/terminalWidgetManager'; import { IShellLaunchConfig, ITerminalDimensions, ITerminalProcessManager, KEYBINDING_CONTEXT_TERMINAL_TEXT_SELECTED, NEVER_MEASURE_RENDER_TIME_STORAGE_KEY, ProcessState, TERMINAL_PANEL_ID, IWindowsShellHelper, SHELL_PATH_INVALID_EXIT_CODE, SHELL_PATH_DIRECTORY_EXIT_CODE, SHELL_CWD_INVALID_EXIT_CODE, KEYBINDING_CONTEXT_TERMINAL_A11Y_TREE_FOCUS, INavigationMode, TitleEventSource, TERMINAL_COMMAND_ID, LEGACY_CONSOLE_MODE_EXIT_CODE } from 'vs/workbench/contrib/terminal/common/terminal'; import { ansiColorIdentifiers, TERMINAL_BACKGROUND_COLOR, TERMINAL_CURSOR_BACKGROUND_COLOR, TERMINAL_CURSOR_FOREGROUND_COLOR, TERMINAL_FOREGROUND_COLOR, TERMINAL_SELECTION_BACKGROUND_COLOR } from 'vs/workbench/contrib/terminal/common/terminalColorRegistry'; import { TerminalConfigHelper } from 'vs/workbench/contrib/terminal/browser/terminalConfigHelper'; import { TerminalLinkHandler } from 'vs/workbench/contrib/terminal/browser/terminalLinkHandler'; import { IPanelService } from 'vs/workbench/services/panel/common/panelService'; import { IAccessibilityService, AccessibilitySupport } from 'vs/platform/accessibility/common/accessibility'; import { ITerminalInstanceService, ITerminalInstance, TerminalShellType } from 'vs/workbench/contrib/terminal/browser/terminal'; import { TerminalProcessManager } from 'vs/workbench/contrib/terminal/browser/terminalProcessManager'; import { Terminal as XTermTerminal, IBuffer, ITerminalAddon } from 'xterm'; import { SearchAddon, ISearchOptions } from 'xterm-addon-search'; import { CommandTrackerAddon } from 'vs/workbench/contrib/terminal/browser/addons/commandTrackerAddon'; import { NavigationModeAddon } from 'vs/workbench/contrib/terminal/browser/addons/navigationModeAddon'; import { XTermCore } from 'vs/workbench/contrib/terminal/browser/xterm-private'; import { IEditorOptions } from 'vs/editor/common/config/editorOptions'; // How long in milliseconds should an average frame take to render for a notification to appear // which suggests the fallback DOM-based renderer const SLOW_CANVAS_RENDER_THRESHOLD = 50; const NUMBER_OF_FRAMES_TO_MEASURE = 20; export const DEFAULT_COMMANDS_TO_SKIP_SHELL: string[] = [ TERMINAL_COMMAND_ID.CLEAR_SELECTION, TERMINAL_COMMAND_ID.CLEAR, TERMINAL_COMMAND_ID.COPY_SELECTION, TERMINAL_COMMAND_ID.DELETE_TO_LINE_START, TERMINAL_COMMAND_ID.DELETE_WORD_LEFT, TERMINAL_COMMAND_ID.DELETE_WORD_RIGHT, TERMINAL_COMMAND_ID.FIND_WIDGET_FOCUS, TERMINAL_COMMAND_ID.FIND_WIDGET_HIDE, TERMINAL_COMMAND_ID.FIND_NEXT, TERMINAL_COMMAND_ID.FIND_PREVIOUS, TERMINAL_COMMAND_ID.TOGGLE_FIND_REGEX, TERMINAL_COMMAND_ID.TOGGLE_FIND_WHOLE_WORD, TERMINAL_COMMAND_ID.TOGGLE_FIND_CASE_SENSITIVE, TERMINAL_COMMAND_ID.FOCUS_NEXT_PANE, TERMINAL_COMMAND_ID.FOCUS_NEXT, TERMINAL_COMMAND_ID.FOCUS_PREVIOUS_PANE, TERMINAL_COMMAND_ID.FOCUS_PREVIOUS, TERMINAL_COMMAND_ID.FOCUS, TERMINAL_COMMAND_ID.KILL, TERMINAL_COMMAND_ID.MOVE_TO_LINE_END, TERMINAL_COMMAND_ID.MOVE_TO_LINE_START, TERMINAL_COMMAND_ID.NEW_IN_ACTIVE_WORKSPACE, TERMINAL_COMMAND_ID.NEW, TERMINAL_COMMAND_ID.PASTE, TERMINAL_COMMAND_ID.RESIZE_PANE_DOWN, TERMINAL_COMMAND_ID.RESIZE_PANE_LEFT, TERMINAL_COMMAND_ID.RESIZE_PANE_RIGHT, TERMINAL_COMMAND_ID.RESIZE_PANE_UP, TERMINAL_COMMAND_ID.RUN_ACTIVE_FILE, TERMINAL_COMMAND_ID.RUN_SELECTED_TEXT, TERMINAL_COMMAND_ID.SCROLL_DOWN_LINE, TERMINAL_COMMAND_ID.SCROLL_DOWN_PAGE, TERMINAL_COMMAND_ID.SCROLL_TO_BOTTOM, TERMINAL_COMMAND_ID.SCROLL_TO_NEXT_COMMAND, TERMINAL_COMMAND_ID.SCROLL_TO_PREVIOUS_COMMAND, TERMINAL_COMMAND_ID.SCROLL_TO_TOP, TERMINAL_COMMAND_ID.SCROLL_UP_LINE, TERMINAL_COMMAND_ID.SCROLL_UP_PAGE, TERMINAL_COMMAND_ID.SEND_SEQUENCE, TERMINAL_COMMAND_ID.SELECT_ALL, TERMINAL_COMMAND_ID.SELECT_TO_NEXT_COMMAND, TERMINAL_COMMAND_ID.SELECT_TO_NEXT_LINE, TERMINAL_COMMAND_ID.SELECT_TO_PREVIOUS_COMMAND, TERMINAL_COMMAND_ID.SELECT_TO_PREVIOUS_LINE, TERMINAL_COMMAND_ID.SPLIT_IN_ACTIVE_WORKSPACE, TERMINAL_COMMAND_ID.SPLIT, TERMINAL_COMMAND_ID.TOGGLE, TERMINAL_COMMAND_ID.NAVIGATION_MODE_EXIT, TERMINAL_COMMAND_ID.NAVIGATION_MODE_FOCUS_NEXT, TERMINAL_COMMAND_ID.NAVIGATION_MODE_FOCUS_PREVIOUS, 'editor.action.toggleTabFocusMode', 'workbench.action.quickOpen', 'workbench.action.quickOpenPreviousEditor', 'workbench.action.showCommands', 'workbench.action.tasks.build', 'workbench.action.tasks.restartTask', 'workbench.action.tasks.runTask', 'workbench.action.tasks.reRunTask', 'workbench.action.tasks.showLog', 'workbench.action.tasks.showTasks', 'workbench.action.tasks.terminate', 'workbench.action.tasks.test', 'workbench.action.toggleFullScreen', 'workbench.action.terminal.focusAtIndex1', 'workbench.action.terminal.focusAtIndex2', 'workbench.action.terminal.focusAtIndex3', 'workbench.action.terminal.focusAtIndex4', 'workbench.action.terminal.focusAtIndex5', 'workbench.action.terminal.focusAtIndex6', 'workbench.action.terminal.focusAtIndex7', 'workbench.action.terminal.focusAtIndex8', 'workbench.action.terminal.focusAtIndex9', 'workbench.action.focusSecondEditorGroup', 'workbench.action.focusThirdEditorGroup', 'workbench.action.focusFourthEditorGroup', 'workbench.action.focusFifthEditorGroup', 'workbench.action.focusSixthEditorGroup', 'workbench.action.focusSeventhEditorGroup', 'workbench.action.focusEighthEditorGroup', 'workbench.action.nextPanelView', 'workbench.action.previousPanelView', 'workbench.action.nextSideBarView', 'workbench.action.previousSideBarView', 'workbench.action.debug.start', 'workbench.action.debug.stop', 'workbench.action.debug.run', 'workbench.action.debug.restart', 'workbench.action.debug.continue', 'workbench.action.debug.pause', 'workbench.action.debug.stepInto', 'workbench.action.debug.stepOut', 'workbench.action.debug.stepOver', 'workbench.action.nextEditor', 'workbench.action.previousEditor', 'workbench.action.nextEditorInGroup', 'workbench.action.previousEditorInGroup', 'workbench.action.openNextRecentlyUsedEditor', 'workbench.action.openPreviousRecentlyUsedEditor', 'workbench.action.openNextRecentlyUsedEditorInGroup', 'workbench.action.openPreviousRecentlyUsedEditorInGroup', 'workbench.action.quickOpenNextRecentlyUsedEditor', 'workbench.action.quickOpenPreviousRecentlyUsedEditor', 'workbench.action.quickOpenNextRecentlyUsedEditorInGroup', 'workbench.action.quickOpenPreviousRecentlyUsedEditorInGroup', 'workbench.action.focusActiveEditorGroup', 'workbench.action.focusFirstEditorGroup', 'workbench.action.focusLastEditorGroup', 'workbench.action.firstEditorInGroup', 'workbench.action.lastEditorInGroup', 'workbench.action.navigateUp', 'workbench.action.navigateDown', 'workbench.action.navigateRight', 'workbench.action.navigateLeft', 'workbench.action.togglePanel', 'workbench.action.quickOpenView', 'workbench.action.toggleMaximizedPanel' ]; let xtermConstructor: Promise<typeof XTermTerminal> | undefined; interface ICanvasDimensions { width: number; height: number; } interface IGridDimensions { cols: number; rows: number; } export class TerminalInstance extends Disposable implements ITerminalInstance { private static readonly EOL_REGEX = /\r?\n/g; private static _lastKnownCanvasDimensions: ICanvasDimensions | undefined; private static _lastKnownGridDimensions: IGridDimensions | undefined; private static _idCounter = 1; private _processManager!: ITerminalProcessManager; private _pressAnyKeyToCloseListener: IDisposable | undefined; private _id: number; private _isExiting: boolean; private _hadFocusOnExit: boolean; private _isVisible: boolean; private _isDisposed: boolean; private _exitCode: number | undefined; private _skipTerminalCommands: string[]; private _shellType: TerminalShellType; private _title: string = ''; private _wrapperElement: (HTMLElement & { xterm?: XTermTerminal }) | undefined; private _xterm: XTermTerminal | undefined; private _xtermCore: XTermCore | undefined; private _xtermSearch: SearchAddon | undefined; private _xtermElement: HTMLDivElement | undefined; private _terminalHasTextContextKey: IContextKey<boolean>; private _terminalA11yTreeFocusContextKey: IContextKey<boolean>; private _cols: number = 0; private _rows: number = 0; private _dimensionsOverride: ITerminalDimensions | undefined; private _windowsShellHelper: IWindowsShellHelper | undefined; private _xtermReadyPromise: Promise<XTermTerminal>; private _titleReadyPromise: Promise<string>; private _titleReadyComplete: ((title: string) => any) | undefined; private _messageTitleDisposable: IDisposable | undefined; private _widgetManager: TerminalWidgetManager | undefined; private _linkHandler: TerminalLinkHandler | undefined; private _commandTrackerAddon: CommandTrackerAddon | undefined; private _navigationModeAddon: INavigationMode & ITerminalAddon | undefined; public disableLayout: boolean; public get id(): number { return this._id; } public get cols(): number { if (this._dimensionsOverride && this._dimensionsOverride.cols) { return Math.min(Math.max(this._dimensionsOverride.cols, 2), this._cols); } return this._cols; } public get rows(): number { if (this._dimensionsOverride && this._dimensionsOverride.rows) { return Math.min(Math.max(this._dimensionsOverride.rows, 2), this._rows); } return this._rows; } public get maxCols(): number { return this._cols; } public get maxRows(): number { return this._rows; } // TODO: Ideally processId would be merged into processReady public get processId(): number | undefined { return this._processManager.shellProcessId; } // TODO: How does this work with detached processes? // TODO: Should this be an event as it can fire twice? public get processReady(): Promise<void> { return this._processManager.ptyProcessReady; } public get exitCode(): number | undefined { return this._exitCode; } public get title(): string { return this._title; } public get hadFocusOnExit(): boolean { return this._hadFocusOnExit; } public get isTitleSetByProcess(): boolean { return !!this._messageTitleDisposable; } public get shellLaunchConfig(): IShellLaunchConfig { return this._shellLaunchConfig; } public get shellType(): TerminalShellType { return this._shellType; } public get commandTracker(): CommandTrackerAddon | undefined { return this._commandTrackerAddon; } public get navigationMode(): INavigationMode | undefined { return this._navigationModeAddon; } private readonly _onExit = new Emitter<number | undefined>(); public get onExit(): Event<number | undefined> { return this._onExit.event; } private readonly _onDisposed = new Emitter<ITerminalInstance>(); public get onDisposed(): Event<ITerminalInstance> { return this._onDisposed.event; } private readonly _onFocused = new Emitter<ITerminalInstance>(); public get onFocused(): Event<ITerminalInstance> { return this._onFocused.event; } private readonly _onProcessIdReady = new Emitter<ITerminalInstance>(); public get onProcessIdReady(): Event<ITerminalInstance> { return this._onProcessIdReady.event; } private readonly _onTitleChanged = new Emitter<ITerminalInstance>(); public get onTitleChanged(): Event<ITerminalInstance> { return this._onTitleChanged.event; } private readonly _onData = new Emitter<string>(); public get onData(): Event<string> { return this._onData.event; } private readonly _onLineData = new Emitter<string>(); public get onLineData(): Event<string> { return this._onLineData.event; } private readonly _onRequestExtHostProcess = new Emitter<ITerminalInstance>(); public get onRequestExtHostProcess(): Event<ITerminalInstance> { return this._onRequestExtHostProcess.event; } private readonly _onDimensionsChanged = new Emitter<void>(); public get onDimensionsChanged(): Event<void> { return this._onDimensionsChanged.event; } private readonly _onMaximumDimensionsChanged = new Emitter<void>(); public get onMaximumDimensionsChanged(): Event<void> { return this._onMaximumDimensionsChanged.event; } private readonly _onFocus = new Emitter<ITerminalInstance>(); public get onFocus(): Event<ITerminalInstance> { return this._onFocus.event; } public constructor( private readonly _terminalFocusContextKey: IContextKey<boolean>, private readonly _configHelper: TerminalConfigHelper, private _container: HTMLElement | undefined, private _shellLaunchConfig: IShellLaunchConfig, @ITerminalInstanceService private readonly _terminalInstanceService: ITerminalInstanceService, @IContextKeyService private readonly _contextKeyService: IContextKeyService, @IKeybindingService private readonly _keybindingService: IKeybindingService, @INotificationService private readonly _notificationService: INotificationService, @IPanelService private readonly _panelService: IPanelService, @IInstantiationService private readonly _instantiationService: IInstantiationService, @IClipboardService private readonly _clipboardService: IClipboardService, @IThemeService private readonly _themeService: IThemeService, @IConfigurationService private readonly _configurationService: IConfigurationService, @ILogService private readonly _logService: ILogService, @IStorageService private readonly _storageService: IStorageService, @IAccessibilityService private readonly _accessibilityService: IAccessibilityService ) { super(); this._skipTerminalCommands = []; this._isExiting = false; this._hadFocusOnExit = false; this._isVisible = false; this._isDisposed = false; this._id = TerminalInstance._idCounter++; this._titleReadyPromise = new Promise<string>(c => { this._titleReadyComplete = c; }); this._terminalHasTextContextKey = KEYBINDING_CONTEXT_TERMINAL_TEXT_SELECTED.bindTo(this._contextKeyService); this._terminalA11yTreeFocusContextKey = KEYBINDING_CONTEXT_TERMINAL_A11Y_TREE_FOCUS.bindTo(this._contextKeyService); this.disableLayout = false; this._logService.trace(`terminalInstance#ctor (id: ${this.id})`, this._shellLaunchConfig); this._initDimensions(); this._createProcess(); this._xtermReadyPromise = this._createXterm(); this._xtermReadyPromise.then(() => { // Only attach xterm.js to the DOM if the terminal panel has been opened before. if (_container) { this._attachToElement(_container); } }); this.addDisposable(this._configurationService.onDidChangeConfiguration(e => { if (e.affectsConfiguration('terminal.integrated') || e.affectsConfiguration('editor.fastScrollSensitivity') || e.affectsConfiguration('editor.mouseWheelScrollSensitivity')) { this.updateConfig(); // HACK: Trigger another async layout to ensure xterm's CharMeasure is ready to use, // this hack can be removed when https://github.com/xtermjs/xterm.js/issues/702 is // supported. this.setVisible(this._isVisible); } if (e.affectsConfiguration('editor.accessibilitySupport')) { this.updateAccessibilitySupport(); } })); } public addDisposable(disposable: IDisposable): void { this._register(disposable); } private _initDimensions(): void { // The terminal panel needs to have been created if (!this._container) { return; } const computedStyle = window.getComputedStyle(this._container.parentElement!); const width = parseInt(computedStyle.getPropertyValue('width').replace('px', ''), 10); const height = parseInt(computedStyle.getPropertyValue('height').replace('px', ''), 10); this._evaluateColsAndRows(width, height); } /** * Evaluates and sets the cols and rows of the terminal if possible. * @param width The width of the container. * @param height The height of the container. * @return The terminal's width if it requires a layout. */ private _evaluateColsAndRows(width: number, height: number): number | null { // Ignore if dimensions are undefined or 0 if (!width || !height) { this._setLastKnownColsAndRows(); return null; } const dimension = this._getDimension(width, height); if (!dimension) { this._setLastKnownColsAndRows(); return null; } const font = this._configHelper.getFont(this._xtermCore); if (!font.charWidth || !font.charHeight) { this._setLastKnownColsAndRows(); return null; } // Because xterm.js converts from CSS pixels to actual pixels through // the use of canvas, window.devicePixelRatio needs to be used here in // order to be precise. font.charWidth/charHeight alone as insufficient // when window.devicePixelRatio changes. const scaledWidthAvailable = dimension.width * window.devicePixelRatio; const scaledCharWidth = font.charWidth * window.devicePixelRatio + font.letterSpacing; const newCols = Math.max(Math.floor(scaledWidthAvailable / scaledCharWidth), 1); const scaledHeightAvailable = dimension.height * window.devicePixelRatio; const scaledCharHeight = Math.ceil(font.charHeight * window.devicePixelRatio); const scaledLineHeight = Math.floor(scaledCharHeight * font.lineHeight); const newRows = Math.max(Math.floor(scaledHeightAvailable / scaledLineHeight), 1); if (this._cols !== newCols || this._rows !== newRows) { this._cols = newCols; this._rows = newRows; this._fireMaximumDimensionsChanged(); } return dimension.width; } private _setLastKnownColsAndRows(): void { if (TerminalInstance._lastKnownGridDimensions) { this._cols = TerminalInstance._lastKnownGridDimensions.cols; this._rows = TerminalInstance._lastKnownGridDimensions.rows; } } @debounce(50) private _fireMaximumDimensionsChanged(): void { this._onMaximumDimensionsChanged.fire(); } private _getDimension(width: number, height: number): ICanvasDimensions | undefined { // The font needs to have been initialized const font = this._configHelper.getFont(this._xtermCore); if (!font || !font.charWidth || !font.charHeight) { return undefined; } // The panel is minimized if (!this._isVisible) { return TerminalInstance._lastKnownCanvasDimensions; } if (!this._wrapperElement) { return undefined; } const wrapperElementStyle = getComputedStyle(this._wrapperElement); const marginLeft = parseInt(wrapperElementStyle.marginLeft!.split('px')[0], 10); const marginRight = parseInt(wrapperElementStyle.marginRight!.split('px')[0], 10); const bottom = parseInt(wrapperElementStyle.bottom!.split('px')[0], 10); const innerWidth = width - marginLeft - marginRight; const innerHeight = height - bottom - 1; TerminalInstance._lastKnownCanvasDimensions = new dom.Dimension(innerWidth, innerHeight); return TerminalInstance._lastKnownCanvasDimensions; } private async _getXtermConstructor(): Promise<typeof XTermTerminal> { if (xtermConstructor) { return xtermConstructor; } xtermConstructor = new Promise<typeof XTermTerminal>(async (resolve) => { const Terminal = await this._terminalInstanceService.getXtermConstructor(); // Localize strings Terminal.strings.promptLabel = nls.localize('terminal.integrated.a11yPromptLabel', 'Terminal input'); Terminal.strings.tooMuchOutput = nls.localize('terminal.integrated.a11yTooMuchOutput', 'Too much output to announce, navigate to rows manually to read'); resolve(Terminal); }); return xtermConstructor; } /** * Create xterm.js instance and attach data listeners. */ protected async _createXterm(): Promise<XTermTerminal> { const Terminal = await this._getXtermConstructor(); const font = this._configHelper.getFont(undefined, true); const config = this._configHelper.config; const editorOptions = this._configurationService.getValue<IEditorOptions>('editor'); const xterm = new Terminal({ scrollback: config.scrollback, theme: this._getXtermTheme(), drawBoldTextInBrightColors: config.drawBoldTextInBrightColors, fontFamily: font.fontFamily, fontWeight: config.fontWeight, fontWeightBold: config.fontWeightBold, fontSize: font.fontSize, letterSpacing: font.letterSpacing, lineHeight: font.lineHeight, minimumContrastRatio: config.minimumContrastRatio, bellStyle: config.enableBell ? 'sound' : 'none', macOptionIsMeta: config.macOptionIsMeta, macOptionClickForcesSelection: config.macOptionClickForcesSelection, rightClickSelectsWord: config.rightClickBehavior === 'selectWord', fastScrollModifier: 'alt', fastScrollSensitivity: editorOptions.fastScrollSensitivity, scrollSensitivity: editorOptions.mouseWheelScrollSensitivity, rendererType: config.rendererType === 'auto' || config.rendererType === 'experimentalWebgl' ? 'canvas' : config.rendererType, wordSeparator: ' ()[]{}\',"`' }); this._xterm = xterm; this._xtermCore = (xterm as any)._core as XTermCore; this.updateAccessibilitySupport(); this._terminalInstanceService.getXtermSearchConstructor().then(Addon => { this._xtermSearch = new Addon(); xterm.loadAddon(this._xtermSearch); }); if (this._shellLaunchConfig.initialText) { this._xterm.writeln(this._shellLaunchConfig.initialText); } this._xterm.onLineFeed(() => this._onLineFeed()); this._xterm.onKey(e => this._onKey(e.key, e.domEvent)); this._xterm.onSelectionChange(async () => this._onSelectionChange()); this._processManager.onProcessData(data => this._onProcessData(data)); this._xterm.onData(data => this._processManager.write(data)); this.processReady.then(async () => { if (this._linkHandler) { this._linkHandler.processCwd = await this._processManager.getInitialCwd(); } }); // Init winpty compat and link handler after process creation as they rely on the // underlying process OS this._processManager.onProcessReady(() => { if (this._processManager.os === platform.OperatingSystem.Windows) { xterm.setOption('windowsMode', true); // Force line data to be sent when the cursor is moved, the main purpose for // this is because ConPTY will often not do a line feed but instead move the // cursor, in which case we still want to send the current line's data to tasks. xterm.parser.addCsiHandler({ final: 'H' }, () => { this._onCursorMove(); return false; }); } this._linkHandler = this._instantiationService.createInstance(TerminalLinkHandler, xterm, this._processManager, this._configHelper); }); this._commandTrackerAddon = new CommandTrackerAddon(); this._xterm.loadAddon(this._commandTrackerAddon); this._register(this._themeService.onThemeChange(theme => this._updateTheme(xterm, theme))); return xterm; } private _isScreenReaderOptimized(): boolean { const detected = this._accessibilityService.getAccessibilitySupport() === AccessibilitySupport.Enabled; const config = this._configurationService.getValue('editor.accessibilitySupport'); return config === 'on' || (config === 'auto' && detected); } public reattachToElement(container: HTMLElement): void { if (!this._wrapperElement) { throw new Error('The terminal instance has not been attached to a container yet'); } this._wrapperElement.parentNode?.removeChild(this._wrapperElement); this._container = container; this._container.appendChild(this._wrapperElement); } public attachToElement(container: HTMLElement): void { // The container did not change, do nothing if (this._container === container) { return; } // Attach has not occured yet if (!this._wrapperElement) { this._attachToElement(container); return; } // The container changed, reattach this._container?.removeChild(this._wrapperElement); this._container = container; this._container.appendChild(this._wrapperElement); } public _attachToElement(container: HTMLElement): void { this._xtermReadyPromise.then(xterm => { if (this._wrapperElement) { throw new Error('The terminal instance has already been attached to a container'); } this._container = container; this._wrapperElement = document.createElement('div'); dom.addClass(this._wrapperElement, 'terminal-wrapper'); this._xtermElement = document.createElement('div'); // Attach the xterm object to the DOM, exposing it to the smoke tests this._wrapperElement.xterm = this._xterm; this._wrapperElement.appendChild(this._xtermElement); this._container.appendChild(this._wrapperElement); xterm.open(this._xtermElement); if (this._configHelper.config.rendererType === 'experimentalWebgl') { this._terminalInstanceService.getXtermWebglConstructor().then(Addon => { xterm.loadAddon(new Addon()); }); } if (!xterm.element || !xterm.textarea) { throw new Error('xterm elements not set after open'); } xterm.textarea.addEventListener('focus', () => this._onFocus.fire(this)); xterm.attachCustomKeyEventHandler((event: KeyboardEvent): boolean => { // Disable all input if the terminal is exiting if (this._isExiting) { return false; } // Skip processing by xterm.js of keyboard events that resolve to commands described // within commandsToSkipShell const standardKeyboardEvent = new StandardKeyboardEvent(event); const resolveResult = this._keybindingService.softDispatch(standardKeyboardEvent, standardKeyboardEvent.target); // Respect chords if the allowChords setting is set and it's not Escape. Escape is // handled specially for Zen Mode's Escape, Escape chord, plus it's important in // terminals generally const allowChords = resolveResult && resolveResult.enterChord && this._configHelper.config.allowChords && event.key !== 'Escape'; if (allowChords || resolveResult && this._skipTerminalCommands.some(k => k === resolveResult.commandId)) { event.preventDefault(); return false; } // If tab focus mode is on, tab is not passed to the terminal if (TabFocus.getTabFocusMode() && event.keyCode === 9) { return false; } // Always have alt+F4 skip the terminal on Windows and allow it to be handled by the // system if (platform.isWindows && event.altKey && event.key === 'F4' && !event.ctrlKey) { return false; } return true; }); this._register(dom.addDisposableListener(xterm.element, 'mousedown', () => { // We need to listen to the mouseup event on the document since the user may release // the mouse button anywhere outside of _xterm.element. const listener = dom.addDisposableListener(document, 'mouseup', () => { // Delay with a setTimeout to allow the mouseup to propagate through the DOM // before evaluating the new selection state. setTimeout(() => this._refreshSelectionContextKey(), 0); listener.dispose(); }); })); // xterm.js currently drops selection on keyup as we need to handle this case. this._register(dom.addDisposableListener(xterm.element, 'keyup', () => { // Wait until keyup has propagated through the DOM before evaluating // the new selection state. setTimeout(() => this._refreshSelectionContextKey(), 0); })); const xtermHelper: HTMLElement = <HTMLElement>xterm.element.querySelector('.xterm-helpers'); const focusTrap: HTMLElement = document.createElement('div'); focusTrap.setAttribute('tabindex', '0'); dom.addClass(focusTrap, 'focus-trap'); this._register(dom.addDisposableListener(focusTrap, 'focus', () => { let currentElement = focusTrap; while (!dom.hasClass(currentElement, 'part')) { currentElement = currentElement.parentElement!; } const hidePanelElement = <HTMLElement>currentElement.querySelector('.hide-panel-action'); hidePanelElement.focus(); })); xtermHelper.insertBefore(focusTrap, xterm.textarea); this._register(dom.addDisposableListener(xterm.textarea, 'focus', () => { this._terminalFocusContextKey.set(true); this._onFocused.fire(this); })); this._register(dom.addDisposableListener(xterm.textarea, 'blur', () => { this._terminalFocusContextKey.reset(); this._refreshSelectionContextKey(); })); this._register(dom.addDisposableListener(xterm.element, 'focus', () => { this._terminalFocusContextKey.set(true); })); this._register(dom.addDisposableListener(xterm.element, 'blur', () => { this._terminalFocusContextKey.reset(); this._refreshSelectionContextKey(); })); const widgetManager = new TerminalWidgetManager(this._wrapperElement); this._widgetManager = widgetManager; this._processManager.onProcessReady(() => this._linkHandler?.setWidgetManager(widgetManager)); const computedStyle = window.getComputedStyle(this._container); const width = parseInt(computedStyle.getPropertyValue('width').replace('px', ''), 10); const height = parseInt(computedStyle.getPropertyValue('height').replace('px', ''), 10); this.layout(new dom.Dimension(width, height)); this.setVisible(this._isVisible); this.updateConfig(); // If IShellLaunchConfig.waitOnExit was true and the process finished before the terminal // panel was initialized. if (xterm.getOption('disableStdin')) { this._attachPressAnyKeyToCloseListener(xterm); } const neverMeasureRenderTime = this._storageService.getBoolean(NEVER_MEASURE_RENDER_TIME_STORAGE_KEY, StorageScope.GLOBAL, false); if (!neverMeasureRenderTime && this._configHelper.config.rendererType === 'auto') { this._measureRenderTime(); } }); } private async _measureRenderTime(): Promise<void> { await this._xtermReadyPromise; const frameTimes: number[] = []; const textRenderLayer = this._xtermCore!._renderService._renderer._renderLayers[0]; const originalOnGridChanged = textRenderLayer.onGridChanged; const evaluateCanvasRenderer = () => { // Discard first frame time as it's normal to take longer frameTimes.shift(); const medianTime = frameTimes.sort((a, b) => a - b)[Math.floor(frameTimes.length / 2)]; if (medianTime > SLOW_CANVAS_RENDER_THRESHOLD) { const promptChoices: IPromptChoice[] = [ { label: nls.localize('yes', "Yes"), run: () => this._configurationService.updateValue('terminal.integrated.rendererType', 'dom', ConfigurationTarget.USER) } as IPromptChoice, { label: nls.localize('no', "No"), run: () => { } } as IPromptChoice, { label: nls.localize('dontShowAgain', "Don't Show Again"), isSecondary: true, run: () => this._storageService.store(NEVER_MEASURE_RENDER_TIME_STORAGE_KEY, true, StorageScope.GLOBAL) } as IPromptChoice ]; this._notificationService.prompt( Severity.Warning, nls.localize('terminal.slowRendering', 'The standard renderer for the integrated terminal appears to be slow on your computer. Would you like to switch to the alternative DOM-based renderer which may improve performance? [Read more about terminal settings](https://code.visualstudio.com/docs/editor/integrated-terminal#_changing-how-the-terminal-is-rendered).'), promptChoices ); } }; textRenderLayer.onGridChanged = (terminal: XTermTerminal, firstRow: number, lastRow: number) => { const startTime = performance.now(); originalOnGridChanged.call(textRenderLayer, terminal, firstRow, lastRow); frameTimes.push(performance.now() - startTime); if (frameTimes.length === NUMBER_OF_FRAMES_TO_MEASURE) { evaluateCanvasRenderer(); // Restore original function textRenderLayer.onGridChanged = originalOnGridChanged; } }; } public registerLinkMatcher(regex: RegExp, handler: (url: string) => void, matchIndex?: number, validationCallback?: (uri: string, callback: (isValid: boolean) => void) => void): number { return this._linkHandler!.registerCustomLinkHandler(regex, handler, matchIndex, validationCallback); } public deregisterLinkMatcher(linkMatcherId: number): void { this._xtermReadyPromise.then(xterm => xterm.deregisterLinkMatcher(linkMatcherId)); } public hasSelection(): boolean { return this._xterm ? this._xterm.hasSelection() : false; } public async copySelection(): Promise<void> { const xterm = await this._xtermReadyPromise; if (this.hasSelection()) { await this._clipboardService.writeText(xterm.getSelection()); } else { this._notificationService.warn(nls.localize('terminal.integrated.copySelection.noSelection', 'The terminal has no selection to copy')); } } public get selection(): string | undefined { return this._xterm && this.hasSelection() ? this._xterm.getSelection() : undefined; } public clearSelection(): void { this._xterm?.clearSelection(); } public selectAll(): void { // Focus here to ensure the terminal context key is set this._xterm?.focus(); this._xterm?.selectAll(); } public findNext(term: string, searchOptions: ISearchOptions): boolean { if (!this._xtermSearch) { return false; } return this._xtermSearch.findNext(term, searchOptions); } public findPrevious(term: string, searchOptions: ISearchOptions): boolean { if (!this._xtermSearch) { return false; } return this._xtermSearch.findPrevious(term, searchOptions); } public notifyFindWidgetFocusChanged(isFocused: boolean): void { if (!this._xterm) { return; } const terminalFocused = !isFocused && (document.activeElement === this._xterm.textarea || document.activeElement === this._xterm.element); this._terminalFocusContextKey.set(terminalFocused); } public dispose(immediate?: boolean): void { this._logService.trace(`terminalInstance#dispose (id: ${this.id})`); dispose(this._windowsShellHelper); this._windowsShellHelper = undefined; this._linkHandler = dispose(this._linkHandler); this._commandTrackerAddon = dispose(this._commandTrackerAddon); this._widgetManager = dispose(this._widgetManager); if (this._xterm && this._xterm.element) { this._hadFocusOnExit = dom.hasClass(this._xterm.element, 'focus'); } if (this._wrapperElement) { if (this._wrapperElement.xterm) { this._wrapperElement.xterm = undefined; } if (this._wrapperElement.parentElement && this._container) { this._container.removeChild(this._wrapperElement); } } if (this._xterm) { const buffer = this._xterm.buffer; this._sendLineData(buffer, buffer.baseY + buffer.cursorY); this._xterm.dispose(); } if (this._pressAnyKeyToCloseListener) { this._pressAnyKeyToCloseListener.dispose(); this._pressAnyKeyToCloseListener = undefined; } this._processManager.dispose(immediate); // Process manager dispose/shutdown doesn't fire process exit, trigger with undefined if it // hasn't happened yet this._onProcessExit(undefined); if (!this._isDisposed) { this._isDisposed = true; this._onDisposed.fire(this); } super.dispose(); } public forceRedraw(): void { if (!this._xterm) { return; } if (this._configHelper.config.experimentalRefreshOnResume) { if (this._xterm.getOption('rendererType') !== 'dom') { this._xterm.setOption('rendererType', 'dom'); // Do this asynchronously to clear our the texture atlas as all terminals will not // be using canvas const xterm = this._xterm; setTimeout(() => xterm.setOption('rendererType', 'canvas'), 0); } } this._xterm.refresh(0, this._xterm.rows - 1); } public focus(force?: boolean): void { if (!this._xterm) { return; } const selection = window.getSelection(); if (!selection) { return; } const text = selection.toString(); if (!text || force) { this._xterm.focus(); } } public focusWhenReady(force?: boolean): Promise<void> { return this._xtermReadyPromise.then(() => this.focus(force)); } public async paste(): Promise<void> { if (!this._xterm) { return; } this.focus(); this._xterm.paste(await this._clipboardService.readText()); } public write(text: string): void { this._xtermReadyPromise.then(() => { if (!this._xterm) { return; } this._xterm.write(text); }); } public sendText(text: string, addNewLine: boolean): void { // Normalize line endings to 'enter' press. text = text.replace(TerminalInstance.EOL_REGEX, '\r'); if (addNewLine && text.substr(text.length - 1) !== '\r') { text += '\r'; } // Send it to the process this._processManager.ptyProcessReady.then(() => this._processManager.write(text)); } public setVisible(visible: boolean): void { this._isVisible = visible; if (this._wrapperElement) { dom.toggleClass(this._wrapperElement, 'active', visible); } if (visible && this._xterm && this._xtermCore) { // Trigger a manual scroll event which will sync the viewport and scroll bar. This is // necessary if the number of rows in the terminal has decreased while it was in the // background since scrollTop changes take no effect but the terminal's position does // change since the number of visible rows decreases. // This can likely be removed after https://github.com/xtermjs/xterm.js/issues/291 is // fixed upstream. this._xtermCore._onScroll.fire(this._xterm.buffer.viewportY); if (this._container && this._container.parentElement) { // Force a layout when the instance becomes invisible. This is particularly important // for ensuring that terminals that are created in the background by an extension will // correctly get correct character measurements in order to render to the screen (see // #34554). const computedStyle = window.getComputedStyle(this._container.parentElement); const width = parseInt(computedStyle.getPropertyValue('width').replace('px', ''), 10); const height = parseInt(computedStyle.getPropertyValue('height').replace('px', ''), 10); this.layout(new dom.Dimension(width, height)); // HACK: Trigger another async layout to ensure xterm's CharMeasure is ready to use, // this hack can be removed when https://github.com/xtermjs/xterm.js/issues/702 is // supported. setTimeout(() => this.layout(new dom.Dimension(width, height)), 0); } } } public scrollDownLine(): void { this._xterm?.scrollLines(1); } public scrollDownPage(): void { this._xterm?.scrollPages(1); } public scrollToBottom(): void { this._xterm?.scrollToBottom(); } public scrollUpLine(): void { this._xterm?.scrollLines(-1); } public scrollUpPage(): void { this._xterm?.scrollPages(-1); } public scrollToTop(): void { this._xterm?.scrollToTop(); } public clear(): void { this._xterm?.clear(); } private _refreshSelectionContextKey() { const activePanel = this._panelService.getActivePanel(); const isActive = !!activePanel && activePanel.getId() === TERMINAL_PANEL_ID; this._terminalHasTextContextKey.set(isActive && this.hasSelection()); } protected _createProcess(): void { this._processManager = this._instantiationService.createInstance(TerminalProcessManager, this._id, this._configHelper); this._processManager.onProcessReady(() => this._onProcessIdReady.fire(this)); this._processManager.onProcessExit(exitCode => this._onProcessExit(exitCode)); this._processManager.onProcessData(data => this._onData.fire(data)); this._processManager.onProcessOverrideDimensions(e => this.setDimensions(e)); this._processManager.onProcessResolvedShellLaunchConfig(e => this._setResolvedShellLaunchConfig(e)); if (this._shellLaunchConfig.name) { this.setTitle(this._shellLaunchConfig.name, TitleEventSource.Api); } else { // Only listen for process title changes when a name is not provided if (this._configHelper.config.experimentalUseTitleEvent) { this._processManager.ptyProcessReady.then(() => { this._terminalInstanceService.getDefaultShellAndArgs(false).then(e => { this.setTitle(e.shell, TitleEventSource.Sequence); }); this._xtermReadyPromise.then(xterm => { this._messageTitleDisposable = xterm.onTitleChange(e => this._onTitleChange(e)); }); }); } else { this.setTitle(this._shellLaunchConfig.executable, TitleEventSource.Process); this._messageTitleDisposable = this._processManager.onProcessTitle(title => this.setTitle(title ? title : '', TitleEventSource.Process)); } } if (platform.isWindows) { this._processManager.ptyProcessReady.then(() => { if (this._processManager.remoteAuthority) { return; } this._xtermReadyPromise.then(xterm => { if (!this._isDisposed && this._processManager && this._processManager.shellProcessId) { this._windowsShellHelper = this._terminalInstanceService.createWindowsShellHelper(this._processManager.shellProcessId, this, xterm); } }); }); } // Create the process asynchronously to allow the terminal's container // to be created so dimensions are accurate setTimeout(() => { this._processManager.createProcess(this._shellLaunchConfig, this._cols, this._rows, this._isScreenReaderOptimized()); }, 0); } private _onProcessData(data: string): void { this._widgetManager?.closeMessage(); this._xterm?.write(data); } /** * Called when either a process tied to a terminal has exited or when a terminal renderer * simulates a process exiting (e.g. custom execution task). * @param exitCode The exit code of the process, this is undefined when the terminal was exited * through user action. */ private _onProcessExit(exitCode?: number): void { // Prevent dispose functions being triggered multiple times if (this._isExiting) { return; } this._logService.debug(`Terminal process exit (id: ${this.id}) with code ${exitCode}`); this._exitCode = exitCode; this._isExiting = true; let exitCodeMessage: string | undefined; // Create exit code message if (exitCode) { if (exitCode === SHELL_PATH_INVALID_EXIT_CODE) { exitCodeMessage = nls.localize('terminal.integrated.exitedWithInvalidPath', 'The terminal shell path "{0}" does not exist', this._shellLaunchConfig.executable); } else if (exitCode === SHELL_PATH_DIRECTORY_EXIT_CODE) { exitCodeMessage = nls.localize('terminal.integrated.exitedWithInvalidPathDirectory', 'The terminal shell path "{0}" is a directory', this._shellLaunchConfig.executable); } else if (exitCode === SHELL_CWD_INVALID_EXIT_CODE && this._shellLaunchConfig.cwd) { exitCodeMessage = nls.localize('terminal.integrated.exitedWithInvalidCWD', 'The terminal shell CWD "{0}" does not exist', this._shellLaunchConfig.cwd.toString()); } else if (exitCode === LEGACY_CONSOLE_MODE_EXIT_CODE) { exitCodeMessage = nls.localize('terminal.integrated.legacyConsoleModeError', 'The terminal failed to launch properly because your system has legacy console mode enabled, uncheck "Use legacy console" cmd.exe\'s properties to fix this.'); } else if (this._processManager.processState === ProcessState.KILLED_DURING_LAUNCH) { let args = ''; if (typeof this._shellLaunchConfig.args === 'string') { args = ` ${this._shellLaunchConfig.args}`; } else if (this._shellLaunchConfig.args && this._shellLaunchConfig.args.length) { args = ' ' + this._shellLaunchConfig.args.map(a => { if (typeof a === 'string' && a.indexOf(' ') !== -1) { return `'${a}'`; } return a; }).join(' '); } if (this._shellLaunchConfig.executable) { exitCodeMessage = nls.localize('terminal.integrated.launchFailed', 'The terminal process command \'{0}{1}\' failed to launch (exit code: {2})', this._shellLaunchConfig.executable, args, exitCode); } else { exitCodeMessage = nls.localize('terminal.integrated.launchFailedExtHost', 'The terminal process failed to launch (exit code: {0})', exitCode); } } else { exitCodeMessage = nls.localize('terminal.integrated.exitedWithCode', 'The terminal process terminated with exit code: {0}', exitCode); } } this._logService.debug(`Terminal process exit (id: ${this.id}) state ${this._processManager.processState}`); // Only trigger wait on exit when the exit was *not* triggered by the // user (via the `workbench.action.terminal.kill` command). if (this._shellLaunchConfig.waitOnExit && this._processManager.processState !== ProcessState.KILLED_BY_USER) { this._xtermReadyPromise.then(xterm => { if (exitCodeMessage) { xterm.writeln(exitCodeMessage); } if (typeof this._shellLaunchConfig.waitOnExit === 'string') { let message = this._shellLaunchConfig.waitOnExit; // Bold the message and add an extra new line to make it stand out from the rest of the output message = `\r\n\x1b[1m${message}\x1b[0m`; xterm.writeln(message); } // Disable all input if the terminal is exiting and listen for next keypress xterm.setOption('disableStdin', true); if (xterm.textarea) { this._attachPressAnyKeyToCloseListener(xterm); } }); } else { this.dispose(); if (exitCodeMessage) { if (this._processManager.processState === ProcessState.KILLED_DURING_LAUNCH) { this._notificationService.error(exitCodeMessage); } else { if (this._configHelper.config.showExitAlert) { this._notificationService.error(exitCodeMessage); } else { console.warn(exitCodeMessage); } } } } this._onExit.fire(exitCode); } private _attachPressAnyKeyToCloseListener(xterm: XTermTerminal) { if (xterm.textarea && !this._pressAnyKeyToCloseListener) { this._pressAnyKeyToCloseListener = dom.addDisposableListener(xterm.textarea, 'keypress', (event: KeyboardEvent) => { if (this._pressAnyKeyToCloseListener) { this._pressAnyKeyToCloseListener.dispose(); this._pressAnyKeyToCloseListener = undefined; this.dispose(); event.preventDefault(); } }); } } public reuseTerminal(shell: IShellLaunchConfig): void { // Unsubscribe any key listener we may have. this._pressAnyKeyToCloseListener?.dispose(); this._pressAnyKeyToCloseListener = undefined; // Kill and clear up the process, making the process manager ready for a new process this._processManager.dispose(); if (this._xterm) { // Ensure new processes' output starts at start of new line this._xterm.write('\n\x1b[G'); // Print initialText if specified if (shell.initialText) { this._xterm.writeln(shell.initialText); } // Clean up waitOnExit state if (this._isExiting && this._shellLaunchConfig.waitOnExit) { this._xterm.setOption('disableStdin', false); this._isExiting = false; } } // HACK: Force initialText to be non-falsy for reused terminals such that the // conptyInheritCursor flag is passed to the node-pty, this flag can cause a Window to hang // in Windows 10 1903 so we only want to use it when something is definitely written to the // terminal. shell.initialText = ' '; // Set the new shell launch config this._shellLaunchConfig = shell; // Must be done before calling _createProcess() // Launch the process unless this is only a renderer. // In the renderer only cases, we still need to set the title correctly. const oldTitle = this._title; this._createProcess(); if (oldTitle !== this._title) { this.setTitle(this._title, TitleEventSource.Process); } this._processManager.onProcessData(data => this._onProcessData(data)); } private _onLineFeed(): void { const buffer = this._xterm!.buffer; const newLine = buffer.getLine(buffer.baseY + buffer.cursorY); if (newLine && !newLine.isWrapped) { this._sendLineData(buffer, buffer.baseY + buffer.cursorY - 1); } } private _onCursorMove(): void { const buffer = this._xterm!.buffer; this._sendLineData(buffer, buffer.baseY + buffer.cursorY); } private _onTitleChange(title: string): void { if (this.isTitleSetByProcess) { this.setTitle(title, TitleEventSource.Sequence); } } private _sendLineData(buffer: IBuffer, lineIndex: number): void { let line = buffer.getLine(lineIndex); if (!line) { return; } let lineData = line.translateToString(true); while (lineIndex > 0 && line.isWrapped) { line = buffer.getLine(--lineIndex); if (!line) { break; } lineData = line.translateToString(false) + lineData; } this._onLineData.fire(lineData); } private _onKey(key: string, ev: KeyboardEvent): void { const event = new StandardKeyboardEvent(ev); if (event.equals(KeyCode.Enter)) { this._updateProcessCwd(); } } private async _onSelectionChange(): Promise<void> { if (this._configurationService.getValue('terminal.integrated.copyOnSelection')) { if (this.hasSelection()) { await this.copySelection(); } } } @debounce(2000) private async _updateProcessCwd(): Promise<string> { // reset cwd if it has changed, so file based url paths can be resolved const cwd = await this.getCwd(); if (cwd && this._linkHandler) { this._linkHandler.processCwd = cwd; } return cwd; } public updateConfig(): void { const config = this._configHelper.config; this._setCursorBlink(config.cursorBlinking); this._setCursorStyle(config.cursorStyle); this._setCommandsToSkipShell(config.commandsToSkipShell); this._setEnableBell(config.enableBell); this._safeSetOption('scrollback', config.scrollback); this._safeSetOption('minimumContrastRatio', config.minimumContrastRatio); this._safeSetOption('fastScrollSensitivity', config.fastScrollSensitivity); this._safeSetOption('scrollSensitivity', config.mouseWheelScrollSensitivity); this._safeSetOption('macOptionIsMeta', config.macOptionIsMeta); this._safeSetOption('macOptionClickForcesSelection', config.macOptionClickForcesSelection); this._safeSetOption('rightClickSelectsWord', config.rightClickBehavior === 'selectWord'); if (config.rendererType !== 'experimentalWebgl') { // Never set webgl as it's an addon not a rendererType this._safeSetOption('rendererType', config.rendererType === 'auto' ? 'canvas' : config.rendererType); } } public updateAccessibilitySupport(): void { const isEnabled = this._isScreenReaderOptimized(); if (isEnabled) { this._navigationModeAddon = new NavigationModeAddon(this._terminalA11yTreeFocusContextKey); this._xterm!.loadAddon(this._navigationModeAddon); } else { this._navigationModeAddon?.dispose(); this._navigationModeAddon = undefined; } this._xterm!.setOption('screenReaderMode', isEnabled); } private _setCursorBlink(blink: boolean): void { if (this._xterm && this._xterm.getOption('cursorBlink') !== blink) { this._xterm.setOption('cursorBlink', blink); this._xterm.refresh(0, this._xterm.rows - 1); } } private _setCursorStyle(style: string): void { if (this._xterm && this._xterm.getOption('cursorStyle') !== style) { // 'line' is used instead of bar in VS Code to be consistent with editor.cursorStyle const xtermOption = style === 'line' ? 'bar' : style; this._xterm.setOption('cursorStyle', xtermOption); } } private _setCommandsToSkipShell(commands: string[]): void { const excludeCommands = commands.filter(command => command[0] === '-').map(command => command.slice(1)); this._skipTerminalCommands = DEFAULT_COMMANDS_TO_SKIP_SHELL.filter(defaultCommand => { return excludeCommands.indexOf(defaultCommand) === -1; }).concat(commands); } private _setEnableBell(isEnabled: boolean): void { if (this._xterm) { if (this._xterm.getOption('bellStyle') === 'sound') { if (!this._configHelper.config.enableBell) { this._xterm.setOption('bellStyle', 'none'); } } else { if (this._configHelper.config.enableBell) { this._xterm.setOption('bellStyle', 'sound'); } } } } private _safeSetOption(key: string, value: any): void { if (!this._xterm) { return; } if (this._xterm.getOption(key) !== value) { this._xterm.setOption(key, value); } } public layout(dimension: dom.Dimension): void { if (this.disableLayout) { return; } const terminalWidth = this._evaluateColsAndRows(dimension.width, dimension.height); if (!terminalWidth) { return; } if (this._xterm && this._xterm.element) { this._xterm.element.style.width = terminalWidth + 'px'; } this._resize(); } @debounce(50) private _resize(): void { let cols = this.cols; let rows = this.rows; if (this._xterm && this._xtermCore) { // Only apply these settings when the terminal is visible so that // the characters are measured correctly. if (this._isVisible) { const font = this._configHelper.getFont(this._xtermCore); const config = this._configHelper.config; this._safeSetOption('letterSpacing', font.letterSpacing); this._safeSetOption('lineHeight', font.lineHeight); this._safeSetOption('fontSize', font.fontSize); this._safeSetOption('fontFamily', font.fontFamily); this._safeSetOption('fontWeight', config.fontWeight); this._safeSetOption('fontWeightBold', config.fontWeightBold); this._safeSetOption('drawBoldTextInBrightColors', config.drawBoldTextInBrightColors); } if (isNaN(cols) || isNaN(rows)) { return; } if (cols !== this._xterm.cols || rows !== this._xterm.rows) { this._onDimensionsChanged.fire(); } this._xterm.resize(cols, rows); TerminalInstance._lastKnownGridDimensions = { cols, rows }; if (this._isVisible) { // HACK: Force the renderer to unpause by simulating an IntersectionObserver event. // This is to fix an issue where dragging the window to the top of the screen to // maximize on Windows/Linux would fire an event saying that the terminal was not // visible. if (this._xterm.getOption('rendererType') === 'canvas') { this._xtermCore._renderService._onIntersectionChange({ intersectionRatio: 1 }); // HACK: Force a refresh of the screen to ensure links are refresh corrected. // This can probably be removed when the above hack is fixed in Chromium. this._xterm.refresh(0, this._xterm.rows - 1); } } } this._processManager.ptyProcessReady.then(() => this._processManager.setDimensions(cols, rows)); } public setShellType(shellType: TerminalShellType) { this._shellType = shellType; } public setTitle(title: string | undefined, eventSource: TitleEventSource): void { if (!title) { return; } switch (eventSource) { case TitleEventSource.Process: title = path.basename(title); if (platform.isWindows) { // Remove the .exe extension title = title.split('.exe')[0]; } break; case TitleEventSource.Api: // If the title has not been set by the API or the rename command, unregister the handler that // automatically updates the terminal name dispose(this._messageTitleDisposable); this._messageTitleDisposable = undefined; dispose(this._windowsShellHelper); this._windowsShellHelper = undefined; break; } const didTitleChange = title !== this._title; this._title = title; if (didTitleChange) { if (this._titleReadyComplete) { this._titleReadyComplete(title); this._titleReadyComplete = undefined; } this._onTitleChanged.fire(this); } } public waitForTitle(): Promise<string> { return this._titleReadyPromise; } public setDimensions(dimensions: ITerminalDimensions | undefined): void { this._dimensionsOverride = dimensions; this._resize(); } private _setResolvedShellLaunchConfig(shellLaunchConfig: IShellLaunchConfig): void { this._shellLaunchConfig.args = shellLaunchConfig.args; this._shellLaunchConfig.cwd = shellLaunchConfig.cwd; this._shellLaunchConfig.executable = shellLaunchConfig.executable; this._shellLaunchConfig.env = shellLaunchConfig.env; } private _getXtermTheme(theme?: ITheme): any { if (!theme) { theme = this._themeService.getTheme(); } const foregroundColor = theme.getColor(TERMINAL_FOREGROUND_COLOR); const backgroundColor = theme.getColor(TERMINAL_BACKGROUND_COLOR) || theme.getColor(PANEL_BACKGROUND); const cursorColor = theme.getColor(TERMINAL_CURSOR_FOREGROUND_COLOR) || foregroundColor; const cursorAccentColor = theme.getColor(TERMINAL_CURSOR_BACKGROUND_COLOR) || backgroundColor; const selectionColor = theme.getColor(TERMINAL_SELECTION_BACKGROUND_COLOR); return { background: backgroundColor ? backgroundColor.toString() : null, foreground: foregroundColor ? foregroundColor.toString() : null, cursor: cursorColor ? cursorColor.toString() : null, cursorAccent: cursorAccentColor ? cursorAccentColor.toString() : null, selection: selectionColor ? selectionColor.toString() : null, black: theme.getColor(ansiColorIdentifiers[0])!.toString(), red: theme.getColor(ansiColorIdentifiers[1])!.toString(), green: theme.getColor(ansiColorIdentifiers[2])!.toString(), yellow: theme.getColor(ansiColorIdentifiers[3])!.toString(), blue: theme.getColor(ansiColorIdentifiers[4])!.toString(), magenta: theme.getColor(ansiColorIdentifiers[5])!.toString(), cyan: theme.getColor(ansiColorIdentifiers[6])!.toString(), white: theme.getColor(ansiColorIdentifiers[7])!.toString(), brightBlack: theme.getColor(ansiColorIdentifiers[8])!.toString(), brightRed: theme.getColor(ansiColorIdentifiers[9])!.toString(), brightGreen: theme.getColor(ansiColorIdentifiers[10])!.toString(), brightYellow: theme.getColor(ansiColorIdentifiers[11])!.toString(), brightBlue: theme.getColor(ansiColorIdentifiers[12])!.toString(), brightMagenta: theme.getColor(ansiColorIdentifiers[13])!.toString(), brightCyan: theme.getColor(ansiColorIdentifiers[14])!.toString(), brightWhite: theme.getColor(ansiColorIdentifiers[15])!.toString() }; } private _updateTheme(xterm: XTermTerminal, theme?: ITheme): void { xterm.setOption('theme', this._getXtermTheme(theme)); } public async toggleEscapeSequenceLogging(): Promise<void> { const xterm = await this._xtermReadyPromise; const isDebug = xterm.getOption('logLevel') === 'debug'; xterm.setOption('logLevel', isDebug ? 'info' : 'debug'); } public getInitialCwd(): Promise<string> { return this._processManager.getInitialCwd(); } public getCwd(): Promise<string> { return this._processManager.getCwd(); } } registerThemingParticipant((theme: ITheme, collector: ICssStyleCollector) => { // Border const border = theme.getColor(activeContrastBorder); if (border) { collector.addRule(` .hc-black .monaco-workbench .panel.integrated-terminal .xterm.focus::before, .hc-black .monaco-workbench .panel.integrated-terminal .xterm:focus::before { border-color: ${border}; }` ); } // Scrollbar const scrollbarSliderBackgroundColor = theme.getColor(scrollbarSliderBackground); if (scrollbarSliderBackgroundColor) { collector.addRule(` .monaco-workbench .panel.integrated-terminal .find-focused .xterm .xterm-viewport, .monaco-workbench .panel.integrated-terminal .xterm.focus .xterm-viewport, .monaco-workbench .panel.integrated-terminal .xterm:focus .xterm-viewport, .monaco-workbench .panel.integrated-terminal .xterm:hover .xterm-viewport { background-color: ${scrollbarSliderBackgroundColor} !important; }` ); } const scrollbarSliderHoverBackgroundColor = theme.getColor(scrollbarSliderHoverBackground); if (scrollbarSliderHoverBackgroundColor) { collector.addRule(`.monaco-workbench .panel.integrated-terminal .xterm .xterm-viewport::-webkit-scrollbar-thumb:hover { background-color: ${scrollbarSliderHoverBackgroundColor}; }`); } const scrollbarSliderActiveBackgroundColor = theme.getColor(scrollbarSliderActiveBackground); if (scrollbarSliderActiveBackgroundColor) { collector.addRule(`.monaco-workbench .panel.integrated-terminal .xterm .xterm-viewport::-webkit-scrollbar-thumb:active { background-color: ${scrollbarSliderActiveBackgroundColor}; }`); } });
src/vs/workbench/contrib/terminal/browser/terminalInstance.ts
1
https://github.com/microsoft/vscode/commit/afc57a083c0c4e20ae87cf52b97820f1b43acfc5
[ 0.9989676475524902, 0.020650044083595276, 0.00016247529129032046, 0.00016982655506581068, 0.1385713815689087 ]
{ "id": 2, "code_window": [ "\t\t}\n", "\t}\n", "\n", "\tprivate _setCommandsToSkipShell(commands: string[]): void {\n", "\t\tconst excludeCommands = commands.filter(command => command[0] === '-').map(command => command.slice(1));\n", "\t\tthis._skipTerminalCommands = DEFAULT_COMMANDS_TO_SKIP_SHELL.filter(defaultCommand => {\n", "\t\t\treturn excludeCommands.indexOf(defaultCommand) === -1;\n", "\t\t}).concat(commands);\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tprivate _setCursorBarWidth(width: number): void {\n", "\t\tconsole.log('option', width);\n", "\t\tif (this._xterm && this._xterm.getOption('cursorWidth') !== width) {\n", "\t\t\tconsole.log('set option', width);\n", "\t\t\tthis._xterm.setOption('cursorWidth', width);\n", "\t\t}\n", "\t}\n", "\n" ], "file_path": "src/vs/workbench/contrib/terminal/browser/terminalInstance.ts", "type": "add", "edit_start_line_idx": 1042 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { CharCode } from 'vs/base/common/charCode'; import { Range } from 'vs/editor/common/core/range'; import { DefaultEndOfLine, IIdentifiedSingleEditOperation, ITextBuffer, ITextBufferBuilder } from 'vs/editor/common/model'; export function getRandomInt(min: number, max: number): number { return Math.floor(Math.random() * (max - min + 1)) + min; } export function getRandomEOLSequence(): string { let rnd = getRandomInt(1, 3); if (rnd === 1) { return '\n'; } if (rnd === 2) { return '\r'; } return '\r\n'; } export function getRandomString(minLength: number, maxLength: number): string { let length = getRandomInt(minLength, maxLength); let r = ''; for (let i = 0; i < length; i++) { r += String.fromCharCode(getRandomInt(CharCode.a, CharCode.z)); } return r; } export function generateRandomEdits(chunks: string[], editCnt: number): IIdentifiedSingleEditOperation[] { let lines: string[] = []; for (const chunk of chunks) { let newLines = chunk.split(/\r\n|\r|\n/); if (lines.length === 0) { lines.push(...newLines); } else { newLines[0] = lines[lines.length - 1] + newLines[0]; lines.splice(lines.length - 1, 1, ...newLines); } } let ops: IIdentifiedSingleEditOperation[] = []; for (let i = 0; i < editCnt; i++) { let line = getRandomInt(1, lines.length); let startColumn = getRandomInt(1, Math.max(lines[line - 1].length, 1)); let endColumn = getRandomInt(startColumn, Math.max(lines[line - 1].length, startColumn)); let text: string = ''; if (Math.random() < 0.5) { text = getRandomString(5, 10); } ops.push({ text: text, range: new Range(line, startColumn, line, endColumn) }); lines[line - 1] = lines[line - 1].substring(0, startColumn - 1) + text + lines[line - 1].substring(endColumn - 1); } return ops; } export function generateSequentialInserts(chunks: string[], editCnt: number): IIdentifiedSingleEditOperation[] { let lines: string[] = []; for (const chunk of chunks) { let newLines = chunk.split(/\r\n|\r|\n/); if (lines.length === 0) { lines.push(...newLines); } else { newLines[0] = lines[lines.length - 1] + newLines[0]; lines.splice(lines.length - 1, 1, ...newLines); } } let ops: IIdentifiedSingleEditOperation[] = []; for (let i = 0; i < editCnt; i++) { let line = lines.length; let column = lines[line - 1].length + 1; let text: string = ''; if (Math.random() < 0.5) { text = '\n'; lines.push(''); } else { text = getRandomString(1, 2); lines[line - 1] += text; } ops.push({ text: text, range: new Range(line, column, line, column) }); } return ops; } export function generateRandomReplaces(chunks: string[], editCnt: number, searchStringLen: number, replaceStringLen: number): IIdentifiedSingleEditOperation[] { let lines: string[] = []; for (const chunk of chunks) { let newLines = chunk.split(/\r\n|\r|\n/); if (lines.length === 0) { lines.push(...newLines); } else { newLines[0] = lines[lines.length - 1] + newLines[0]; lines.splice(lines.length - 1, 1, ...newLines); } } let ops: IIdentifiedSingleEditOperation[] = []; let chunkSize = Math.max(1, Math.floor(lines.length / editCnt)); let chunkCnt = Math.floor(lines.length / chunkSize); let replaceString = getRandomString(replaceStringLen, replaceStringLen); let previousChunksLength = 0; for (let i = 0; i < chunkCnt; i++) { let startLine = previousChunksLength + 1; let endLine = previousChunksLength + chunkSize; let line = getRandomInt(startLine, endLine); let maxColumn = lines[line - 1].length + 1; let startColumn = getRandomInt(1, maxColumn); let endColumn = Math.min(maxColumn, startColumn + searchStringLen); ops.push({ text: replaceString, range: new Range(line, startColumn, line, endColumn) }); previousChunksLength = endLine; } return ops; } export function createMockText(lineCount: number, minColumn: number, maxColumn: number) { let fixedEOL = getRandomEOLSequence(); let lines: string[] = []; for (let i = 0; i < lineCount; i++) { if (i !== 0) { lines.push(fixedEOL); } lines.push(getRandomString(minColumn, maxColumn)); } return lines.join(''); } export function createMockBuffer(str: string, bufferBuilder: ITextBufferBuilder): ITextBuffer { bufferBuilder.acceptChunk(str); let bufferFactory = bufferBuilder.finish(); let buffer = bufferFactory.create(DefaultEndOfLine.LF); return buffer; } export function generateRandomChunkWithLF(minLength: number, maxLength: number): string { let length = getRandomInt(minLength, maxLength); let r = ''; for (let i = 0; i < length; i++) { let randomI = getRandomInt(0, CharCode.z - CharCode.a + 1); if (randomI === 0 && Math.random() < 0.3) { r += '\n'; } else { r += String.fromCharCode(randomI + CharCode.a - 1); } } return r; }
src/vs/editor/test/common/model/linesTextBuffer/textBufferAutoTestUtils.ts
0
https://github.com/microsoft/vscode/commit/afc57a083c0c4e20ae87cf52b97820f1b43acfc5
[ 0.002650977112352848, 0.0003155621525365859, 0.00016444898210465908, 0.00016923058137763292, 0.000583862594794482 ]
{ "id": 2, "code_window": [ "\t\t}\n", "\t}\n", "\n", "\tprivate _setCommandsToSkipShell(commands: string[]): void {\n", "\t\tconst excludeCommands = commands.filter(command => command[0] === '-').map(command => command.slice(1));\n", "\t\tthis._skipTerminalCommands = DEFAULT_COMMANDS_TO_SKIP_SHELL.filter(defaultCommand => {\n", "\t\t\treturn excludeCommands.indexOf(defaultCommand) === -1;\n", "\t\t}).concat(commands);\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tprivate _setCursorBarWidth(width: number): void {\n", "\t\tconsole.log('option', width);\n", "\t\tif (this._xterm && this._xterm.getOption('cursorWidth') !== width) {\n", "\t\t\tconsole.log('set option', width);\n", "\t\t\tthis._xterm.setOption('cursorWidth', width);\n", "\t\t}\n", "\t}\n", "\n" ], "file_path": "src/vs/workbench/contrib/terminal/browser/terminalInstance.ts", "type": "add", "edit_start_line_idx": 1042 }
<svg width="53" height="36" viewBox="0 0 53 36" fill="none" xmlns="http://www.w3.org/2000/svg"> <g clip-path="url(#clip0)"> <path fill-rule="evenodd" clip-rule="evenodd" d="M48.0364 4.01042H4.00779L4.00779 32.0286H48.0364V4.01042ZM4.00779 0.0078125C1.79721 0.0078125 0.00518799 1.79984 0.00518799 4.01042V32.0286C0.00518799 34.2392 1.79721 36.0312 4.00779 36.0312H48.0364C50.247 36.0312 52.039 34.2392 52.039 32.0286V4.01042C52.039 1.79984 50.247 0.0078125 48.0364 0.0078125H4.00779ZM8.01042 8.01302H12.013V12.0156H8.01042V8.01302ZM20.0182 8.01302H16.0156V12.0156H20.0182V8.01302ZM24.0208 8.01302H28.0234V12.0156H24.0208V8.01302ZM36.0286 8.01302H32.026V12.0156H36.0286V8.01302ZM40.0312 8.01302H44.0339V12.0156H40.0312V8.01302ZM16.0156 16.0182H8.01042V20.0208H16.0156V16.0182ZM20.0182 16.0182H24.0208V20.0208H20.0182V16.0182ZM32.026 16.0182H28.0234V20.0208H32.026V16.0182ZM44.0339 16.0182V20.0208H36.0286V16.0182H44.0339ZM12.013 24.0234H8.01042V28.026H12.013V24.0234ZM16.0156 24.0234H36.0286V28.026H16.0156V24.0234ZM44.0339 24.0234H40.0312V28.026H44.0339V24.0234Z" fill="#C5C5C5"/> </g> <defs> <clipPath id="clip0"> <rect width="53" height="36" fill="white"/> </clipPath> </defs> </svg>
src/vs/editor/standalone/browser/iPadShowKeyboard/keyboard-dark.svg
0
https://github.com/microsoft/vscode/commit/afc57a083c0c4e20ae87cf52b97820f1b43acfc5
[ 0.0008423416293226182, 0.0005129877827130258, 0.00018363393610343337, 0.0005129877827130258, 0.00032935384660959244 ]
{ "id": 2, "code_window": [ "\t\t}\n", "\t}\n", "\n", "\tprivate _setCommandsToSkipShell(commands: string[]): void {\n", "\t\tconst excludeCommands = commands.filter(command => command[0] === '-').map(command => command.slice(1));\n", "\t\tthis._skipTerminalCommands = DEFAULT_COMMANDS_TO_SKIP_SHELL.filter(defaultCommand => {\n", "\t\t\treturn excludeCommands.indexOf(defaultCommand) === -1;\n", "\t\t}).concat(commands);\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tprivate _setCursorBarWidth(width: number): void {\n", "\t\tconsole.log('option', width);\n", "\t\tif (this._xterm && this._xterm.getOption('cursorWidth') !== width) {\n", "\t\t\tconsole.log('set option', width);\n", "\t\t\tthis._xterm.setOption('cursorWidth', width);\n", "\t\t}\n", "\t}\n", "\n" ], "file_path": "src/vs/workbench/contrib/terminal/browser/terminalInstance.ts", "type": "add", "edit_start_line_idx": 1042 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { ok } from 'vs/base/common/assert'; import { Schemas } from 'vs/base/common/network'; import { regExpLeadsToEndlessLoop } from 'vs/base/common/strings'; import { URI } from 'vs/base/common/uri'; import { MirrorTextModel } from 'vs/editor/common/model/mirrorTextModel'; import { ensureValidWordDefinition, getWordAtText } from 'vs/editor/common/model/wordHelper'; import { MainThreadDocumentsShape } from 'vs/workbench/api/common/extHost.protocol'; import { EndOfLine, Position, Range } from 'vs/workbench/api/common/extHostTypes'; import * as vscode from 'vscode'; import { equals } from 'vs/base/common/arrays'; const _modeId2WordDefinition = new Map<string, RegExp>(); export function setWordDefinitionFor(modeId: string, wordDefinition: RegExp | undefined): void { _modeId2WordDefinition.set(modeId, wordDefinition); } export function getWordDefinitionFor(modeId: string): RegExp | undefined { return _modeId2WordDefinition.get(modeId); } export class ExtHostDocumentData extends MirrorTextModel { private _proxy: MainThreadDocumentsShape; private _languageId: string; private _isDirty: boolean; private _document?: vscode.TextDocument; private _isDisposed: boolean = false; constructor(proxy: MainThreadDocumentsShape, uri: URI, lines: string[], eol: string, languageId: string, versionId: number, isDirty: boolean ) { super(uri, lines, eol, versionId); this._proxy = proxy; this._languageId = languageId; this._isDirty = isDirty; } dispose(): void { // we don't really dispose documents but let // extensions still read from them. some // operations, live saving, will now error tho ok(!this._isDisposed); this._isDisposed = true; this._isDirty = false; } equalLines(lines: readonly string[]): boolean { return equals(this._lines, lines); } get document(): vscode.TextDocument { if (!this._document) { const data = this; this._document = { get uri() { return data._uri; }, get fileName() { return data._uri.fsPath; }, get isUntitled() { return data._uri.scheme === Schemas.untitled; }, get languageId() { return data._languageId; }, get version() { return data._versionId; }, get isClosed() { return data._isDisposed; }, get isDirty() { return data._isDirty; }, save() { return data._save(); }, getText(range?) { return range ? data._getTextInRange(range) : data.getText(); }, get eol() { return data._eol === '\n' ? EndOfLine.LF : EndOfLine.CRLF; }, get lineCount() { return data._lines.length; }, lineAt(lineOrPos: number | vscode.Position) { return data._lineAt(lineOrPos); }, offsetAt(pos) { return data._offsetAt(pos); }, positionAt(offset) { return data._positionAt(offset); }, validateRange(ran) { return data._validateRange(ran); }, validatePosition(pos) { return data._validatePosition(pos); }, getWordRangeAtPosition(pos, regexp?) { return data._getWordRangeAtPosition(pos, regexp); } }; } return Object.freeze(this._document); } _acceptLanguageId(newLanguageId: string): void { ok(!this._isDisposed); this._languageId = newLanguageId; } _acceptIsDirty(isDirty: boolean): void { ok(!this._isDisposed); this._isDirty = isDirty; } private _save(): Promise<boolean> { if (this._isDisposed) { return Promise.reject(new Error('Document has been closed')); } return this._proxy.$trySaveDocument(this._uri); } private _getTextInRange(_range: vscode.Range): string { const range = this._validateRange(_range); if (range.isEmpty) { return ''; } if (range.isSingleLine) { return this._lines[range.start.line].substring(range.start.character, range.end.character); } const lineEnding = this._eol, startLineIndex = range.start.line, endLineIndex = range.end.line, resultLines: string[] = []; resultLines.push(this._lines[startLineIndex].substring(range.start.character)); for (let i = startLineIndex + 1; i < endLineIndex; i++) { resultLines.push(this._lines[i]); } resultLines.push(this._lines[endLineIndex].substring(0, range.end.character)); return resultLines.join(lineEnding); } private _lineAt(lineOrPosition: number | vscode.Position): vscode.TextLine { let line: number | undefined; if (lineOrPosition instanceof Position) { line = lineOrPosition.line; } else if (typeof lineOrPosition === 'number') { line = lineOrPosition; } if (typeof line !== 'number' || line < 0 || line >= this._lines.length || Math.floor(line) !== line) { throw new Error('Illegal value for `line`'); } return new ExtHostDocumentLine(line, this._lines[line], line === this._lines.length - 1); } private _offsetAt(position: vscode.Position): number { position = this._validatePosition(position); this._ensureLineStarts(); return this._lineStarts!.getAccumulatedValue(position.line - 1) + position.character; } private _positionAt(offset: number): vscode.Position { offset = Math.floor(offset); offset = Math.max(0, offset); this._ensureLineStarts(); const out = this._lineStarts!.getIndexOf(offset); const lineLength = this._lines[out.index].length; // Ensure we return a valid position return new Position(out.index, Math.min(out.remainder, lineLength)); } // ---- range math private _validateRange(range: vscode.Range): vscode.Range { if (!(range instanceof Range)) { throw new Error('Invalid argument'); } const start = this._validatePosition(range.start); const end = this._validatePosition(range.end); if (start === range.start && end === range.end) { return range; } return new Range(start.line, start.character, end.line, end.character); } private _validatePosition(position: vscode.Position): vscode.Position { if (!(position instanceof Position)) { throw new Error('Invalid argument'); } let { line, character } = position; let hasChanged = false; if (line < 0) { line = 0; character = 0; hasChanged = true; } else if (line >= this._lines.length) { line = this._lines.length - 1; character = this._lines[line].length; hasChanged = true; } else { const maxCharacter = this._lines[line].length; if (character < 0) { character = 0; hasChanged = true; } else if (character > maxCharacter) { character = maxCharacter; hasChanged = true; } } if (!hasChanged) { return position; } return new Position(line, character); } private _getWordRangeAtPosition(_position: vscode.Position, regexp?: RegExp): vscode.Range | undefined { const position = this._validatePosition(_position); if (!regexp) { // use default when custom-regexp isn't provided regexp = getWordDefinitionFor(this._languageId); } else if (regExpLeadsToEndlessLoop(regexp)) { // use default when custom-regexp is bad throw new Error(`[getWordRangeAtPosition]: ignoring custom regexp '${regexp.source}' because it matches the empty string.`); } const wordAtText = getWordAtText( position.character + 1, ensureValidWordDefinition(regexp), this._lines[position.line], 0 ); if (wordAtText) { return new Range(position.line, wordAtText.startColumn - 1, position.line, wordAtText.endColumn - 1); } return undefined; } } class ExtHostDocumentLine implements vscode.TextLine { private readonly _line: number; private readonly _text: string; private readonly _isLastLine: boolean; constructor(line: number, text: string, isLastLine: boolean) { this._line = line; this._text = text; this._isLastLine = isLastLine; } public get lineNumber(): number { return this._line; } public get text(): string { return this._text; } public get range(): Range { return new Range(this._line, 0, this._line, this._text.length); } public get rangeIncludingLineBreak(): Range { if (this._isLastLine) { return this.range; } return new Range(this._line, 0, this._line + 1, 0); } public get firstNonWhitespaceCharacterIndex(): number { //TODO@api, rename to 'leadingWhitespaceLength' return /^(\s*)/.exec(this._text)![1].length; } public get isEmptyOrWhitespace(): boolean { return this.firstNonWhitespaceCharacterIndex === this._text.length; } }
src/vs/workbench/api/common/extHostDocumentData.ts
0
https://github.com/microsoft/vscode/commit/afc57a083c0c4e20ae87cf52b97820f1b43acfc5
[ 0.00019790491205640137, 0.00017118068353738636, 0.00016583404794801027, 0.00017045173444785178, 0.000005730020802729996 ]
{ "id": 3, "code_window": [ "\tmacOptionClickForcesSelection: boolean;\n", "\trendererType: 'auto' | 'canvas' | 'dom' | 'experimentalWebgl';\n", "\trightClickBehavior: 'default' | 'copyPaste' | 'paste' | 'selectWord';\n", "\tcursorBlinking: boolean;\n", "\tcursorStyle: string;\n", "\tdrawBoldTextInBrightColors: boolean;\n", "\tfastScrollSensitivity: number;\n", "\tfontFamily: string;\n", "\tfontWeight: FontWeight;\n", "\tfontWeightBold: FontWeight;\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tcursorBarWidth: number;\n" ], "file_path": "src/vs/workbench/contrib/terminal/common/terminal.ts", "type": "add", "edit_start_line_idx": 93 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { KeyCode, KeyMod } from 'vs/base/common/keyCodes'; import * as platform from 'vs/base/common/platform'; import 'vs/css!./media/scrollbar'; import 'vs/css!./media/terminal'; import 'vs/css!./media/widgets'; import 'vs/css!./media/xterm'; import * as nls from 'vs/nls'; import { SyncActionDescriptor } from 'vs/platform/actions/common/actions'; import { CommandsRegistry } from 'vs/platform/commands/common/commands'; import { ContextKeyExpr } from 'vs/platform/contextkey/common/contextkey'; import { KeybindingWeight } from 'vs/platform/keybinding/common/keybindingsRegistry'; import { Registry } from 'vs/platform/registry/common/platform'; import { Extensions as ActionBarExtensions, IActionBarRegistry, Scope } from 'vs/workbench/browser/actions'; import * as panel from 'vs/workbench/browser/panel'; import { getQuickNavigateHandler } from 'vs/workbench/browser/parts/quickopen/quickopen'; import { Extensions as QuickOpenExtensions, IQuickOpenRegistry, QuickOpenHandlerDescriptor } from 'vs/workbench/browser/quickopen'; import { Extensions as ActionExtensions, IWorkbenchActionRegistry } from 'vs/workbench/common/actions'; import { ClearSelectionTerminalAction, ClearTerminalAction, CopyTerminalSelectionAction, CreateNewInActiveWorkspaceTerminalAction, CreateNewTerminalAction, DeleteToLineStartTerminalAction, DeleteWordLeftTerminalAction, DeleteWordRightTerminalAction, FindNext, FindPrevious, FocusActiveTerminalAction, FocusNextPaneTerminalAction, FocusNextTerminalAction, FocusPreviousPaneTerminalAction, FocusPreviousTerminalAction, FocusTerminalFindWidgetAction, HideTerminalFindWidgetAction, KillTerminalAction, MoveToLineEndTerminalAction, MoveToLineStartTerminalAction, QuickOpenActionTermContributor, QuickOpenTermAction, RenameTerminalAction, ResizePaneDownTerminalAction, ResizePaneLeftTerminalAction, ResizePaneRightTerminalAction, ResizePaneUpTerminalAction, RunActiveFileInTerminalAction, RunSelectedTextInTerminalAction, ScrollDownPageTerminalAction, ScrollDownTerminalAction, ScrollToBottomTerminalAction, ScrollToNextCommandAction, ScrollToPreviousCommandAction, ScrollToTopTerminalAction, ScrollUpPageTerminalAction, ScrollUpTerminalAction, SelectAllTerminalAction, SelectDefaultShellWindowsTerminalAction, SelectToNextCommandAction, SelectToNextLineAction, SelectToPreviousCommandAction, SelectToPreviousLineAction, SendSequenceTerminalCommand, SplitInActiveWorkspaceTerminalAction, SplitTerminalAction, TerminalPasteAction, TERMINAL_PICKER_PREFIX, ToggleCaseSensitiveCommand, ToggleEscapeSequenceLoggingAction, ToggleRegexCommand, ToggleTerminalAction, ToggleWholeWordCommand, NavigationModeFocusPreviousTerminalAction, NavigationModeFocusNextTerminalAction, NavigationModeExitTerminalAction, ManageWorkspaceShellPermissionsTerminalCommand, CreateNewWithCwdTerminalCommand, RenameWithArgTerminalCommand } from 'vs/workbench/contrib/terminal/browser/terminalActions'; import { TerminalPanel } from 'vs/workbench/contrib/terminal/browser/terminalPanel'; import { TerminalPickerHandler } from 'vs/workbench/contrib/terminal/browser/terminalQuickOpen'; import { KEYBINDING_CONTEXT_TERMINAL_FIND_WIDGET_FOCUSED, KEYBINDING_CONTEXT_TERMINAL_FIND_WIDGET_NOT_VISIBLE, KEYBINDING_CONTEXT_TERMINAL_FIND_WIDGET_VISIBLE, KEYBINDING_CONTEXT_TERMINAL_FOCUS, KEYBINDING_CONTEXT_TERMINAL_TEXT_SELECTED, TERMINAL_PANEL_ID, DEFAULT_LETTER_SPACING, DEFAULT_LINE_HEIGHT, TerminalCursorStyle, TERMINAL_ACTION_CATEGORY, KEYBINDING_CONTEXT_TERMINAL_A11Y_TREE_FOCUS, TERMINAL_COMMAND_ID } from 'vs/workbench/contrib/terminal/common/terminal'; import { registerColors } from 'vs/workbench/contrib/terminal/common/terminalColorRegistry'; import { setupTerminalCommands } from 'vs/workbench/contrib/terminal/browser/terminalCommands'; import { setupTerminalMenu } from 'vs/workbench/contrib/terminal/common/terminalMenu'; import { IConfigurationRegistry, Extensions } from 'vs/platform/configuration/common/configurationRegistry'; import { EDITOR_FONT_DEFAULTS } from 'vs/editor/common/config/editorOptions'; import { DEFAULT_COMMANDS_TO_SKIP_SHELL } from 'vs/workbench/contrib/terminal/browser/terminalInstance'; import { TerminalService } from 'vs/workbench/contrib/terminal/browser/terminalService'; import { registerSingleton } from 'vs/platform/instantiation/common/extensions'; import { registerShellConfiguration } from 'vs/workbench/contrib/terminal/common/terminalShellConfig'; import { CONTEXT_ACCESSIBILITY_MODE_ENABLED } from 'vs/platform/accessibility/common/accessibility'; import { ITerminalService } from 'vs/workbench/contrib/terminal/browser/terminal'; import { BrowserFeatures } from 'vs/base/browser/canIUse'; registerSingleton(ITerminalService, TerminalService, true); if (platform.isWeb) { registerShellConfiguration(); } const quickOpenRegistry = (Registry.as<IQuickOpenRegistry>(QuickOpenExtensions.Quickopen)); const inTerminalsPicker = 'inTerminalPicker'; quickOpenRegistry.registerQuickOpenHandler( QuickOpenHandlerDescriptor.create( TerminalPickerHandler, TerminalPickerHandler.ID, TERMINAL_PICKER_PREFIX, inTerminalsPicker, nls.localize('quickOpen.terminal', "Show All Opened Terminals") ) ); const quickOpenNavigateNextInTerminalPickerId = 'workbench.action.quickOpenNavigateNextInTerminalPicker'; CommandsRegistry.registerCommand( { id: quickOpenNavigateNextInTerminalPickerId, handler: getQuickNavigateHandler(quickOpenNavigateNextInTerminalPickerId, true) }); const quickOpenNavigatePreviousInTerminalPickerId = 'workbench.action.quickOpenNavigatePreviousInTerminalPicker'; CommandsRegistry.registerCommand( { id: quickOpenNavigatePreviousInTerminalPickerId, handler: getQuickNavigateHandler(quickOpenNavigatePreviousInTerminalPickerId, false) }); const configurationRegistry = Registry.as<IConfigurationRegistry>(Extensions.Configuration); configurationRegistry.registerConfiguration({ id: 'terminal', order: 100, title: nls.localize('terminalIntegratedConfigurationTitle', "Integrated Terminal"), type: 'object', properties: { 'terminal.integrated.automationShell.linux': { markdownDescription: nls.localize('terminal.integrated.automationShell.linux', "A path that when set will override {0} and ignore {1} values for automation-related terminal usage like tasks and debug.", '`terminal.integrated.shell.linux`', '`shellArgs`'), type: ['string', 'null'], default: null }, 'terminal.integrated.automationShell.osx': { markdownDescription: nls.localize('terminal.integrated.automationShell.osx', "A path that when set will override {0} and ignore {1} values for automation-related terminal usage like tasks and debug.", '`terminal.integrated.shell.osx`', '`shellArgs`'), type: ['string', 'null'], default: null }, 'terminal.integrated.automationShell.windows': { markdownDescription: nls.localize('terminal.integrated.automationShell.windows', "A path that when set will override {0} and ignore {1} values for automation-related terminal usage like tasks and debug.", '`terminal.integrated.shell.windows`', '`shellArgs`'), type: ['string', 'null'], default: null }, 'terminal.integrated.shellArgs.linux': { markdownDescription: nls.localize('terminal.integrated.shellArgs.linux', "The command line arguments to use when on the Linux terminal. [Read more about configuring the shell](https://code.visualstudio.com/docs/editor/integrated-terminal#_configuration)."), type: 'array', items: { type: 'string' }, default: [] }, 'terminal.integrated.shellArgs.osx': { markdownDescription: nls.localize('terminal.integrated.shellArgs.osx', "The command line arguments to use when on the macOS terminal. [Read more about configuring the shell](https://code.visualstudio.com/docs/editor/integrated-terminal#_configuration)."), type: 'array', items: { type: 'string' }, // Unlike on Linux, ~/.profile is not sourced when logging into a macOS session. This // is the reason terminals on macOS typically run login shells by default which set up // the environment. See http://unix.stackexchange.com/a/119675/115410 default: ['-l'] }, 'terminal.integrated.shellArgs.windows': { markdownDescription: nls.localize('terminal.integrated.shellArgs.windows', "The command line arguments to use when on the Windows terminal. [Read more about configuring the shell](https://code.visualstudio.com/docs/editor/integrated-terminal#_configuration)."), 'anyOf': [ { type: 'array', items: { type: 'string', markdownDescription: nls.localize('terminal.integrated.shellArgs.windows', "The command line arguments to use when on the Windows terminal. [Read more about configuring the shell](https://code.visualstudio.com/docs/editor/integrated-terminal#_configuration).") }, }, { type: 'string', markdownDescription: nls.localize('terminal.integrated.shellArgs.windows.string', "The command line arguments in [command-line format](https://msdn.microsoft.com/en-au/08dfcab2-eb6e-49a4-80eb-87d4076c98c6) to use when on the Windows terminal. [Read more about configuring the shell](https://code.visualstudio.com/docs/editor/integrated-terminal#_configuration).") } ], default: [] }, 'terminal.integrated.macOptionIsMeta': { description: nls.localize('terminal.integrated.macOptionIsMeta', "Controls whether to treat the option key as the meta key in the terminal on macOS."), type: 'boolean', default: false }, 'terminal.integrated.macOptionClickForcesSelection': { description: nls.localize('terminal.integrated.macOptionClickForcesSelection', "Controls whether to force selection when using Option+click on macOS. This will force a regular (line) selection and disallow the use of column selection mode. This enables copying and pasting using the regular terminal selection, for example, when mouse mode is enabled in tmux."), type: 'boolean', default: false }, 'terminal.integrated.copyOnSelection': { description: nls.localize('terminal.integrated.copyOnSelection', "Controls whether text selected in the terminal will be copied to the clipboard."), type: 'boolean', default: false }, 'terminal.integrated.drawBoldTextInBrightColors': { description: nls.localize('terminal.integrated.drawBoldTextInBrightColors', "Controls whether bold text in the terminal will always use the \"bright\" ANSI color variant."), type: 'boolean', default: true }, 'terminal.integrated.fontFamily': { markdownDescription: nls.localize('terminal.integrated.fontFamily', "Controls the font family of the terminal, this defaults to `#editor.fontFamily#`'s value."), type: 'string' }, // TODO: Support font ligatures // 'terminal.integrated.fontLigatures': { // 'description': nls.localize('terminal.integrated.fontLigatures', "Controls whether font ligatures are enabled in the terminal."), // 'type': 'boolean', // 'default': false // }, 'terminal.integrated.fontSize': { description: nls.localize('terminal.integrated.fontSize', "Controls the font size in pixels of the terminal."), type: 'number', default: EDITOR_FONT_DEFAULTS.fontSize }, 'terminal.integrated.letterSpacing': { description: nls.localize('terminal.integrated.letterSpacing', "Controls the letter spacing of the terminal, this is an integer value which represents the amount of additional pixels to add between characters."), type: 'number', default: DEFAULT_LETTER_SPACING }, 'terminal.integrated.lineHeight': { description: nls.localize('terminal.integrated.lineHeight', "Controls the line height of the terminal, this number is multiplied by the terminal font size to get the actual line-height in pixels."), type: 'number', default: DEFAULT_LINE_HEIGHT }, 'terminal.integrated.minimumContrastRatio': { markdownDescription: nls.localize('terminal.integrated.minimumContrastRatio', "When set the foreground color of each cell will change to try meet the contrast ratio specified. Example values:\n\n- 1: The default, do nothing.\n- 4.5: [WCAG AA compliance (minimum)](https://www.w3.org/TR/UNDERSTANDING-WCAG20/visual-audio-contrast-contrast.html).\n- 7: [WCAG AAA compliance (enhanced)](https://www.w3.org/TR/UNDERSTANDING-WCAG20/visual-audio-contrast7.html).\n- 21: White on black or black on white."), type: 'number', default: 1 }, 'terminal.integrated.fastScrollSensitivity': { markdownDescription: nls.localize('terminal.integrated.fastScrollSensitivity', "Scrolling speed multiplier when pressing `Alt`."), type: 'number', default: 5 }, 'terminal.integrated.mouseWheelScrollSensitivity': { markdownDescription: nls.localize('terminal.integrated.mouseWheelScrollSensitivity', "A multiplier to be used on the `deltaY` of mouse wheel scroll events."), type: 'number', default: 1 }, 'terminal.integrated.fontWeight': { type: 'string', enum: ['normal', 'bold', '100', '200', '300', '400', '500', '600', '700', '800', '900'], description: nls.localize('terminal.integrated.fontWeight', "The font weight to use within the terminal for non-bold text."), default: 'normal' }, 'terminal.integrated.fontWeightBold': { type: 'string', enum: ['normal', 'bold', '100', '200', '300', '400', '500', '600', '700', '800', '900'], description: nls.localize('terminal.integrated.fontWeightBold', "The font weight to use within the terminal for bold text."), default: 'bold' }, 'terminal.integrated.cursorBlinking': { description: nls.localize('terminal.integrated.cursorBlinking', "Controls whether the terminal cursor blinks."), type: 'boolean', default: false }, 'terminal.integrated.cursorStyle': { description: nls.localize('terminal.integrated.cursorStyle', "Controls the style of terminal cursor."), enum: [TerminalCursorStyle.BLOCK, TerminalCursorStyle.LINE, TerminalCursorStyle.UNDERLINE], default: TerminalCursorStyle.BLOCK }, 'terminal.integrated.scrollback': { description: nls.localize('terminal.integrated.scrollback', "Controls the maximum amount of lines the terminal keeps in its buffer."), type: 'number', default: 1000 }, 'terminal.integrated.detectLocale': { markdownDescription: nls.localize('terminal.integrated.detectLocale', "Controls whether to detect and set the `$LANG` environment variable to a UTF-8 compliant option since VS Code's terminal only supports UTF-8 encoded data coming from the shell."), type: 'string', enum: ['auto', 'off', 'on'], markdownEnumDescriptions: [ nls.localize('terminal.integrated.detectLocale.auto', "Set the `$LANG` environment variable if the existing variable does not exist or it does not end in `'.UTF-8'`."), nls.localize('terminal.integrated.detectLocale.off', "Do not set the `$LANG` environment variable."), nls.localize('terminal.integrated.detectLocale.on', "Always set the `$LANG` environment variable.") ], default: 'auto' }, 'terminal.integrated.rendererType': { type: 'string', enum: ['auto', 'canvas', 'dom', 'experimentalWebgl'], markdownEnumDescriptions: [ nls.localize('terminal.integrated.rendererType.auto', "Let VS Code guess which renderer to use."), nls.localize('terminal.integrated.rendererType.canvas', "Use the standard GPU/canvas-based renderer."), nls.localize('terminal.integrated.rendererType.dom', "Use the fallback DOM-based renderer."), nls.localize('terminal.integrated.rendererType.experimentalWebgl', "Use the experimental webgl-based renderer. Note that this has some [known issues](https://github.com/xtermjs/xterm.js/issues?q=is%3Aopen+is%3Aissue+label%3Aarea%2Faddon%2Fwebgl) and this will only be enabled for new terminals (not hot swappable like the other renderers).") ], default: 'auto', description: nls.localize('terminal.integrated.rendererType', "Controls how the terminal is rendered.") }, 'terminal.integrated.rightClickBehavior': { type: 'string', enum: ['default', 'copyPaste', 'paste', 'selectWord'], enumDescriptions: [ nls.localize('terminal.integrated.rightClickBehavior.default', "Show the context menu."), nls.localize('terminal.integrated.rightClickBehavior.copyPaste', "Copy when there is a selection, otherwise paste."), nls.localize('terminal.integrated.rightClickBehavior.paste', "Paste on right click."), nls.localize('terminal.integrated.rightClickBehavior.selectWord', "Select the word under the cursor and show the context menu.") ], default: platform.isMacintosh ? 'selectWord' : platform.isWindows ? 'copyPaste' : 'default', description: nls.localize('terminal.integrated.rightClickBehavior', "Controls how terminal reacts to right click.") }, 'terminal.integrated.cwd': { description: nls.localize('terminal.integrated.cwd', "An explicit start path where the terminal will be launched, this is used as the current working directory (cwd) for the shell process. This may be particularly useful in workspace settings if the root directory is not a convenient cwd."), type: 'string', default: undefined }, 'terminal.integrated.confirmOnExit': { description: nls.localize('terminal.integrated.confirmOnExit', "Controls whether to confirm on exit if there are active terminal sessions."), type: 'boolean', default: false }, 'terminal.integrated.enableBell': { description: nls.localize('terminal.integrated.enableBell', "Controls whether the terminal bell is enabled."), type: 'boolean', default: false }, 'terminal.integrated.commandsToSkipShell': { markdownDescription: nls.localize('terminal.integrated.commandsToSkipShell', "A set of command IDs whose keybindings will not be sent to the shell and instead always be handled by Code. This allows the use of keybindings that would normally be consumed by the shell to act the same as when the terminal is not focused, for example ctrl+p to launch Quick Open.\nDefault Skipped Commands:\n\n{0}", DEFAULT_COMMANDS_TO_SKIP_SHELL.sort().map(command => `- ${command}`).join('\n')), type: 'array', items: { type: 'string' }, default: [] }, 'terminal.integrated.allowChords': { markdownDescription: nls.localize('terminal.integrated.allowChords', "Whether or not to allow chord keybindings in the terminal. Note that when this is true and the keystroke results in a chord it will bypass `#terminal.integrated.commandsToSkipShell#`, setting this to false is particularly useful when you want ctrl+k to go to your shell (not VS Code)."), type: 'boolean', default: true }, 'terminal.integrated.inheritEnv': { markdownDescription: nls.localize('terminal.integrated.inheritEnv', "Whether new shells should inherit their environment from VS Code. This is not supported on Windows."), type: 'boolean', default: true }, 'terminal.integrated.env.osx': { markdownDescription: nls.localize('terminal.integrated.env.osx', "Object with environment variables that will be added to the VS Code process to be used by the terminal on macOS. Set to `null` to delete the environment variable."), type: 'object', additionalProperties: { type: ['string', 'null'] }, default: {} }, 'terminal.integrated.env.linux': { markdownDescription: nls.localize('terminal.integrated.env.linux', "Object with environment variables that will be added to the VS Code process to be used by the terminal on Linux. Set to `null` to delete the environment variable."), type: 'object', additionalProperties: { type: ['string', 'null'] }, default: {} }, 'terminal.integrated.env.windows': { markdownDescription: nls.localize('terminal.integrated.env.windows', "Object with environment variables that will be added to the VS Code process to be used by the terminal on Windows. Set to `null` to delete the environment variable."), type: 'object', additionalProperties: { type: ['string', 'null'] }, default: {} }, 'terminal.integrated.showExitAlert': { description: nls.localize('terminal.integrated.showExitAlert', "Controls whether to show the alert \"The terminal process terminated with exit code\" when exit code is non-zero."), type: 'boolean', default: true }, 'terminal.integrated.splitCwd': { description: nls.localize('terminal.integrated.splitCwd', "Controls the working directory a split terminal starts with."), type: 'string', enum: ['workspaceRoot', 'initial', 'inherited'], enumDescriptions: [ nls.localize('terminal.integrated.splitCwd.workspaceRoot', "A new split terminal will use the workspace root as the working directory. In a multi-root workspace a choice for which root folder to use is offered."), nls.localize('terminal.integrated.splitCwd.initial', "A new split terminal will use the working directory that the parent terminal started with."), nls.localize('terminal.integrated.splitCwd.inherited', "On macOS and Linux, a new split terminal will use the working directory of the parent terminal. On Windows, this behaves the same as initial."), ], default: 'inherited' }, 'terminal.integrated.windowsEnableConpty': { description: nls.localize('terminal.integrated.windowsEnableConpty', "Whether to use ConPTY for Windows terminal process communication (requires Windows 10 build number 18309+). Winpty will be used if this is false."), type: 'boolean', default: true }, 'terminal.integrated.experimentalRefreshOnResume': { description: nls.localize('terminal.integrated.experimentalRefreshOnResume', "An experimental setting that will refresh the terminal renderer when the system is resumed."), type: 'boolean', default: false }, 'terminal.integrated.experimentalUseTitleEvent': { description: nls.localize('terminal.integrated.experimentalUseTitleEvent', "An experimental setting that will use the terminal title event for the dropdown title. This setting will only apply to new terminals."), type: 'boolean', default: false }, 'terminal.integrated.enableFileLinks': { description: nls.localize('terminal.integrated.enableFileLinks', "Whether to enable file links in the terminal. Links can be slow when working on a network drive in particular because each file link is verified against the file system."), type: 'boolean', default: true } } }); const registry = Registry.as<IWorkbenchActionRegistry>(ActionExtensions.WorkbenchActions); registry.registerWorkbenchAction(SyncActionDescriptor.create(QuickOpenTermAction, QuickOpenTermAction.ID, QuickOpenTermAction.LABEL), 'Terminal: Switch Active Terminal', nls.localize('terminal', "Terminal")); const actionBarRegistry = Registry.as<IActionBarRegistry>(ActionBarExtensions.Actionbar); actionBarRegistry.registerActionBarContributor(Scope.VIEWER, QuickOpenActionTermContributor); (<panel.PanelRegistry>Registry.as(panel.Extensions.Panels)).registerPanel(panel.PanelDescriptor.create( TerminalPanel, TERMINAL_PANEL_ID, nls.localize('terminal', "Terminal"), 'terminal', 40, TERMINAL_COMMAND_ID.TOGGLE )); Registry.as<panel.PanelRegistry>(panel.Extensions.Panels).setDefaultPanelId(TERMINAL_PANEL_ID); // On mac cmd+` is reserved to cycle between windows, that's why the keybindings use WinCtrl const category = TERMINAL_ACTION_CATEGORY; const actionRegistry = Registry.as<IWorkbenchActionRegistry>(ActionExtensions.WorkbenchActions); actionRegistry.registerWorkbenchAction(SyncActionDescriptor.create(KillTerminalAction, KillTerminalAction.ID, KillTerminalAction.LABEL), 'Terminal: Kill the Active Terminal Instance', category); actionRegistry.registerWorkbenchAction(SyncActionDescriptor.create(CreateNewTerminalAction, CreateNewTerminalAction.ID, CreateNewTerminalAction.LABEL, { primary: KeyMod.CtrlCmd | KeyMod.Shift | KeyCode.US_BACKTICK, mac: { primary: KeyMod.WinCtrl | KeyMod.Shift | KeyCode.US_BACKTICK } }), 'Terminal: Create New Integrated Terminal', category); actionRegistry.registerWorkbenchAction(SyncActionDescriptor.create(ClearSelectionTerminalAction, ClearSelectionTerminalAction.ID, ClearSelectionTerminalAction.LABEL, { primary: KeyCode.Escape, linux: { primary: KeyCode.Escape } }, ContextKeyExpr.and(KEYBINDING_CONTEXT_TERMINAL_FOCUS, KEYBINDING_CONTEXT_TERMINAL_TEXT_SELECTED, KEYBINDING_CONTEXT_TERMINAL_FIND_WIDGET_NOT_VISIBLE)), 'Terminal: Clear Selection', category); actionRegistry.registerWorkbenchAction(SyncActionDescriptor.create(CreateNewInActiveWorkspaceTerminalAction, CreateNewInActiveWorkspaceTerminalAction.ID, CreateNewInActiveWorkspaceTerminalAction.LABEL), 'Terminal: Create New Integrated Terminal (In Active Workspace)', category); actionRegistry.registerWorkbenchAction(SyncActionDescriptor.create(FocusActiveTerminalAction, FocusActiveTerminalAction.ID, FocusActiveTerminalAction.LABEL), 'Terminal: Focus Terminal', category); actionRegistry.registerWorkbenchAction(SyncActionDescriptor.create(FocusNextTerminalAction, FocusNextTerminalAction.ID, FocusNextTerminalAction.LABEL), 'Terminal: Focus Next Terminal', category); actionRegistry.registerWorkbenchAction(SyncActionDescriptor.create(FocusPreviousTerminalAction, FocusPreviousTerminalAction.ID, FocusPreviousTerminalAction.LABEL), 'Terminal: Focus Previous Terminal', category); actionRegistry.registerWorkbenchAction(SyncActionDescriptor.create(SelectAllTerminalAction, SelectAllTerminalAction.ID, SelectAllTerminalAction.LABEL, { // Don't use ctrl+a by default as that would override the common go to start // of prompt shell binding primary: 0, // Technically this doesn't need to be here as it will fall back to this // behavior anyway when handed to xterm.js, having this handled by VS Code // makes it easier for users to see how it works though. mac: { primary: KeyMod.CtrlCmd | KeyCode.KEY_A } }, KEYBINDING_CONTEXT_TERMINAL_FOCUS), 'Terminal: Select All', category); actionRegistry.registerWorkbenchAction(SyncActionDescriptor.create(RunSelectedTextInTerminalAction, RunSelectedTextInTerminalAction.ID, RunSelectedTextInTerminalAction.LABEL), 'Terminal: Run Selected Text In Active Terminal', category); actionRegistry.registerWorkbenchAction(SyncActionDescriptor.create(RunActiveFileInTerminalAction, RunActiveFileInTerminalAction.ID, RunActiveFileInTerminalAction.LABEL), 'Terminal: Run Active File In Active Terminal', category); actionRegistry.registerWorkbenchAction(SyncActionDescriptor.create(ToggleTerminalAction, ToggleTerminalAction.ID, ToggleTerminalAction.LABEL, { primary: KeyMod.CtrlCmd | KeyCode.US_BACKTICK, mac: { primary: KeyMod.WinCtrl | KeyCode.US_BACKTICK } }), 'View: Toggle Integrated Terminal', nls.localize('viewCategory', "View")); actionRegistry.registerWorkbenchAction(SyncActionDescriptor.create(ScrollDownTerminalAction, ScrollDownTerminalAction.ID, ScrollDownTerminalAction.LABEL, { primary: KeyMod.CtrlCmd | KeyMod.Alt | KeyCode.PageDown, linux: { primary: KeyMod.CtrlCmd | KeyMod.Shift | KeyCode.DownArrow } }, KEYBINDING_CONTEXT_TERMINAL_FOCUS), 'Terminal: Scroll Down (Line)', category); actionRegistry.registerWorkbenchAction(SyncActionDescriptor.create(ScrollDownPageTerminalAction, ScrollDownPageTerminalAction.ID, ScrollDownPageTerminalAction.LABEL, { primary: KeyMod.Shift | KeyCode.PageDown, mac: { primary: KeyCode.PageDown } }, KEYBINDING_CONTEXT_TERMINAL_FOCUS), 'Terminal: Scroll Down (Page)', category); actionRegistry.registerWorkbenchAction(SyncActionDescriptor.create(ScrollToBottomTerminalAction, ScrollToBottomTerminalAction.ID, ScrollToBottomTerminalAction.LABEL, { primary: KeyMod.CtrlCmd | KeyCode.End, linux: { primary: KeyMod.Shift | KeyCode.End } }, KEYBINDING_CONTEXT_TERMINAL_FOCUS), 'Terminal: Scroll to Bottom', category); actionRegistry.registerWorkbenchAction(SyncActionDescriptor.create(ScrollUpTerminalAction, ScrollUpTerminalAction.ID, ScrollUpTerminalAction.LABEL, { primary: KeyMod.CtrlCmd | KeyMod.Alt | KeyCode.PageUp, linux: { primary: KeyMod.CtrlCmd | KeyMod.Shift | KeyCode.UpArrow }, }, KEYBINDING_CONTEXT_TERMINAL_FOCUS), 'Terminal: Scroll Up (Line)', category); actionRegistry.registerWorkbenchAction(SyncActionDescriptor.create(ScrollUpPageTerminalAction, ScrollUpPageTerminalAction.ID, ScrollUpPageTerminalAction.LABEL, { primary: KeyMod.Shift | KeyCode.PageUp, mac: { primary: KeyCode.PageUp } }, KEYBINDING_CONTEXT_TERMINAL_FOCUS), 'Terminal: Scroll Up (Page)', category); actionRegistry.registerWorkbenchAction(SyncActionDescriptor.create(ScrollToTopTerminalAction, ScrollToTopTerminalAction.ID, ScrollToTopTerminalAction.LABEL, { primary: KeyMod.CtrlCmd | KeyCode.Home, linux: { primary: KeyMod.Shift | KeyCode.Home } }, KEYBINDING_CONTEXT_TERMINAL_FOCUS), 'Terminal: Scroll to Top', category); actionRegistry.registerWorkbenchAction(SyncActionDescriptor.create(ClearTerminalAction, ClearTerminalAction.ID, ClearTerminalAction.LABEL, { primary: 0, mac: { primary: KeyMod.CtrlCmd | KeyCode.KEY_K } }, KEYBINDING_CONTEXT_TERMINAL_FOCUS, KeybindingWeight.WorkbenchContrib + 1), 'Terminal: Clear', category); actionRegistry.registerWorkbenchAction(SyncActionDescriptor.create(SelectDefaultShellWindowsTerminalAction, SelectDefaultShellWindowsTerminalAction.ID, SelectDefaultShellWindowsTerminalAction.LABEL), 'Terminal: Select Default Shell', category); actionRegistry.registerWorkbenchAction(SyncActionDescriptor.create(ManageWorkspaceShellPermissionsTerminalCommand, ManageWorkspaceShellPermissionsTerminalCommand.ID, ManageWorkspaceShellPermissionsTerminalCommand.LABEL), 'Terminal: Manage Workspace Shell Permissions', category); actionRegistry.registerWorkbenchAction(SyncActionDescriptor.create(RenameTerminalAction, RenameTerminalAction.ID, RenameTerminalAction.LABEL), 'Terminal: Rename', category); actionRegistry.registerWorkbenchAction(SyncActionDescriptor.create(FocusTerminalFindWidgetAction, FocusTerminalFindWidgetAction.ID, FocusTerminalFindWidgetAction.LABEL, { primary: KeyMod.CtrlCmd | KeyCode.KEY_F }, KEYBINDING_CONTEXT_TERMINAL_FOCUS), 'Terminal: Focus Find Widget', category); actionRegistry.registerWorkbenchAction(SyncActionDescriptor.create(FocusTerminalFindWidgetAction, FocusTerminalFindWidgetAction.ID, FocusTerminalFindWidgetAction.LABEL, { primary: KeyMod.CtrlCmd | KeyCode.KEY_F }, KEYBINDING_CONTEXT_TERMINAL_FIND_WIDGET_FOCUSED), 'Terminal: Focus Find Widget', category); actionRegistry.registerWorkbenchAction(SyncActionDescriptor.create(HideTerminalFindWidgetAction, HideTerminalFindWidgetAction.ID, HideTerminalFindWidgetAction.LABEL, { primary: KeyCode.Escape, secondary: [KeyMod.Shift | KeyCode.Escape] }, ContextKeyExpr.and(KEYBINDING_CONTEXT_TERMINAL_FOCUS, KEYBINDING_CONTEXT_TERMINAL_FIND_WIDGET_VISIBLE)), 'Terminal: Hide Find Widget', category); actionRegistry.registerWorkbenchAction(SyncActionDescriptor.create(DeleteWordLeftTerminalAction, DeleteWordLeftTerminalAction.ID, DeleteWordLeftTerminalAction.LABEL, { primary: KeyMod.CtrlCmd | KeyCode.Backspace, mac: { primary: KeyMod.Alt | KeyCode.Backspace } }, KEYBINDING_CONTEXT_TERMINAL_FOCUS), 'Terminal: Delete Word Left', category); actionRegistry.registerWorkbenchAction(SyncActionDescriptor.create(DeleteWordRightTerminalAction, DeleteWordRightTerminalAction.ID, DeleteWordRightTerminalAction.LABEL, { primary: KeyMod.CtrlCmd | KeyCode.Delete, mac: { primary: KeyMod.Alt | KeyCode.Delete } }, KEYBINDING_CONTEXT_TERMINAL_FOCUS), 'Terminal: Delete Word Right', category); actionRegistry.registerWorkbenchAction(SyncActionDescriptor.create(DeleteToLineStartTerminalAction, DeleteToLineStartTerminalAction.ID, DeleteToLineStartTerminalAction.LABEL, { primary: 0, mac: { primary: KeyMod.CtrlCmd | KeyCode.Backspace } }, KEYBINDING_CONTEXT_TERMINAL_FOCUS), 'Terminal: Delete To Line Start', category); actionRegistry.registerWorkbenchAction(SyncActionDescriptor.create(MoveToLineStartTerminalAction, MoveToLineStartTerminalAction.ID, MoveToLineStartTerminalAction.LABEL, { primary: 0, mac: { primary: KeyMod.CtrlCmd | KeyCode.LeftArrow } }, KEYBINDING_CONTEXT_TERMINAL_FOCUS), 'Terminal: Move To Line Start', category); actionRegistry.registerWorkbenchAction(SyncActionDescriptor.create(MoveToLineEndTerminalAction, MoveToLineEndTerminalAction.ID, MoveToLineEndTerminalAction.LABEL, { primary: 0, mac: { primary: KeyMod.CtrlCmd | KeyCode.RightArrow } }, KEYBINDING_CONTEXT_TERMINAL_FOCUS), 'Terminal: Move To Line End', category); actionRegistry.registerWorkbenchAction(SyncActionDescriptor.create(SplitTerminalAction, SplitTerminalAction.ID, SplitTerminalAction.LABEL, { primary: KeyMod.CtrlCmd | KeyMod.Shift | KeyCode.KEY_5, mac: { primary: KeyMod.CtrlCmd | KeyCode.US_BACKSLASH, secondary: [KeyMod.WinCtrl | KeyMod.Shift | KeyCode.KEY_5] } }, KEYBINDING_CONTEXT_TERMINAL_FOCUS), 'Terminal: Split Terminal', category); actionRegistry.registerWorkbenchAction(SyncActionDescriptor.create(SplitInActiveWorkspaceTerminalAction, SplitInActiveWorkspaceTerminalAction.ID, SplitInActiveWorkspaceTerminalAction.LABEL), 'Terminal: Split Terminal (In Active Workspace)', category); actionRegistry.registerWorkbenchAction(SyncActionDescriptor.create(FocusPreviousPaneTerminalAction, FocusPreviousPaneTerminalAction.ID, FocusPreviousPaneTerminalAction.LABEL, { primary: KeyMod.Alt | KeyCode.LeftArrow, secondary: [KeyMod.Alt | KeyCode.UpArrow], mac: { primary: KeyMod.Alt | KeyMod.CtrlCmd | KeyCode.LeftArrow, secondary: [KeyMod.Alt | KeyMod.CtrlCmd | KeyCode.UpArrow] } }, KEYBINDING_CONTEXT_TERMINAL_FOCUS), 'Terminal: Focus Previous Pane', category); actionRegistry.registerWorkbenchAction(SyncActionDescriptor.create(FocusNextPaneTerminalAction, FocusNextPaneTerminalAction.ID, FocusNextPaneTerminalAction.LABEL, { primary: KeyMod.Alt | KeyCode.RightArrow, secondary: [KeyMod.Alt | KeyCode.DownArrow], mac: { primary: KeyMod.Alt | KeyMod.CtrlCmd | KeyCode.RightArrow, secondary: [KeyMod.Alt | KeyMod.CtrlCmd | KeyCode.DownArrow] } }, KEYBINDING_CONTEXT_TERMINAL_FOCUS), 'Terminal: Focus Next Pane', category); actionRegistry.registerWorkbenchAction(SyncActionDescriptor.create(ResizePaneLeftTerminalAction, ResizePaneLeftTerminalAction.ID, ResizePaneLeftTerminalAction.LABEL, { primary: 0, linux: { primary: KeyMod.CtrlCmd | KeyMod.Shift | KeyCode.LeftArrow }, mac: { primary: KeyMod.CtrlCmd | KeyMod.WinCtrl | KeyCode.LeftArrow } }, KEYBINDING_CONTEXT_TERMINAL_FOCUS), 'Terminal: Resize Pane Left', category); actionRegistry.registerWorkbenchAction(SyncActionDescriptor.create(ResizePaneRightTerminalAction, ResizePaneRightTerminalAction.ID, ResizePaneRightTerminalAction.LABEL, { primary: 0, linux: { primary: KeyMod.CtrlCmd | KeyMod.Shift | KeyCode.RightArrow }, mac: { primary: KeyMod.CtrlCmd | KeyMod.WinCtrl | KeyCode.RightArrow } }, KEYBINDING_CONTEXT_TERMINAL_FOCUS), 'Terminal: Resize Pane Right', category); actionRegistry.registerWorkbenchAction(SyncActionDescriptor.create(ResizePaneUpTerminalAction, ResizePaneUpTerminalAction.ID, ResizePaneUpTerminalAction.LABEL, { primary: 0, mac: { primary: KeyMod.CtrlCmd | KeyMod.WinCtrl | KeyCode.UpArrow } }, KEYBINDING_CONTEXT_TERMINAL_FOCUS), 'Terminal: Resize Pane Up', category); actionRegistry.registerWorkbenchAction(SyncActionDescriptor.create(ResizePaneDownTerminalAction, ResizePaneDownTerminalAction.ID, ResizePaneDownTerminalAction.LABEL, { primary: 0, mac: { primary: KeyMod.CtrlCmd | KeyMod.WinCtrl | KeyCode.DownArrow } }, KEYBINDING_CONTEXT_TERMINAL_FOCUS), 'Terminal: Resize Pane Down', category); actionRegistry.registerWorkbenchAction(SyncActionDescriptor.create(ScrollToPreviousCommandAction, ScrollToPreviousCommandAction.ID, ScrollToPreviousCommandAction.LABEL, { primary: 0, mac: { primary: KeyMod.CtrlCmd | KeyCode.UpArrow } }, ContextKeyExpr.and(KEYBINDING_CONTEXT_TERMINAL_FOCUS, CONTEXT_ACCESSIBILITY_MODE_ENABLED.negate())), 'Terminal: Scroll To Previous Command', category); actionRegistry.registerWorkbenchAction(SyncActionDescriptor.create(ScrollToNextCommandAction, ScrollToNextCommandAction.ID, ScrollToNextCommandAction.LABEL, { primary: 0, mac: { primary: KeyMod.CtrlCmd | KeyCode.DownArrow } }, ContextKeyExpr.and(KEYBINDING_CONTEXT_TERMINAL_FOCUS, CONTEXT_ACCESSIBILITY_MODE_ENABLED.negate())), 'Terminal: Scroll To Next Command', category); actionRegistry.registerWorkbenchAction(SyncActionDescriptor.create(SelectToPreviousCommandAction, SelectToPreviousCommandAction.ID, SelectToPreviousCommandAction.LABEL, { primary: 0, mac: { primary: KeyMod.CtrlCmd | KeyMod.Shift | KeyCode.UpArrow } }, KEYBINDING_CONTEXT_TERMINAL_FOCUS), 'Terminal: Select To Previous Command', category); actionRegistry.registerWorkbenchAction(SyncActionDescriptor.create(SelectToNextCommandAction, SelectToNextCommandAction.ID, SelectToNextCommandAction.LABEL, { primary: 0, mac: { primary: KeyMod.CtrlCmd | KeyMod.Shift | KeyCode.DownArrow } }, KEYBINDING_CONTEXT_TERMINAL_FOCUS), 'Terminal: Select To Next Command', category); actionRegistry.registerWorkbenchAction(SyncActionDescriptor.create(NavigationModeExitTerminalAction, NavigationModeExitTerminalAction.ID, NavigationModeExitTerminalAction.LABEL, { primary: KeyCode.Escape }, ContextKeyExpr.and(KEYBINDING_CONTEXT_TERMINAL_A11Y_TREE_FOCUS, CONTEXT_ACCESSIBILITY_MODE_ENABLED)), 'Terminal: Exit Navigation Mode', category); actionRegistry.registerWorkbenchAction(SyncActionDescriptor.create(NavigationModeFocusPreviousTerminalAction, NavigationModeFocusPreviousTerminalAction.ID, NavigationModeFocusPreviousTerminalAction.LABEL, { primary: KeyMod.CtrlCmd | KeyCode.UpArrow }, ContextKeyExpr.and(KEYBINDING_CONTEXT_TERMINAL_FOCUS, CONTEXT_ACCESSIBILITY_MODE_ENABLED)), 'Terminal: Focus Previous Line (Navigation Mode)', category); actionRegistry.registerWorkbenchAction(SyncActionDescriptor.create(NavigationModeFocusPreviousTerminalAction, NavigationModeFocusPreviousTerminalAction.ID, NavigationModeFocusPreviousTerminalAction.LABEL, { primary: KeyMod.CtrlCmd | KeyCode.UpArrow }, ContextKeyExpr.and(KEYBINDING_CONTEXT_TERMINAL_A11Y_TREE_FOCUS, CONTEXT_ACCESSIBILITY_MODE_ENABLED)), 'Terminal: Focus Previous Line (Navigation Mode)', category); actionRegistry.registerWorkbenchAction(SyncActionDescriptor.create(NavigationModeFocusNextTerminalAction, NavigationModeFocusNextTerminalAction.ID, NavigationModeFocusNextTerminalAction.LABEL, { primary: KeyMod.CtrlCmd | KeyCode.DownArrow }, ContextKeyExpr.and(KEYBINDING_CONTEXT_TERMINAL_FOCUS, CONTEXT_ACCESSIBILITY_MODE_ENABLED)), 'Terminal: Focus Next Line (Navigation Mode)', category); actionRegistry.registerWorkbenchAction(SyncActionDescriptor.create(NavigationModeFocusNextTerminalAction, NavigationModeFocusNextTerminalAction.ID, NavigationModeFocusNextTerminalAction.LABEL, { primary: KeyMod.CtrlCmd | KeyCode.DownArrow }, ContextKeyExpr.and(KEYBINDING_CONTEXT_TERMINAL_A11Y_TREE_FOCUS, CONTEXT_ACCESSIBILITY_MODE_ENABLED)), 'Terminal: Focus Next Line (Navigation Mode)', category); actionRegistry.registerWorkbenchAction(SyncActionDescriptor.create(SelectToPreviousLineAction, SelectToPreviousLineAction.ID, SelectToPreviousLineAction.LABEL), 'Terminal: Select To Previous Line', category); actionRegistry.registerWorkbenchAction(SyncActionDescriptor.create(SelectToNextLineAction, SelectToNextLineAction.ID, SelectToNextLineAction.LABEL), 'Terminal: Select To Next Line', category); actionRegistry.registerWorkbenchAction(SyncActionDescriptor.create(ToggleEscapeSequenceLoggingAction, ToggleEscapeSequenceLoggingAction.ID, ToggleEscapeSequenceLoggingAction.LABEL), 'Terminal: Toggle Escape Sequence Logging', category); actionRegistry.registerWorkbenchAction(SyncActionDescriptor.create(ToggleRegexCommand, ToggleRegexCommand.ID, ToggleRegexCommand.LABEL, { primary: KeyMod.Alt | KeyCode.KEY_R, mac: { primary: KeyMod.CtrlCmd | KeyMod.Alt | KeyCode.KEY_R } }, KEYBINDING_CONTEXT_TERMINAL_FIND_WIDGET_FOCUSED), 'Terminal: Toggle find using regex', category); actionRegistry.registerWorkbenchAction(SyncActionDescriptor.create(ToggleRegexCommand, ToggleRegexCommand.ID, ToggleRegexCommand.LABEL, { primary: KeyMod.Alt | KeyCode.KEY_R, mac: { primary: KeyMod.CtrlCmd | KeyMod.Alt | KeyCode.KEY_R } }, KEYBINDING_CONTEXT_TERMINAL_FOCUS), 'Terminal: Toggle find using regex', category); actionRegistry.registerWorkbenchAction(SyncActionDescriptor.create(ToggleWholeWordCommand, ToggleWholeWordCommand.ID, ToggleWholeWordCommand.LABEL, { primary: KeyMod.Alt | KeyCode.KEY_W, mac: { primary: KeyMod.CtrlCmd | KeyMod.Alt | KeyCode.KEY_W } }, KEYBINDING_CONTEXT_TERMINAL_FIND_WIDGET_FOCUSED), 'Terminal: Toggle find using whole word', category); actionRegistry.registerWorkbenchAction(SyncActionDescriptor.create(ToggleWholeWordCommand, ToggleWholeWordCommand.ID, ToggleWholeWordCommand.LABEL, { primary: KeyMod.Alt | KeyCode.KEY_W, mac: { primary: KeyMod.CtrlCmd | KeyMod.Alt | KeyCode.KEY_W } }, KEYBINDING_CONTEXT_TERMINAL_FOCUS), 'Terminal: Toggle find using whole word', category); actionRegistry.registerWorkbenchAction(SyncActionDescriptor.create(ToggleCaseSensitiveCommand, ToggleCaseSensitiveCommand.ID, ToggleCaseSensitiveCommand.LABEL, { primary: KeyMod.Alt | KeyCode.KEY_C, mac: { primary: KeyMod.CtrlCmd | KeyMod.Alt | KeyCode.KEY_C } }, KEYBINDING_CONTEXT_TERMINAL_FIND_WIDGET_FOCUSED), 'Terminal: Toggle find using case sensitive', category); actionRegistry.registerWorkbenchAction(SyncActionDescriptor.create(ToggleCaseSensitiveCommand, ToggleCaseSensitiveCommand.ID, ToggleCaseSensitiveCommand.LABEL, { primary: KeyMod.Alt | KeyCode.KEY_C, mac: { primary: KeyMod.CtrlCmd | KeyMod.Alt | KeyCode.KEY_C } }, KEYBINDING_CONTEXT_TERMINAL_FOCUS), 'Terminal: Toggle find using case sensitive', category); actionRegistry.registerWorkbenchAction(SyncActionDescriptor.create(FindNext, FindNext.ID, FindNext.LABEL, { primary: KeyCode.F3, mac: { primary: KeyMod.CtrlCmd | KeyCode.KEY_G, secondary: [KeyCode.F3] } }, KEYBINDING_CONTEXT_TERMINAL_FOCUS), 'Terminal: Find next', category); actionRegistry.registerWorkbenchAction(SyncActionDescriptor.create(FindNext, FindNext.ID, FindNext.LABEL, { primary: KeyCode.F3, secondary: [KeyMod.Shift | KeyCode.Enter], mac: { primary: KeyMod.CtrlCmd | KeyCode.KEY_G, secondary: [KeyCode.F3, KeyMod.Shift | KeyCode.Enter] } }, KEYBINDING_CONTEXT_TERMINAL_FIND_WIDGET_FOCUSED), 'Terminal: Find next', category); actionRegistry.registerWorkbenchAction(SyncActionDescriptor.create(FindPrevious, FindPrevious.ID, FindPrevious.LABEL, { primary: KeyMod.Shift | KeyCode.F3, mac: { primary: KeyMod.CtrlCmd | KeyMod.Shift | KeyCode.KEY_G, secondary: [KeyMod.Shift | KeyCode.F3] }, }, KEYBINDING_CONTEXT_TERMINAL_FOCUS), 'Terminal: Find previous', category); actionRegistry.registerWorkbenchAction(SyncActionDescriptor.create(FindPrevious, FindPrevious.ID, FindPrevious.LABEL, { primary: KeyMod.Shift | KeyCode.F3, secondary: [KeyCode.Enter], mac: { primary: KeyMod.CtrlCmd | KeyMod.Shift | KeyCode.KEY_G, secondary: [KeyMod.Shift | KeyCode.F3, KeyCode.Enter] }, }, KEYBINDING_CONTEXT_TERMINAL_FIND_WIDGET_FOCUSED), 'Terminal: Find previous', category); // Commands might be affected by Web restrictons if (BrowserFeatures.clipboard.writeText) { actionRegistry.registerWorkbenchAction(SyncActionDescriptor.create(CopyTerminalSelectionAction, CopyTerminalSelectionAction.ID, CopyTerminalSelectionAction.LABEL, { primary: KeyMod.CtrlCmd | KeyCode.KEY_C, win: { primary: KeyMod.CtrlCmd | KeyCode.KEY_C, secondary: [KeyMod.CtrlCmd | KeyMod.Shift | KeyCode.KEY_C] }, linux: { primary: KeyMod.CtrlCmd | KeyMod.Shift | KeyCode.KEY_C } }, ContextKeyExpr.and(KEYBINDING_CONTEXT_TERMINAL_TEXT_SELECTED, KEYBINDING_CONTEXT_TERMINAL_FOCUS)), 'Terminal: Copy Selection', category); } if (BrowserFeatures.clipboard.readText) { actionRegistry.registerWorkbenchAction(SyncActionDescriptor.create(TerminalPasteAction, TerminalPasteAction.ID, TerminalPasteAction.LABEL, { primary: KeyMod.CtrlCmd | KeyCode.KEY_V, win: { primary: KeyMod.CtrlCmd | KeyCode.KEY_V, secondary: [KeyMod.CtrlCmd | KeyMod.Shift | KeyCode.KEY_V] }, linux: { primary: KeyMod.CtrlCmd | KeyMod.Shift | KeyCode.KEY_V } }, KEYBINDING_CONTEXT_TERMINAL_FOCUS), 'Terminal: Paste into Active Terminal', category); } (new SendSequenceTerminalCommand({ id: SendSequenceTerminalCommand.ID, precondition: undefined, description: { description: SendSequenceTerminalCommand.LABEL, args: [{ name: 'args', schema: { type: 'object', required: ['text'], properties: { text: { type: 'string' } }, } }] } })).register(); (new CreateNewWithCwdTerminalCommand({ id: CreateNewWithCwdTerminalCommand.ID, precondition: undefined, description: { description: CreateNewWithCwdTerminalCommand.LABEL, args: [{ name: 'args', schema: { type: 'object', required: ['cwd'], properties: { cwd: { description: CreateNewWithCwdTerminalCommand.CWD_ARG_LABEL, type: 'string' } }, } }] } })).register(); (new RenameWithArgTerminalCommand({ id: RenameWithArgTerminalCommand.ID, precondition: undefined, description: { description: RenameWithArgTerminalCommand.LABEL, args: [{ name: 'args', schema: { type: 'object', required: ['name'], properties: { name: { description: RenameWithArgTerminalCommand.NAME_ARG_LABEL, type: 'string', minLength: 1 } } } }] } })).register(); setupTerminalCommands(); setupTerminalMenu(); registerColors();
src/vs/workbench/contrib/terminal/browser/terminal.contribution.ts
1
https://github.com/microsoft/vscode/commit/afc57a083c0c4e20ae87cf52b97820f1b43acfc5
[ 0.9914507269859314, 0.030039934441447258, 0.00016212323680520058, 0.0001692770456429571, 0.16877105832099915 ]
{ "id": 3, "code_window": [ "\tmacOptionClickForcesSelection: boolean;\n", "\trendererType: 'auto' | 'canvas' | 'dom' | 'experimentalWebgl';\n", "\trightClickBehavior: 'default' | 'copyPaste' | 'paste' | 'selectWord';\n", "\tcursorBlinking: boolean;\n", "\tcursorStyle: string;\n", "\tdrawBoldTextInBrightColors: boolean;\n", "\tfastScrollSensitivity: number;\n", "\tfontFamily: string;\n", "\tfontWeight: FontWeight;\n", "\tfontWeightBold: FontWeight;\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tcursorBarWidth: number;\n" ], "file_path": "src/vs/workbench/contrib/terminal/common/terminal.ts", "type": "add", "edit_start_line_idx": 93 }
{ "displayName": "HLSL Language Basics", "description": "Provides syntax highlighting and bracket matching in HLSL files." }
extensions/hlsl/package.nls.json
0
https://github.com/microsoft/vscode/commit/afc57a083c0c4e20ae87cf52b97820f1b43acfc5
[ 0.00017303241475019604, 0.00017303241475019604, 0.00017303241475019604, 0.00017303241475019604, 0 ]
{ "id": 3, "code_window": [ "\tmacOptionClickForcesSelection: boolean;\n", "\trendererType: 'auto' | 'canvas' | 'dom' | 'experimentalWebgl';\n", "\trightClickBehavior: 'default' | 'copyPaste' | 'paste' | 'selectWord';\n", "\tcursorBlinking: boolean;\n", "\tcursorStyle: string;\n", "\tdrawBoldTextInBrightColors: boolean;\n", "\tfastScrollSensitivity: number;\n", "\tfontFamily: string;\n", "\tfontWeight: FontWeight;\n", "\tfontWeightBold: FontWeight;\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tcursorBarWidth: number;\n" ], "file_path": "src/vs/workbench/contrib/terminal/common/terminal.ts", "type": "add", "edit_start_line_idx": 93 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ .monaco-toolbar .toolbar-toggle-more { display: inline-block; padding: 0; }
src/vs/base/browser/ui/toolbar/toolbar.css
0
https://github.com/microsoft/vscode/commit/afc57a083c0c4e20ae87cf52b97820f1b43acfc5
[ 0.0001764580374583602, 0.0001764580374583602, 0.0001764580374583602, 0.0001764580374583602, 0 ]
{ "id": 3, "code_window": [ "\tmacOptionClickForcesSelection: boolean;\n", "\trendererType: 'auto' | 'canvas' | 'dom' | 'experimentalWebgl';\n", "\trightClickBehavior: 'default' | 'copyPaste' | 'paste' | 'selectWord';\n", "\tcursorBlinking: boolean;\n", "\tcursorStyle: string;\n", "\tdrawBoldTextInBrightColors: boolean;\n", "\tfastScrollSensitivity: number;\n", "\tfontFamily: string;\n", "\tfontWeight: FontWeight;\n", "\tfontWeightBold: FontWeight;\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tcursorBarWidth: number;\n" ], "file_path": "src/vs/workbench/contrib/terminal/common/terminal.ts", "type": "add", "edit_start_line_idx": 93 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as assert from 'vs/base/common/assert'; import { Emitter, Event } from 'vs/base/common/event'; import { Disposable } from 'vs/base/common/lifecycle'; import * as objects from 'vs/base/common/objects'; import { IDiffEditor } from 'vs/editor/browser/editorBrowser'; import { ICursorPositionChangedEvent } from 'vs/editor/common/controller/cursorEvents'; import { Range } from 'vs/editor/common/core/range'; import { ILineChange, ScrollType } from 'vs/editor/common/editorCommon'; interface IDiffRange { rhs: boolean; range: Range; } export interface Options { followsCaret?: boolean; ignoreCharChanges?: boolean; alwaysRevealFirst?: boolean; } const defaultOptions: Options = { followsCaret: true, ignoreCharChanges: true, alwaysRevealFirst: true }; export interface IDiffNavigator { canNavigate(): boolean; next(): void; previous(): void; dispose(): void; } /** * Create a new diff navigator for the provided diff editor. */ export class DiffNavigator extends Disposable implements IDiffNavigator { private readonly _editor: IDiffEditor; private readonly _options: Options; private readonly _onDidUpdate = this._register(new Emitter<this>()); readonly onDidUpdate: Event<this> = this._onDidUpdate.event; private disposed: boolean; private revealFirst: boolean; private nextIdx: number; private ranges: IDiffRange[]; private ignoreSelectionChange: boolean; constructor(editor: IDiffEditor, options: Options = {}) { super(); this._editor = editor; this._options = objects.mixin(options, defaultOptions, false); this.disposed = false; this.nextIdx = -1; this.ranges = []; this.ignoreSelectionChange = false; this.revealFirst = Boolean(this._options.alwaysRevealFirst); // hook up to diff editor for diff, disposal, and caret move this._register(this._editor.onDidDispose(() => this.dispose())); this._register(this._editor.onDidUpdateDiff(() => this._onDiffUpdated())); if (this._options.followsCaret) { this._register(this._editor.getModifiedEditor().onDidChangeCursorPosition((e: ICursorPositionChangedEvent) => { if (this.ignoreSelectionChange) { return; } this.nextIdx = -1; })); } if (this._options.alwaysRevealFirst) { this._register(this._editor.getModifiedEditor().onDidChangeModel((e) => { this.revealFirst = true; })); } // init things this._init(); } private _init(): void { let changes = this._editor.getLineChanges(); if (!changes) { return; } } private _onDiffUpdated(): void { this._init(); this._compute(this._editor.getLineChanges()); if (this.revealFirst) { // Only reveal first on first non-null changes if (this._editor.getLineChanges() !== null) { this.revealFirst = false; this.nextIdx = -1; this.next(ScrollType.Immediate); } } } private _compute(lineChanges: ILineChange[] | null): void { // new ranges this.ranges = []; if (lineChanges) { // create ranges from changes lineChanges.forEach((lineChange) => { if (!this._options.ignoreCharChanges && lineChange.charChanges) { lineChange.charChanges.forEach((charChange) => { this.ranges.push({ rhs: true, range: new Range( charChange.modifiedStartLineNumber, charChange.modifiedStartColumn, charChange.modifiedEndLineNumber, charChange.modifiedEndColumn) }); }); } else { this.ranges.push({ rhs: true, range: new Range(lineChange.modifiedStartLineNumber, 1, lineChange.modifiedStartLineNumber, 1) }); } }); } // sort this.ranges.sort((left, right) => { if (left.range.getStartPosition().isBeforeOrEqual(right.range.getStartPosition())) { return -1; } else if (right.range.getStartPosition().isBeforeOrEqual(left.range.getStartPosition())) { return 1; } else { return 0; } }); this._onDidUpdate.fire(this); } private _initIdx(fwd: boolean): void { let found = false; let position = this._editor.getPosition(); if (!position) { this.nextIdx = 0; return; } for (let i = 0, len = this.ranges.length; i < len && !found; i++) { let range = this.ranges[i].range; if (position.isBeforeOrEqual(range.getStartPosition())) { this.nextIdx = i + (fwd ? 0 : -1); found = true; } } if (!found) { // after the last change this.nextIdx = fwd ? 0 : this.ranges.length - 1; } if (this.nextIdx < 0) { this.nextIdx = this.ranges.length - 1; } } private _move(fwd: boolean, scrollType: ScrollType): void { assert.ok(!this.disposed, 'Illegal State - diff navigator has been disposed'); if (!this.canNavigate()) { return; } if (this.nextIdx === -1) { this._initIdx(fwd); } else if (fwd) { this.nextIdx += 1; if (this.nextIdx >= this.ranges.length) { this.nextIdx = 0; } } else { this.nextIdx -= 1; if (this.nextIdx < 0) { this.nextIdx = this.ranges.length - 1; } } let info = this.ranges[this.nextIdx]; this.ignoreSelectionChange = true; try { let pos = info.range.getStartPosition(); this._editor.setPosition(pos); this._editor.revealPositionInCenter(pos, scrollType); } finally { this.ignoreSelectionChange = false; } } canNavigate(): boolean { return this.ranges && this.ranges.length > 0; } next(scrollType: ScrollType = ScrollType.Smooth): void { this._move(true, scrollType); } previous(scrollType: ScrollType = ScrollType.Smooth): void { this._move(false, scrollType); } dispose(): void { super.dispose(); this.ranges = []; this.disposed = true; } }
src/vs/editor/browser/widget/diffNavigator.ts
0
https://github.com/microsoft/vscode/commit/afc57a083c0c4e20ae87cf52b97820f1b43acfc5
[ 0.0007380067836493254, 0.00020046174176968634, 0.00016461120685562491, 0.000171999228768982, 0.00011542337597347796 ]
{ "id": 0, "code_window": [ " \"propDescriptions\": {\n", " \"children\": \"The content of the component.\",\n", " \"disableBackdropTransition\": \"Disable the backdrop transition. This can improve the FPS on low-end devices.\",\n", " \"disableDiscovery\": \"If <code>true</code>, touching the screen near the edge of the drawer will not slide in the drawer a bit to promote accidental discovery of the swipe gesture.\",\n", " \"disableSwipeToOpen\": \"If <code>true</code>, swipe to open is disabled. This is useful in browsers where swiping triggers navigation actions. Swipe to open is disabled on iOS browsers by default.\",\n", " \"hysteresis\": \"Affects how far the drawer must be opened/closed to change his state. Specified as percent (0-1) of the width of the drawer\",\n", " \"minFlingVelocity\": \"Defines, from which (average) velocity on, the swipe is defined as complete although hysteresis isn&#39;t reached. Good threshold is between 250 - 1000 px/s\",\n", " \"onClose\": \"Callback fired when the component requests to be closed.<br><br><strong>Signature:</strong><br><code>function(event: object) =&gt; void</code><br><em>event:</em> The event source of the callback.\",\n", " \"onOpen\": \"Callback fired when the component requests to be opened.<br><br><strong>Signature:</strong><br><code>function(event: object) =&gt; void</code><br><em>event:</em> The event source of the callback.\",\n", " \"open\": \"If <code>true</code>, the component is shown.\",\n", " \"SwipeAreaProps\": \"The element is used to intercept the touch events on the edge.\",\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " \"hysteresis\": \"Affects how far the drawer must be opened/closed to change its state. Specified as percent (0-1) of the width of the drawer\",\n" ], "file_path": "docs/translations/api-docs/swipeable-drawer/swipeable-drawer.json", "type": "replace", "edit_start_line_idx": 7 }
import * as React from 'react'; import PropTypes from 'prop-types'; import { elementTypeAcceptingRef } from '@material-ui/utils'; import { getThemeProps } from '@material-ui/styles'; import Drawer, { getAnchor, isHorizontal } from '../Drawer/Drawer'; import ownerDocument from '../utils/ownerDocument'; import ownerWindow from '../utils/ownerWindow'; import useEventCallback from '../utils/useEventCallback'; import useEnhancedEffect from '../utils/useEnhancedEffect'; import { duration } from '../styles/transitions'; import useTheme from '../styles/useTheme'; import { getTransitionProps } from '../transitions/utils'; import NoSsr from '../NoSsr'; import SwipeArea from './SwipeArea'; // This value is closed to what browsers are using internally to // trigger a native scroll. const UNCERTAINTY_THRESHOLD = 3; // px // This is the part of the drawer displayed on touch start. const DRAG_STARTED_SIGNAL = 20; // px // We can only have one instance at the time claiming ownership for handling the swipe. // Otherwise, the UX would be confusing. // That's why we use a singleton here. let claimedSwipeInstance = null; // Exported for test purposes. export function reset() { claimedSwipeInstance = null; } function calculateCurrentX(anchor, touches, doc) { return anchor === 'right' ? doc.body.offsetWidth - touches[0].pageX : touches[0].pageX; } function calculateCurrentY(anchor, touches, containerWindow) { return anchor === 'bottom' ? containerWindow.innerHeight - touches[0].clientY : touches[0].clientY; } function getMaxTranslate(horizontalSwipe, paperInstance) { return horizontalSwipe ? paperInstance.clientWidth : paperInstance.clientHeight; } function getTranslate(currentTranslate, startLocation, open, maxTranslate) { return Math.min( Math.max( open ? startLocation - currentTranslate : maxTranslate + startLocation - currentTranslate, 0, ), maxTranslate, ); } /** * @param {Element | null} element * @param {Element} rootNode */ function getDomTreeShapes(element, rootNode) { // Adapted from https://github.com/oliviertassinari/react-swipeable-views/blob/7666de1dba253b896911adf2790ce51467670856/packages/react-swipeable-views/src/SwipeableViews.js#L129 const domTreeShapes = []; while (element && element !== rootNode.parentElement) { const style = ownerWindow(rootNode).getComputedStyle(element); if ( // Ignore the scroll children if the element is absolute positioned. style.getPropertyValue('position') === 'absolute' || // Ignore the scroll children if the element has an overflowX hidden style.getPropertyValue('overflow-x') === 'hidden' ) { // noop } else if ( (element.clientWidth > 0 && element.scrollWidth > element.clientWidth) || (element.clientHeight > 0 && element.scrollHeight > element.clientHeight) ) { // Ignore the nodes that have no width. // Keep elements with a scroll domTreeShapes.push(element); } element = element.parentElement; } return domTreeShapes; } /** * @param {object} param0 * @param {ReturnType<getDomTreeShapes>} param0.domTreeShapes */ function computeHasNativeHandler({ domTreeShapes, start, current, anchor }) { // Adapted from https://github.com/oliviertassinari/react-swipeable-views/blob/7666de1dba253b896911adf2790ce51467670856/packages/react-swipeable-views/src/SwipeableViews.js#L175 const axisProperties = { scrollPosition: { x: 'scrollLeft', y: 'scrollTop', }, scrollLength: { x: 'scrollWidth', y: 'scrollHeight', }, clientLength: { x: 'clientWidth', y: 'clientHeight', }, }; return domTreeShapes.some((shape) => { // Determine if we are going backward or forward. let goingForward = current >= start; if (anchor === 'top' || anchor === 'left') { goingForward = !goingForward; } const axis = anchor === 'left' || anchor === 'right' ? 'x' : 'y'; const scrollPosition = Math.round(shape[axisProperties.scrollPosition[axis]]); const areNotAtStart = scrollPosition > 0; const areNotAtEnd = scrollPosition + shape[axisProperties.clientLength[axis]] < shape[axisProperties.scrollLength[axis]]; if ((goingForward && areNotAtEnd) || (!goingForward && areNotAtStart)) { return true; } return false; }); } const iOS = typeof navigator !== 'undefined' && /iPad|iPhone|iPod/.test(navigator.userAgent); const transitionDurationDefault = { enter: duration.enteringScreen, exit: duration.leavingScreen }; const SwipeableDrawer = React.forwardRef(function SwipeableDrawer(inProps, ref) { const theme = useTheme(); const props = getThemeProps({ name: 'MuiSwipeableDrawer', props: inProps, theme }); const { anchor = 'left', disableBackdropTransition = false, disableDiscovery = false, disableSwipeToOpen = iOS, hideBackdrop, hysteresis = 0.52, minFlingVelocity = 450, ModalProps: { BackdropProps, ...ModalPropsProp } = {}, onClose, onOpen, open, PaperProps = {}, SwipeAreaProps, swipeAreaWidth = 20, transitionDuration = transitionDurationDefault, variant = 'temporary', // Mobile first. ...other } = props; const [maybeSwiping, setMaybeSwiping] = React.useState(false); const swipeInstance = React.useRef({ isSwiping: null, }); const swipeAreaRef = React.useRef(); const backdropRef = React.useRef(); const paperRef = React.useRef(); const touchDetected = React.useRef(false); // Ref for transition duration based on / to match swipe speed const calculatedDurationRef = React.useRef(); // Use a ref so the open value used is always up to date inside useCallback. useEnhancedEffect(() => { calculatedDurationRef.current = null; }, [open]); const setPosition = React.useCallback( (translate, options = {}) => { const { mode = null, changeTransition = true } = options; const anchorRtl = getAnchor(theme, anchor); const rtlTranslateMultiplier = ['right', 'bottom'].indexOf(anchorRtl) !== -1 ? 1 : -1; const horizontalSwipe = isHorizontal(anchor); const transform = horizontalSwipe ? `translate(${rtlTranslateMultiplier * translate}px, 0)` : `translate(0, ${rtlTranslateMultiplier * translate}px)`; const drawerStyle = paperRef.current.style; drawerStyle.webkitTransform = transform; drawerStyle.transform = transform; let transition = ''; if (mode) { transition = theme.transitions.create( 'all', getTransitionProps( { timeout: transitionDuration, }, { mode, }, ), ); } if (changeTransition) { drawerStyle.webkitTransition = transition; drawerStyle.transition = transition; } if (!disableBackdropTransition && !hideBackdrop) { const backdropStyle = backdropRef.current.style; backdropStyle.opacity = 1 - translate / getMaxTranslate(horizontalSwipe, paperRef.current); if (changeTransition) { backdropStyle.webkitTransition = transition; backdropStyle.transition = transition; } } }, [anchor, disableBackdropTransition, hideBackdrop, theme, transitionDuration], ); const handleBodyTouchEnd = useEventCallback((nativeEvent) => { if (!touchDetected.current) { return; } claimedSwipeInstance = null; touchDetected.current = false; setMaybeSwiping(false); // The swipe wasn't started. if (!swipeInstance.current.isSwiping) { swipeInstance.current.isSwiping = null; return; } swipeInstance.current.isSwiping = null; const anchorRtl = getAnchor(theme, anchor); const horizontal = isHorizontal(anchor); let current; if (horizontal) { current = calculateCurrentX( anchorRtl, nativeEvent.changedTouches, ownerDocument(nativeEvent.currentTarget), ); } else { current = calculateCurrentY( anchorRtl, nativeEvent.changedTouches, ownerWindow(nativeEvent.currentTarget), ); } const startLocation = horizontal ? swipeInstance.current.startX : swipeInstance.current.startY; const maxTranslate = getMaxTranslate(horizontal, paperRef.current); const currentTranslate = getTranslate(current, startLocation, open, maxTranslate); const translateRatio = currentTranslate / maxTranslate; if (Math.abs(swipeInstance.current.velocity) > minFlingVelocity) { // Calculate transition duration to match swipe speed calculatedDurationRef.current = Math.abs((maxTranslate - currentTranslate) / swipeInstance.current.velocity) * 1000; } if (open) { if (swipeInstance.current.velocity > minFlingVelocity || translateRatio > hysteresis) { onClose(); } else { // Reset the position, the swipe was aborted. setPosition(0, { mode: 'exit', }); } return; } if (swipeInstance.current.velocity < -minFlingVelocity || 1 - translateRatio > hysteresis) { onOpen(); } else { // Reset the position, the swipe was aborted. setPosition(getMaxTranslate(horizontal, paperRef.current), { mode: 'enter', }); } }); const handleBodyTouchMove = useEventCallback((nativeEvent) => { // the ref may be null when a parent component updates while swiping if (!paperRef.current || !touchDetected.current) { return; } // We are not supposed to handle this touch move because the swipe was started in a scrollable container in the drawer if (claimedSwipeInstance !== null && claimedSwipeInstance !== swipeInstance.current) { return; } const anchorRtl = getAnchor(theme, anchor); const horizontalSwipe = isHorizontal(anchor); const currentX = calculateCurrentX( anchorRtl, nativeEvent.touches, ownerDocument(nativeEvent.currentTarget), ); const currentY = calculateCurrentY( anchorRtl, nativeEvent.touches, ownerWindow(nativeEvent.currentTarget), ); if (open && paperRef.current.contains(nativeEvent.target) && claimedSwipeInstance === null) { const domTreeShapes = getDomTreeShapes(nativeEvent.target, paperRef.current); const hasNativeHandler = computeHasNativeHandler({ domTreeShapes, start: horizontalSwipe ? swipeInstance.current.startX : swipeInstance.current.startY, current: horizontalSwipe ? currentX : currentY, anchor, }); if (hasNativeHandler) { claimedSwipeInstance = true; return; } claimedSwipeInstance = swipeInstance.current; } // We don't know yet. if (swipeInstance.current.isSwiping == null) { const dx = Math.abs(currentX - swipeInstance.current.startX); const dy = Math.abs(currentY - swipeInstance.current.startY); const definitelySwiping = horizontalSwipe ? dx > dy && dx > UNCERTAINTY_THRESHOLD : dy > dx && dy > UNCERTAINTY_THRESHOLD; if (definitelySwiping && nativeEvent.cancelable) { nativeEvent.preventDefault(); } if ( definitelySwiping === true || (horizontalSwipe ? dy > UNCERTAINTY_THRESHOLD : dx > UNCERTAINTY_THRESHOLD) ) { swipeInstance.current.isSwiping = definitelySwiping; if (!definitelySwiping) { handleBodyTouchEnd(nativeEvent); return; } // Shift the starting point. swipeInstance.current.startX = currentX; swipeInstance.current.startY = currentY; // Compensate for the part of the drawer displayed on touch start. if (!disableDiscovery && !open) { if (horizontalSwipe) { swipeInstance.current.startX -= DRAG_STARTED_SIGNAL; } else { swipeInstance.current.startY -= DRAG_STARTED_SIGNAL; } } } } if (!swipeInstance.current.isSwiping) { return; } const maxTranslate = getMaxTranslate(horizontalSwipe, paperRef.current); let startLocation = horizontalSwipe ? swipeInstance.current.startX : swipeInstance.current.startY; if (open && !swipeInstance.current.paperHit) { startLocation = Math.min(startLocation, maxTranslate); } const translate = getTranslate( horizontalSwipe ? currentX : currentY, startLocation, open, maxTranslate, ); if (open) { if (!swipeInstance.current.paperHit) { const paperHit = horizontalSwipe ? currentX < maxTranslate : currentY < maxTranslate; if (paperHit) { swipeInstance.current.paperHit = true; swipeInstance.current.startX = currentX; swipeInstance.current.startY = currentY; } else { return; } } else if (translate === 0) { swipeInstance.current.startX = currentX; swipeInstance.current.startY = currentY; } } if (swipeInstance.current.lastTranslate === null) { swipeInstance.current.lastTranslate = translate; swipeInstance.current.lastTime = performance.now() + 1; } const velocity = ((translate - swipeInstance.current.lastTranslate) / (performance.now() - swipeInstance.current.lastTime)) * 1e3; // Low Pass filter. swipeInstance.current.velocity = swipeInstance.current.velocity * 0.4 + velocity * 0.6; swipeInstance.current.lastTranslate = translate; swipeInstance.current.lastTime = performance.now(); // We are swiping, let's prevent the scroll event on iOS. if (nativeEvent.cancelable) { nativeEvent.preventDefault(); } setPosition(translate); }); const handleBodyTouchStart = useEventCallback((nativeEvent) => { // We are not supposed to handle this touch move. // Example of use case: ignore the event if there is a Slider. if (nativeEvent.defaultPrevented) { return; } // We can only have one node at the time claiming ownership for handling the swipe. if (nativeEvent.defaultMuiPrevented) { return; } // At least one element clogs the drawer interaction zone. if ( open && (hideBackdrop || !backdropRef.current.contains(nativeEvent.target)) && !paperRef.current.contains(nativeEvent.target) ) { return; } const anchorRtl = getAnchor(theme, anchor); const horizontalSwipe = isHorizontal(anchor); const currentX = calculateCurrentX( anchorRtl, nativeEvent.touches, ownerDocument(nativeEvent.currentTarget), ); const currentY = calculateCurrentY( anchorRtl, nativeEvent.touches, ownerWindow(nativeEvent.currentTarget), ); if (!open) { if (disableSwipeToOpen || nativeEvent.target !== swipeAreaRef.current) { return; } if (horizontalSwipe) { if (currentX > swipeAreaWidth) { return; } } else if (currentY > swipeAreaWidth) { return; } } nativeEvent.defaultMuiPrevented = true; claimedSwipeInstance = null; swipeInstance.current.startX = currentX; swipeInstance.current.startY = currentY; setMaybeSwiping(true); if (!open && paperRef.current) { // The ref may be null when a parent component updates while swiping. setPosition( getMaxTranslate(horizontalSwipe, paperRef.current) + (disableDiscovery ? 15 : -DRAG_STARTED_SIGNAL), { changeTransition: false, }, ); } swipeInstance.current.velocity = 0; swipeInstance.current.lastTime = null; swipeInstance.current.lastTranslate = null; swipeInstance.current.paperHit = false; touchDetected.current = true; }); React.useEffect(() => { if (variant === 'temporary') { const doc = ownerDocument(paperRef.current); doc.addEventListener('touchstart', handleBodyTouchStart); // A blocking listener prevents Firefox's navbar to auto-hide on scroll. // It only needs to prevent scrolling on the drawer's content when open. // When closed, the overlay prevents scrolling. doc.addEventListener('touchmove', handleBodyTouchMove, { passive: !open }); doc.addEventListener('touchend', handleBodyTouchEnd); return () => { doc.removeEventListener('touchstart', handleBodyTouchStart); doc.removeEventListener('touchmove', handleBodyTouchMove, { passive: !open }); doc.removeEventListener('touchend', handleBodyTouchEnd); }; } return undefined; }, [variant, open, handleBodyTouchStart, handleBodyTouchMove, handleBodyTouchEnd]); React.useEffect( () => () => { // We need to release the lock. if (claimedSwipeInstance === swipeInstance.current) { claimedSwipeInstance = null; } }, [], ); React.useEffect(() => { if (!open) { setMaybeSwiping(false); } }, [open]); return ( <React.Fragment> <Drawer open={variant === 'temporary' && maybeSwiping ? true : open} variant={variant} ModalProps={{ BackdropProps: { ...BackdropProps, ref: backdropRef, }, ...ModalPropsProp, }} hideBackdrop={hideBackdrop} PaperProps={{ ...PaperProps, style: { pointerEvents: variant === 'temporary' && !open ? 'none' : '', ...PaperProps.style, }, ref: paperRef, }} anchor={anchor} transitionDuration={calculatedDurationRef.current || transitionDuration} onClose={onClose} ref={ref} {...other} /> {!disableSwipeToOpen && variant === 'temporary' && ( <NoSsr> <SwipeArea anchor={anchor} ref={swipeAreaRef} width={swipeAreaWidth} {...SwipeAreaProps} /> </NoSsr> )} </React.Fragment> ); }); SwipeableDrawer.propTypes /* remove-proptypes */ = { // ----------------------------- Warning -------------------------------- // | These PropTypes are generated from the TypeScript type definitions | // | To update them edit the d.ts file and run "yarn proptypes" | // ---------------------------------------------------------------------- /** * @ignore */ anchor: PropTypes.oneOf(['bottom', 'left', 'right', 'top']), /** * The content of the component. */ children: PropTypes.node, /** * Disable the backdrop transition. * This can improve the FPS on low-end devices. * @default false */ disableBackdropTransition: PropTypes.bool, /** * If `true`, touching the screen near the edge of the drawer will not slide in the drawer a bit * to promote accidental discovery of the swipe gesture. * @default false */ disableDiscovery: PropTypes.bool, /** * If `true`, swipe to open is disabled. This is useful in browsers where swiping triggers * navigation actions. Swipe to open is disabled on iOS browsers by default. * @default typeof navigator !== 'undefined' && /iPad|iPhone|iPod/.test(navigator.userAgent) */ disableSwipeToOpen: PropTypes.bool, /** * @ignore */ hideBackdrop: PropTypes.bool, /** * Affects how far the drawer must be opened/closed to change his state. * Specified as percent (0-1) of the width of the drawer * @default 0.52 */ hysteresis: PropTypes.number, /** * Defines, from which (average) velocity on, the swipe is * defined as complete although hysteresis isn't reached. * Good threshold is between 250 - 1000 px/s * @default 450 */ minFlingVelocity: PropTypes.number, /** * @ignore */ ModalProps: PropTypes /* @typescript-to-proptypes-ignore */.shape({ BackdropProps: PropTypes.shape({ component: elementTypeAcceptingRef, }), }), /** * Callback fired when the component requests to be closed. * * @param {object} event The event source of the callback. */ onClose: PropTypes.func.isRequired, /** * Callback fired when the component requests to be opened. * * @param {object} event The event source of the callback. */ onOpen: PropTypes.func.isRequired, /** * If `true`, the component is shown. */ open: PropTypes.bool.isRequired, /** * @ignore */ PaperProps: PropTypes /* @typescript-to-proptypes-ignore */.shape({ component: elementTypeAcceptingRef, style: PropTypes.object, }), /** * The element is used to intercept the touch events on the edge. */ SwipeAreaProps: PropTypes.object, /** * The width of the left most (or right most) area in `px` that * the drawer can be swiped open from. * @default 20 */ swipeAreaWidth: PropTypes.number, /** * The duration for the transition, in milliseconds. * You may specify a single timeout for all transitions, or individually with an object. * @default { enter: duration.enteringScreen, exit: duration.leavingScreen } */ transitionDuration: PropTypes.oneOfType([ PropTypes.number, PropTypes.shape({ appear: PropTypes.number, enter: PropTypes.number, exit: PropTypes.number, }), ]), /** * @ignore */ variant: PropTypes.oneOf(['permanent', 'persistent', 'temporary']), }; export default SwipeableDrawer;
packages/material-ui/src/SwipeableDrawer/SwipeableDrawer.js
1
https://github.com/mui/material-ui/commit/2870aa6251ed7a114a16c8b94ff4c41ce0358dcf
[ 0.2108813375234604, 0.0057870373129844666, 0.00016005104407668114, 0.0011037868680432439, 0.025037091225385666 ]
{ "id": 0, "code_window": [ " \"propDescriptions\": {\n", " \"children\": \"The content of the component.\",\n", " \"disableBackdropTransition\": \"Disable the backdrop transition. This can improve the FPS on low-end devices.\",\n", " \"disableDiscovery\": \"If <code>true</code>, touching the screen near the edge of the drawer will not slide in the drawer a bit to promote accidental discovery of the swipe gesture.\",\n", " \"disableSwipeToOpen\": \"If <code>true</code>, swipe to open is disabled. This is useful in browsers where swiping triggers navigation actions. Swipe to open is disabled on iOS browsers by default.\",\n", " \"hysteresis\": \"Affects how far the drawer must be opened/closed to change his state. Specified as percent (0-1) of the width of the drawer\",\n", " \"minFlingVelocity\": \"Defines, from which (average) velocity on, the swipe is defined as complete although hysteresis isn&#39;t reached. Good threshold is between 250 - 1000 px/s\",\n", " \"onClose\": \"Callback fired when the component requests to be closed.<br><br><strong>Signature:</strong><br><code>function(event: object) =&gt; void</code><br><em>event:</em> The event source of the callback.\",\n", " \"onOpen\": \"Callback fired when the component requests to be opened.<br><br><strong>Signature:</strong><br><code>function(event: object) =&gt; void</code><br><em>event:</em> The event source of the callback.\",\n", " \"open\": \"If <code>true</code>, the component is shown.\",\n", " \"SwipeAreaProps\": \"The element is used to intercept the touch events on the edge.\",\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " \"hysteresis\": \"Affects how far the drawer must be opened/closed to change its state. Specified as percent (0-1) of the width of the drawer\",\n" ], "file_path": "docs/translations/api-docs/swipeable-drawer/swipeable-drawer.json", "type": "replace", "edit_start_line_idx": 7 }
import * as React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <path d="M24 8.98C20.93 5.9 16.69 4 12 4S3.07 5.9 0 8.98L12 21v-9h8.99L24 8.98zM19.59 14l-2.09 2.09-.3-.3L15.41 14 14 15.41l1.79 1.79.3.3L14 19.59 15.41 21l2.09-2.08L19.59 21 21 19.59l-2.08-2.09L21 15.41 19.59 14z" /> , 'SignalWifiBadOutlined');
packages/material-ui-icons/src/SignalWifiBadOutlined.js
0
https://github.com/mui/material-ui/commit/2870aa6251ed7a114a16c8b94ff4c41ce0358dcf
[ 0.00016482544015161693, 0.00016482544015161693, 0.00016482544015161693, 0.00016482544015161693, 0 ]
{ "id": 0, "code_window": [ " \"propDescriptions\": {\n", " \"children\": \"The content of the component.\",\n", " \"disableBackdropTransition\": \"Disable the backdrop transition. This can improve the FPS on low-end devices.\",\n", " \"disableDiscovery\": \"If <code>true</code>, touching the screen near the edge of the drawer will not slide in the drawer a bit to promote accidental discovery of the swipe gesture.\",\n", " \"disableSwipeToOpen\": \"If <code>true</code>, swipe to open is disabled. This is useful in browsers where swiping triggers navigation actions. Swipe to open is disabled on iOS browsers by default.\",\n", " \"hysteresis\": \"Affects how far the drawer must be opened/closed to change his state. Specified as percent (0-1) of the width of the drawer\",\n", " \"minFlingVelocity\": \"Defines, from which (average) velocity on, the swipe is defined as complete although hysteresis isn&#39;t reached. Good threshold is between 250 - 1000 px/s\",\n", " \"onClose\": \"Callback fired when the component requests to be closed.<br><br><strong>Signature:</strong><br><code>function(event: object) =&gt; void</code><br><em>event:</em> The event source of the callback.\",\n", " \"onOpen\": \"Callback fired when the component requests to be opened.<br><br><strong>Signature:</strong><br><code>function(event: object) =&gt; void</code><br><em>event:</em> The event source of the callback.\",\n", " \"open\": \"If <code>true</code>, the component is shown.\",\n", " \"SwipeAreaProps\": \"The element is used to intercept the touch events on the edge.\",\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " \"hysteresis\": \"Affects how far the drawer must be opened/closed to change its state. Specified as percent (0-1) of the width of the drawer\",\n" ], "file_path": "docs/translations/api-docs/swipeable-drawer/swipeable-drawer.json", "type": "replace", "edit_start_line_idx": 7 }
import * as React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <path d="M20 13H3c-.55 0-1 .45-1 1v6c0 .55.45 1 1 1h17c.55 0 1-.45 1-1v-6c0-.55-.45-1-1-1zm0-10H3c-.55 0-1 .45-1 1v6c0 .55.45 1 1 1h17c.55 0 1-.45 1-1V4c0-.55-.45-1-1-1z" /> , 'ViewAgenda');
packages/material-ui-icons/src/ViewAgenda.js
0
https://github.com/mui/material-ui/commit/2870aa6251ed7a114a16c8b94ff4c41ce0358dcf
[ 0.0001644050789764151, 0.0001644050789764151, 0.0001644050789764151, 0.0001644050789764151, 0 ]
{ "id": 0, "code_window": [ " \"propDescriptions\": {\n", " \"children\": \"The content of the component.\",\n", " \"disableBackdropTransition\": \"Disable the backdrop transition. This can improve the FPS on low-end devices.\",\n", " \"disableDiscovery\": \"If <code>true</code>, touching the screen near the edge of the drawer will not slide in the drawer a bit to promote accidental discovery of the swipe gesture.\",\n", " \"disableSwipeToOpen\": \"If <code>true</code>, swipe to open is disabled. This is useful in browsers where swiping triggers navigation actions. Swipe to open is disabled on iOS browsers by default.\",\n", " \"hysteresis\": \"Affects how far the drawer must be opened/closed to change his state. Specified as percent (0-1) of the width of the drawer\",\n", " \"minFlingVelocity\": \"Defines, from which (average) velocity on, the swipe is defined as complete although hysteresis isn&#39;t reached. Good threshold is between 250 - 1000 px/s\",\n", " \"onClose\": \"Callback fired when the component requests to be closed.<br><br><strong>Signature:</strong><br><code>function(event: object) =&gt; void</code><br><em>event:</em> The event source of the callback.\",\n", " \"onOpen\": \"Callback fired when the component requests to be opened.<br><br><strong>Signature:</strong><br><code>function(event: object) =&gt; void</code><br><em>event:</em> The event source of the callback.\",\n", " \"open\": \"If <code>true</code>, the component is shown.\",\n", " \"SwipeAreaProps\": \"The element is used to intercept the touch events on the edge.\",\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " \"hysteresis\": \"Affects how far the drawer must be opened/closed to change its state. Specified as percent (0-1) of the width of the drawer\",\n" ], "file_path": "docs/translations/api-docs/swipeable-drawer/swipeable-drawer.json", "type": "replace", "edit_start_line_idx": 7 }
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><path d="M391.1 179.9l-24.18-24.19a16.46 16.46 0 0 0-11.71-4.85c-4.43 0-8.59 1.72-11.72 4.85l-.38.38-73.31-73.32.38-.38c3.13-3.12 4.85-7.29 4.85-11.71s-1.72-8.59-4.85-11.72l-24.19-24.18a16.59 16.59 0 0 0-23.43 0L162.1 95.24a16.59 16.59 0 0 0 0 23.43l24.18 24.19a16.59 16.59 0 0 0 23.43 0l.38-.38 12.85 12.85-12.47 12.47a16.46 16.46 0 0 0-4.2 16.3L7.35 383A24.95 24.95 0 0 0 0 400.76c0 6.71 2.61 13.02 7.36 17.77a25.04 25.04 0 0 0 17.76 7.34c6.43 0 12.86-2.45 17.76-7.34l198.9-198.9c1.48.41 3.01.64 4.59.64 4.42 0 8.58-1.72 11.71-4.85l12.47-12.47 12.85 12.85-.37.37a16.46 16.46 0 0 0-4.86 11.72c0 4.42 1.72 8.58 4.85 11.71l24.19 24.19c3.13 3.13 7.29 4.85 11.72 4.85s8.58-1.72 11.71-4.85l60.47-60.47c3.13-3.12 4.85-7.28 4.85-11.71s-1.72-8.59-4.85-11.71zM31.55 407.19a9.1 9.1 0 0 1-15.5-6.43c0-2.42.94-4.7 2.65-6.42L216.13 196.9l12.85 12.85L31.54 407.19zm215.2-203.1c-.03.03-.15.15-.37.15s-.34-.12-.38-.16L221.8 179.9c-.04-.03-.15-.15-.15-.37s.11-.34.15-.38l12.47-12.47 24.95 24.94-12.48 12.47zm133.03-12.1l-60.47 60.46c-.04.04-.15.16-.37.16s-.34-.12-.38-.16l-24.19-24.18c-.04-.04-.15-.16-.15-.38s.11-.34.15-.38l6.05-6.05a8.02 8.02 0 0 0 0-11.33l-78.98-78.99 18.51-18.51a8.02 8.02 0 1 0-11.33-11.34l-30.24 30.23c-.2.21-.54.21-.75 0l-24.19-24.18a.54.54 0 0 1 0-.76l60.47-60.46c.2-.21.54-.21.75 0l24.19 24.18c.2.2.2.55 0 .76l-6.02 6.01-.13.14a8.02 8.02 0 0 0 .1 11.23l78.99 78.99-18.52 18.51a8 8 0 0 0 0 11.34 8.02 8.02 0 0 0 11.33 0l30.24-30.23c.04-.04.15-.16.38-.16s.34.12.37.16l24.19 24.18c.04.04.16.16.16.38s-.12.34-.16.38zM511.76 472.1l-5.31-21.24a25.08 25.08 0 0 0-24.37-19.03h-4.28v-17.64c0-9.13-7.44-16.57-16.57-16.57H341.5a16.59 16.59 0 0 0-16.57 16.57v17.64h-4.28a25.08 25.08 0 0 0-24.37 19.03l-5.31 21.25a8.01 8.01 0 0 0 7.78 9.96h205.22a8.02 8.02 0 0 0 7.78-9.96zm-202.74-6.07l2.83-11.29a9.07 9.07 0 0 1 8.8-6.88h29.41a8.02 8.02 0 0 0 0-16.03h-9.08v-17.64c0-.3.24-.53.53-.53h119.72c.3 0 .53.23.53.53v17.64h-77.5a8.02 8.02 0 0 0 0 16.03h97.82c4.17 0 7.8 2.83 8.81 6.88l2.82 11.3H309.02zM401.37 320.66a8.02 8.02 0 0 0-8.02 8.02v42.76a8.02 8.02 0 0 0 16.04 0v-42.76a8.02 8.02 0 0 0-8.02-8.02zM447.71 347.16a8.02 8.02 0 0 0-10.76 3.59l-8.55 17.1a8.02 8.02 0 1 0 14.35 7.17l8.55-17.1a8.02 8.02 0 0 0-3.59-10.76zM374.33 367.85l-8.55-17.1a8.01 8.01 0 1 0-14.34 7.17l8.56 17.1a8.02 8.02 0 1 0 14.33-7.17z"/></svg>
docs/public/static/themes/onepirate/productHowItWorks1.svg
0
https://github.com/mui/material-ui/commit/2870aa6251ed7a114a16c8b94ff4c41ce0358dcf
[ 0.00016070279525592923, 0.00016070279525592923, 0.00016070279525592923, 0.00016070279525592923, 0 ]
{ "id": 1, "code_window": [ " * navigation actions. Swipe to open is disabled on iOS browsers by default.\n", " * @default typeof navigator !== 'undefined' && /iPad|iPhone|iPod/.test(navigator.userAgent)\n", " */\n", " disableSwipeToOpen?: boolean;\n", " /**\n", " * Affects how far the drawer must be opened/closed to change his state.\n", " * Specified as percent (0-1) of the width of the drawer\n", " * @default 0.52\n", " */\n", " hysteresis?: number;\n", " /**\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " * Affects how far the drawer must be opened/closed to change its state.\n" ], "file_path": "packages/material-ui/src/SwipeableDrawer/SwipeableDrawer.d.ts", "type": "replace", "edit_start_line_idx": 23 }
import * as React from 'react'; import { DrawerProps } from '../Drawer'; export interface SwipeableDrawerProps extends Omit<DrawerProps, 'onClose' | 'open'> { /** * Disable the backdrop transition. * This can improve the FPS on low-end devices. * @default false */ disableBackdropTransition?: boolean; /** * If `true`, touching the screen near the edge of the drawer will not slide in the drawer a bit * to promote accidental discovery of the swipe gesture. * @default false */ disableDiscovery?: boolean; /** * If `true`, swipe to open is disabled. This is useful in browsers where swiping triggers * navigation actions. Swipe to open is disabled on iOS browsers by default. * @default typeof navigator !== 'undefined' && /iPad|iPhone|iPod/.test(navigator.userAgent) */ disableSwipeToOpen?: boolean; /** * Affects how far the drawer must be opened/closed to change his state. * Specified as percent (0-1) of the width of the drawer * @default 0.52 */ hysteresis?: number; /** * Defines, from which (average) velocity on, the swipe is * defined as complete although hysteresis isn't reached. * Good threshold is between 250 - 1000 px/s * @default 450 */ minFlingVelocity?: number; /** * Callback fired when the component requests to be closed. * * @param {object} event The event source of the callback. */ onClose: React.ReactEventHandler<{}>; /** * Callback fired when the component requests to be opened. * * @param {object} event The event source of the callback. */ onOpen: React.ReactEventHandler<{}>; /** * If `true`, the component is shown. */ open: boolean; /** * The element is used to intercept the touch events on the edge. */ SwipeAreaProps?: object; /** * The width of the left most (or right most) area in `px` that * the drawer can be swiped open from. * @default 20 */ swipeAreaWidth?: number; } /** * * Demos: * * - [Drawers](https://material-ui.com/components/drawers/) * * API: * * - [SwipeableDrawer API](https://material-ui.com/api/swipeable-drawer/) * - inherits [Drawer API](https://material-ui.com/api/drawer/) */ declare const SwipeableDrawer: React.ComponentType<SwipeableDrawerProps>; export default SwipeableDrawer;
packages/material-ui/src/SwipeableDrawer/SwipeableDrawer.d.ts
1
https://github.com/mui/material-ui/commit/2870aa6251ed7a114a16c8b94ff4c41ce0358dcf
[ 0.9969481825828552, 0.13227148354053497, 0.0001610235485713929, 0.0019254665821790695, 0.3271479606628418 ]
{ "id": 1, "code_window": [ " * navigation actions. Swipe to open is disabled on iOS browsers by default.\n", " * @default typeof navigator !== 'undefined' && /iPad|iPhone|iPod/.test(navigator.userAgent)\n", " */\n", " disableSwipeToOpen?: boolean;\n", " /**\n", " * Affects how far the drawer must be opened/closed to change his state.\n", " * Specified as percent (0-1) of the width of the drawer\n", " * @default 0.52\n", " */\n", " hysteresis?: number;\n", " /**\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " * Affects how far the drawer must be opened/closed to change its state.\n" ], "file_path": "packages/material-ui/src/SwipeableDrawer/SwipeableDrawer.d.ts", "type": "replace", "edit_start_line_idx": 23 }
import * as React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <React.Fragment><path d="M15 14h1.5v1.5H15z" /><path d="M19 3H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zM6.5 9c0-.55.45-1 1-1h2V7H7.25c-.41 0-.75-.34-.75-.75s.34-.75.75-.75H10c.55 0 1 .45 1 1V8c0 .55-.45 1-1 1H8v1h2.25c.41 0 .75.34.75.75s-.34.75-.75.75H7.5c-.55 0-1-.45-1-1V9zm6 8.75c0 .41-.34.75-.75.75s-.75-.34-.75-.75V14h-1v2.25c0 .41-.34.75-.75.75s-.75-.34-.75-.75V14h-1v3.75c0 .41-.34.75-.75.75S6 18.16 6 17.75V13.5c0-.55.45-1 1-1h4.5c.55 0 1 .45 1 1v4.25zm.5-7.25V9c0-.55.45-1 1-1h2V7h-2.25c-.41 0-.75-.34-.75-.75s.34-.75.75-.75h2.75c.55 0 1 .45 1 1V8c0 .55-.45 1-1 1h-2v1h2.25c.41 0 .75.34.75.75s-.34.75-.75.75H14c-.55 0-1-.45-1-1zm5 5.5c0 .55-.45 1-1 1h-2v.75c0 .41-.34.75-.75.75s-.75-.34-.75-.75V13.5c0-.55.45-1 1-1H17c.55 0 1 .45 1 1V16z" /></React.Fragment> , 'TwentyTwoMpRounded');
packages/material-ui-icons/src/TwentyTwoMpRounded.js
0
https://github.com/mui/material-ui/commit/2870aa6251ed7a114a16c8b94ff4c41ce0358dcf
[ 0.00019210089521948248, 0.00019210089521948248, 0.00019210089521948248, 0.00019210089521948248, 0 ]
{ "id": 1, "code_window": [ " * navigation actions. Swipe to open is disabled on iOS browsers by default.\n", " * @default typeof navigator !== 'undefined' && /iPad|iPhone|iPod/.test(navigator.userAgent)\n", " */\n", " disableSwipeToOpen?: boolean;\n", " /**\n", " * Affects how far the drawer must be opened/closed to change his state.\n", " * Specified as percent (0-1) of the width of the drawer\n", " * @default 0.52\n", " */\n", " hysteresis?: number;\n", " /**\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " * Affects how far the drawer must be opened/closed to change its state.\n" ], "file_path": "packages/material-ui/src/SwipeableDrawer/SwipeableDrawer.d.ts", "type": "replace", "edit_start_line_idx": 23 }
import * as React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <path d="M3 22c-.55 0-1-.45-1-1V3c0-.55.45-1 1-1s1 .45 1 1v18c0 .55-.45 1-1 1zM20.5 7h-13C6.67 7 6 7.67 6 8.5S6.67 10 7.5 10h13c.83 0 1.5-.67 1.5-1.5S21.33 7 20.5 7zm-6 7h-7c-.83 0-1.5.67-1.5 1.5S6.67 17 7.5 17h7c.83 0 1.5-.67 1.5-1.5s-.67-1.5-1.5-1.5z" /> , 'AlignHorizontalLeftRounded');
packages/material-ui-icons/src/AlignHorizontalLeftRounded.js
0
https://github.com/mui/material-ui/commit/2870aa6251ed7a114a16c8b94ff4c41ce0358dcf
[ 0.00017718605522532016, 0.00017718605522532016, 0.00017718605522532016, 0.00017718605522532016, 0 ]
{ "id": 1, "code_window": [ " * navigation actions. Swipe to open is disabled on iOS browsers by default.\n", " * @default typeof navigator !== 'undefined' && /iPad|iPhone|iPod/.test(navigator.userAgent)\n", " */\n", " disableSwipeToOpen?: boolean;\n", " /**\n", " * Affects how far the drawer must be opened/closed to change his state.\n", " * Specified as percent (0-1) of the width of the drawer\n", " * @default 0.52\n", " */\n", " hysteresis?: number;\n", " /**\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " * Affects how far the drawer must be opened/closed to change its state.\n" ], "file_path": "packages/material-ui/src/SwipeableDrawer/SwipeableDrawer.d.ts", "type": "replace", "edit_start_line_idx": 23 }
import * as React from 'react'; import ApiPage from 'docs/src/modules/components/ApiPage'; import mapApiPageTranslations from 'docs/src/modules/utils/mapApiPageTranslations'; import jsonPageContent from './list-item.json'; export default function Page(props) { const { descriptions, pageContent } = props; return <ApiPage descriptions={descriptions} pageContent={pageContent} />; } Page.getInitialProps = () => { const req = require.context('docs/translations/api-docs/list-item', false, /list-item.*.json$/); const descriptions = mapApiPageTranslations(req); return { descriptions, pageContent: jsonPageContent, }; };
docs/pages/api-docs/list-item.js
0
https://github.com/mui/material-ui/commit/2870aa6251ed7a114a16c8b94ff4c41ce0358dcf
[ 0.00017842435045167804, 0.0001776526914909482, 0.00017688103253021836, 0.0001776526914909482, 7.716589607298374e-7 ]
{ "id": 2, "code_window": [ " /**\n", " * @ignore\n", " */\n", " hideBackdrop: PropTypes.bool,\n", " /**\n", " * Affects how far the drawer must be opened/closed to change his state.\n", " * Specified as percent (0-1) of the width of the drawer\n", " * @default 0.52\n", " */\n", " hysteresis: PropTypes.number,\n", " /**\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " * Affects how far the drawer must be opened/closed to change its state.\n" ], "file_path": "packages/material-ui/src/SwipeableDrawer/SwipeableDrawer.js", "type": "replace", "edit_start_line_idx": 619 }
import * as React from 'react'; import { DrawerProps } from '../Drawer'; export interface SwipeableDrawerProps extends Omit<DrawerProps, 'onClose' | 'open'> { /** * Disable the backdrop transition. * This can improve the FPS on low-end devices. * @default false */ disableBackdropTransition?: boolean; /** * If `true`, touching the screen near the edge of the drawer will not slide in the drawer a bit * to promote accidental discovery of the swipe gesture. * @default false */ disableDiscovery?: boolean; /** * If `true`, swipe to open is disabled. This is useful in browsers where swiping triggers * navigation actions. Swipe to open is disabled on iOS browsers by default. * @default typeof navigator !== 'undefined' && /iPad|iPhone|iPod/.test(navigator.userAgent) */ disableSwipeToOpen?: boolean; /** * Affects how far the drawer must be opened/closed to change his state. * Specified as percent (0-1) of the width of the drawer * @default 0.52 */ hysteresis?: number; /** * Defines, from which (average) velocity on, the swipe is * defined as complete although hysteresis isn't reached. * Good threshold is between 250 - 1000 px/s * @default 450 */ minFlingVelocity?: number; /** * Callback fired when the component requests to be closed. * * @param {object} event The event source of the callback. */ onClose: React.ReactEventHandler<{}>; /** * Callback fired when the component requests to be opened. * * @param {object} event The event source of the callback. */ onOpen: React.ReactEventHandler<{}>; /** * If `true`, the component is shown. */ open: boolean; /** * The element is used to intercept the touch events on the edge. */ SwipeAreaProps?: object; /** * The width of the left most (or right most) area in `px` that * the drawer can be swiped open from. * @default 20 */ swipeAreaWidth?: number; } /** * * Demos: * * - [Drawers](https://material-ui.com/components/drawers/) * * API: * * - [SwipeableDrawer API](https://material-ui.com/api/swipeable-drawer/) * - inherits [Drawer API](https://material-ui.com/api/drawer/) */ declare const SwipeableDrawer: React.ComponentType<SwipeableDrawerProps>; export default SwipeableDrawer;
packages/material-ui/src/SwipeableDrawer/SwipeableDrawer.d.ts
1
https://github.com/mui/material-ui/commit/2870aa6251ed7a114a16c8b94ff4c41ce0358dcf
[ 0.0074543715454638, 0.0011622385354712605, 0.00016440414765384048, 0.0002910391194745898, 0.0023796926252543926 ]
{ "id": 2, "code_window": [ " /**\n", " * @ignore\n", " */\n", " hideBackdrop: PropTypes.bool,\n", " /**\n", " * Affects how far the drawer must be opened/closed to change his state.\n", " * Specified as percent (0-1) of the width of the drawer\n", " * @default 0.52\n", " */\n", " hysteresis: PropTypes.number,\n", " /**\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " * Affects how far the drawer must be opened/closed to change its state.\n" ], "file_path": "packages/material-ui/src/SwipeableDrawer/SwipeableDrawer.js", "type": "replace", "edit_start_line_idx": 619 }
import * as React from 'react'; import PropTypes from 'prop-types'; import { MuiStyles, WithStyles, withStyles } from '@material-ui/core/styles'; import Clock from './Clock'; import { pipe } from '../internal/pickers/utils'; import { useUtils, useNow, MuiPickersAdapter } from '../internal/pickers/hooks/useUtils'; import { getHourNumbers, getMinutesNumbers } from './ClockNumbers'; import PickersArrowSwitcher from '../internal/pickers/PickersArrowSwitcher'; import { convertValueToMeridiem, createIsAfterIgnoreDatePart, TimeValidationProps, } from '../internal/pickers/time-utils'; import { PickerOnChangeFn } from '../internal/pickers/hooks/useViews'; import { PickerSelectionState } from '../internal/pickers/hooks/usePickerState'; import { useMeridiemMode } from '../internal/pickers/hooks/date-helpers-hooks'; import { ClockView } from './shared'; export interface ExportedClockPickerProps<TDate> extends TimeValidationProps<TDate> { /** * 12h/24h view for hour selection clock. * @default false */ ampm?: boolean; /** * Step over minutes. * @default 1 */ minutesStep?: number; /** * Display ampm controls under the clock (instead of in the toolbar). * @default false */ ampmInClock?: boolean; /** * Enables keyboard listener for moving between days in calendar. * Defaults to `true` unless the `ClockPicker` is used inside a `Static*` picker component. */ allowKeyboardControl?: boolean; /** * Accessible text that helps user to understand which time and view is selected. * @default <TDate extends any>( * view: ClockView, * time: TDate, * adapter: MuiPickersAdapter<TDate>, * ) => `Select ${view}. Selected time is ${adapter.format(time, 'fullTime')}` */ getClockLabelText?: (view: ClockView, time: TDate, adapter: MuiPickersAdapter<TDate>) => string; } export interface ClockPickerProps<TDate> extends ExportedClockPickerProps<TDate> { /** * The components used for each slot. * Either a string to use a HTML element or a component. */ components?: { LeftArrowButton?: React.ElementType; LeftArrowIcon?: React.ElementType; RightArrowButton?: React.ElementType; RightArrowIcon?: React.ElementType; }; /** * The props used for each slot inside. */ componentsProps?: { leftArrowButton?: any; rightArrowButton?: any; }; /** * Selected date @DateIOType. */ date: TDate | null; /** * Get clock number aria-text for hours. * @default (hours: string) => `${hours} hours` */ getHoursClockNumberText?: (hours: string) => string; /** * Get clock number aria-text for minutes. * @default (minutes: string) => `${minutes} minutes` */ getMinutesClockNumberText?: (minutes: string) => string; /** * Get clock number aria-text for seconds. * @default (seconds: string) => `${seconds} seconds` */ getSecondsClockNumberText?: (seconds: string) => string; /** * Left arrow icon aria-label text. * @default 'open previous view' */ leftArrowButtonText?: string; previousViewAvailable: boolean; nextViewAvailable: boolean; /** * On change callback @DateIOType. */ onChange: PickerOnChangeFn<TDate>; openNextView: () => void; openPreviousView: () => void; /** * Right arrow icon aria-label text. * @default 'open next view' */ rightArrowButtonText?: string; showViewSwitcher?: boolean; view: ClockView; } export const styles: MuiStyles<'arrowSwitcher'> = { arrowSwitcher: { position: 'absolute', right: 12, top: 15, }, }; const defaultGetClockLabelText = <TDate extends any>( view: ClockView, time: TDate, adapter: MuiPickersAdapter<TDate>, ) => `Select ${view}. Selected time is ${adapter.format(time, 'fullTime')}`; const defaultGetMinutesClockNumberText = (minutes: string) => `${minutes} minutes`; const defaultGetHoursClockNumberText = (hours: string) => `${hours} hours`; const defaultGetSecondsClockNumberText = (seconds: string) => `${seconds} seconds`; /** * * API: * * - [ClockPicker API](https://material-ui.com/api/clock-picker/) */ function ClockPicker<TDate>(props: ClockPickerProps<TDate> & WithStyles<typeof styles>) { const { allowKeyboardControl, ampm = false, ampmInClock = false, classes, components, componentsProps, date, disableIgnoringDatePartForTimeValidation = false, getClockLabelText = defaultGetClockLabelText, getHoursClockNumberText = defaultGetHoursClockNumberText, getMinutesClockNumberText = defaultGetMinutesClockNumberText, getSecondsClockNumberText = defaultGetSecondsClockNumberText, leftArrowButtonText = 'open previous view', maxTime, minTime, minutesStep = 1, nextViewAvailable, onChange, openNextView, openPreviousView, previousViewAvailable, rightArrowButtonText = 'open next view', shouldDisableTime, showViewSwitcher, view, } = props; const now = useNow<TDate>(); const utils = useUtils<TDate>(); const dateOrNow = date || now; const { meridiemMode, handleMeridiemChange } = useMeridiemMode<TDate>(dateOrNow, ampm, onChange); const isTimeDisabled = React.useCallback( (rawValue: number, viewType: ClockView) => { if (date === null) { return false; } const validateTimeValue = (getRequestedTimePoint: (when: 'start' | 'end') => TDate) => { const isAfterComparingFn = createIsAfterIgnoreDatePart( disableIgnoringDatePartForTimeValidation, utils, ); return Boolean( (minTime && isAfterComparingFn(minTime, getRequestedTimePoint('end'))) || (maxTime && isAfterComparingFn(getRequestedTimePoint('start'), maxTime)) || (shouldDisableTime && shouldDisableTime(rawValue, viewType)), ); }; switch (viewType) { case 'hours': { const hoursWithMeridiem = convertValueToMeridiem(rawValue, meridiemMode, ampm); return validateTimeValue((when: 'start' | 'end') => pipe( (currentDate) => utils.setHours(currentDate, hoursWithMeridiem), (dateWithHours) => utils.setMinutes(dateWithHours, when === 'start' ? 0 : 59), (dateWithMinutes) => utils.setSeconds(dateWithMinutes, when === 'start' ? 0 : 59), )(date), ); } case 'minutes': return validateTimeValue((when: 'start' | 'end') => pipe( (currentDate) => utils.setMinutes(currentDate, rawValue), (dateWithMinutes) => utils.setSeconds(dateWithMinutes, when === 'start' ? 0 : 59), )(date), ); case 'seconds': return validateTimeValue(() => utils.setSeconds(date, rawValue)); default: throw new Error('not supported'); } }, [ ampm, date, disableIgnoringDatePartForTimeValidation, maxTime, meridiemMode, minTime, shouldDisableTime, utils, ], ); const viewProps = React.useMemo(() => { switch (view) { case 'hours': { const handleHoursChange = (value: number, isFinish?: PickerSelectionState) => { const valueWithMeridiem = convertValueToMeridiem(value, meridiemMode, ampm); onChange(utils.setHours(dateOrNow, valueWithMeridiem), isFinish); }; return { onChange: handleHoursChange, value: utils.getHours(dateOrNow), children: getHourNumbers({ date, utils, ampm, onChange: handleHoursChange, getClockNumberText: getHoursClockNumberText, isDisabled: (value) => isTimeDisabled(value, 'hours'), }), }; } case 'minutes': { const minutesValue = utils.getMinutes(dateOrNow); const handleMinutesChange = (value: number, isFinish?: PickerSelectionState) => { onChange(utils.setMinutes(dateOrNow, value), isFinish); }; return { value: minutesValue, onChange: handleMinutesChange, children: getMinutesNumbers({ utils, value: minutesValue, onChange: handleMinutesChange, getClockNumberText: getMinutesClockNumberText, isDisabled: (value) => isTimeDisabled(value, 'minutes'), }), }; } case 'seconds': { const secondsValue = utils.getSeconds(dateOrNow); const handleSecondsChange = (value: number, isFinish?: PickerSelectionState) => { onChange(utils.setSeconds(dateOrNow, value), isFinish); }; return { value: secondsValue, onChange: handleSecondsChange, children: getMinutesNumbers({ utils, value: secondsValue, onChange: handleSecondsChange, getClockNumberText: getSecondsClockNumberText, isDisabled: (value) => isTimeDisabled(value, 'seconds'), }), }; } default: throw new Error('You must provide the type for ClockView'); } }, [ view, utils, date, ampm, getHoursClockNumberText, getMinutesClockNumberText, getSecondsClockNumberText, meridiemMode, onChange, dateOrNow, isTimeDisabled, ]); return ( <React.Fragment> {showViewSwitcher && ( <PickersArrowSwitcher className={classes.arrowSwitcher} leftArrowButtonText={leftArrowButtonText} rightArrowButtonText={rightArrowButtonText} components={components} componentsProps={componentsProps} onLeftClick={openPreviousView} onRightClick={openNextView} isLeftDisabled={previousViewAvailable} isRightDisabled={nextViewAvailable} /> )} <Clock<TDate> date={date} ampmInClock={ampmInClock} type={view} ampm={ampm} getClockLabelText={getClockLabelText} minutesStep={minutesStep} allowKeyboardControl={allowKeyboardControl} isTimeDisabled={isTimeDisabled} meridiemMode={meridiemMode} handleMeridiemChange={handleMeridiemChange} {...viewProps} /> </React.Fragment> ); } ClockPicker.propTypes /* remove-proptypes */ = { // ----------------------------- Warning -------------------------------- // | These PropTypes are generated from the TypeScript type definitions | // | To update them edit TypeScript types and run "yarn proptypes" | // ---------------------------------------------------------------------- /** * Enables keyboard listener for moving between days in calendar. * Defaults to `true` unless the `ClockPicker` is used inside a `Static*` picker component. */ allowKeyboardControl: PropTypes.bool, /** * 12h/24h view for hour selection clock. * @default false */ ampm: PropTypes.bool, /** * Display ampm controls under the clock (instead of in the toolbar). * @default false */ ampmInClock: PropTypes.bool, /** * @ignore */ classes: PropTypes.object.isRequired, /** * The components used for each slot. * Either a string to use a HTML element or a component. */ components: PropTypes.shape({ LeftArrowButton: PropTypes.elementType, LeftArrowIcon: PropTypes.elementType, RightArrowButton: PropTypes.elementType, RightArrowIcon: PropTypes.elementType, }), /** * The props used for each slot inside. */ componentsProps: PropTypes.object, /** * Selected date @DateIOType. */ date: PropTypes.any, /** * Do not ignore date part when validating min/max time. * @default false */ disableIgnoringDatePartForTimeValidation: PropTypes.bool, /** * Accessible text that helps user to understand which time and view is selected. * @default <TDate extends any>( * view: ClockView, * time: TDate, * adapter: MuiPickersAdapter<TDate>, * ) => `Select ${view}. Selected time is ${adapter.format(time, 'fullTime')}` */ getClockLabelText: PropTypes.func, /** * Get clock number aria-text for hours. * @default (hours: string) => `${hours} hours` */ getHoursClockNumberText: PropTypes.func, /** * Get clock number aria-text for minutes. * @default (minutes: string) => `${minutes} minutes` */ getMinutesClockNumberText: PropTypes.func, /** * Get clock number aria-text for seconds. * @default (seconds: string) => `${seconds} seconds` */ getSecondsClockNumberText: PropTypes.func, /** * Left arrow icon aria-label text. * @default 'open previous view' */ leftArrowButtonText: PropTypes.string, /** * Max time acceptable time. * For input validation date part of passed object will be ignored if `disableIgnoringDatePartForTimeValidation` not specified. */ maxTime: PropTypes.any, /** * Min time acceptable time. * For input validation date part of passed object will be ignored if `disableIgnoringDatePartForTimeValidation` not specified. */ minTime: PropTypes.any, /** * Step over minutes. * @default 1 */ minutesStep: PropTypes.number, /** * @ignore */ nextViewAvailable: PropTypes.bool.isRequired, /** * On change callback @DateIOType. */ onChange: PropTypes.func.isRequired, /** * @ignore */ openNextView: PropTypes.func.isRequired, /** * @ignore */ openPreviousView: PropTypes.func.isRequired, /** * @ignore */ previousViewAvailable: PropTypes.bool.isRequired, /** * Right arrow icon aria-label text. * @default 'open next view' */ rightArrowButtonText: PropTypes.string, /** * Dynamically check if time is disabled or not. * If returns `false` appropriate time point will ot be acceptable. */ shouldDisableTime: PropTypes.func, /** * @ignore */ showViewSwitcher: PropTypes.bool, /** * @ignore */ view: PropTypes.oneOf(['hours', 'minutes', 'seconds']).isRequired, } as any; /** * * API: * * - [ClockPicker API](https://material-ui.com/api/clock-picker/) */ export default withStyles(styles, { name: 'MuiClockPicker' })(ClockPicker) as <TDate>( props: ClockPickerProps<TDate>, ) => JSX.Element;
packages/material-ui-lab/src/ClockPicker/ClockPicker.tsx
0
https://github.com/mui/material-ui/commit/2870aa6251ed7a114a16c8b94ff4c41ce0358dcf
[ 0.00021041807485744357, 0.00017248470976483077, 0.00016495421004947275, 0.0001725393085507676, 0.000007799809282005299 ]
{ "id": 2, "code_window": [ " /**\n", " * @ignore\n", " */\n", " hideBackdrop: PropTypes.bool,\n", " /**\n", " * Affects how far the drawer must be opened/closed to change his state.\n", " * Specified as percent (0-1) of the width of the drawer\n", " * @default 0.52\n", " */\n", " hysteresis: PropTypes.number,\n", " /**\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " * Affects how far the drawer must be opened/closed to change its state.\n" ], "file_path": "packages/material-ui/src/SwipeableDrawer/SwipeableDrawer.js", "type": "replace", "edit_start_line_idx": 619 }
import * as React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <path d="M19 3h-4.18C14.4 1.84 13.3 1 12 1s-2.4.84-2.82 2H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm-7-.25c.41 0 .75.34.75.75s-.34.75-.75.75-.75-.34-.75-.75.34-.75.75-.75zm-.35 12.9l-2.79-2.79c-.32-.32-.1-.86.35-.86H11V9c0-.55.45-1 1-1s1 .45 1 1v3h1.79c.45 0 .67.54.35.85l-2.79 2.79c-.19.2-.51.2-.7.01z" /> , 'AssignmentReturnedRounded');
packages/material-ui-icons/src/AssignmentReturnedRounded.js
0
https://github.com/mui/material-ui/commit/2870aa6251ed7a114a16c8b94ff4c41ce0358dcf
[ 0.0001748983486322686, 0.0001748983486322686, 0.0001748983486322686, 0.0001748983486322686, 0 ]
{ "id": 2, "code_window": [ " /**\n", " * @ignore\n", " */\n", " hideBackdrop: PropTypes.bool,\n", " /**\n", " * Affects how far the drawer must be opened/closed to change his state.\n", " * Specified as percent (0-1) of the width of the drawer\n", " * @default 0.52\n", " */\n", " hysteresis: PropTypes.number,\n", " /**\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " * Affects how far the drawer must be opened/closed to change its state.\n" ], "file_path": "packages/material-ui/src/SwipeableDrawer/SwipeableDrawer.js", "type": "replace", "edit_start_line_idx": 619 }
import * as React from 'react'; import PropTypes from 'prop-types'; function Component(props) { const { value } = props; return <div>{value}</div>; } const someValidator = () => new Error(); Component.propTypes = { value: PropTypes.any.isRequired, }; export default Component;
packages/typescript-to-proptypes/test/code-order/output.js
0
https://github.com/mui/material-ui/commit/2870aa6251ed7a114a16c8b94ff4c41ce0358dcf
[ 0.00017463589028920978, 0.00017104391008615494, 0.0001674519298831001, 0.00017104391008615494, 0.0000035919802030548453 ]
{ "id": 0, "code_window": [ "import { MemoryRouter as Router } from 'react-router';\n", "import { Link, LinkProps } from 'react-router-dom';\n", "import Button from '@material-ui/core/Button';\n", "\n", "// required for react-router-dom < 6.0.0\n", "// see https://github.com/ReactTraining/react-router/issues/6056#issuecomment-435524678\n", "const AdapterLink = React.forwardRef<HTMLAnchorElement, LinkProps>((props, ref) => (\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { Omit } from '@material-ui/types';\n" ], "file_path": "docs/src/pages/components/buttons/ButtonRouter.tsx", "type": "add", "edit_start_line_idx": 4 }
import React from 'react'; import { MemoryRouter as Router } from 'react-router'; import { Link, LinkProps } from 'react-router-dom'; import Button from '@material-ui/core/Button'; // required for react-router-dom < 6.0.0 // see https://github.com/ReactTraining/react-router/issues/6056#issuecomment-435524678 const AdapterLink = React.forwardRef<HTMLAnchorElement, LinkProps>((props, ref) => ( <Link innerRef={ref as any} {...props} /> )); type Omit<T, K> = Pick<T, Exclude<keyof T, K>>; const CollisionLink = React.forwardRef<HTMLAnchorElement, Omit<LinkProps, 'innerRef' | 'to'>>( (props, ref) => <Link innerRef={ref as any} to="/getting-started/installation/" {...props} />, ); export default function ButtonRouter() { return ( <Router> <Button color="primary" component={AdapterLink} to="/"> Simple case </Button> <Button component={CollisionLink}>Avoids props collision</Button> </Router> ); }
docs/src/pages/components/buttons/ButtonRouter.tsx
1
https://github.com/mui/material-ui/commit/81ff109944bbb69cbb59dede3bc23a7e387b3ed3
[ 0.9982981085777283, 0.6646604537963867, 0.0003228729765396565, 0.9953604340553284, 0.46975916624069214 ]
{ "id": 0, "code_window": [ "import { MemoryRouter as Router } from 'react-router';\n", "import { Link, LinkProps } from 'react-router-dom';\n", "import Button from '@material-ui/core/Button';\n", "\n", "// required for react-router-dom < 6.0.0\n", "// see https://github.com/ReactTraining/react-router/issues/6056#issuecomment-435524678\n", "const AdapterLink = React.forwardRef<HTMLAnchorElement, LinkProps>((props, ref) => (\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { Omit } from '@material-ui/types';\n" ], "file_path": "docs/src/pages/components/buttons/ButtonRouter.tsx", "type": "add", "edit_start_line_idx": 4 }
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <React.Fragment><path fill="none" d="M0 0h24v24H0V0z" opacity=".87" /><path d="M12 2C6.47 2 2 6.47 2 12s4.47 10 10 10 10-4.47 10-10S17.53 2 12 2zm0 18c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8z" /><path d="M15.59 7L12 10.59 8.41 7 7 8.41 10.59 12 7 15.59 8.41 17 12 13.41 15.59 17 17 15.59 13.41 12 17 8.41z" /></React.Fragment> , 'CancelOutlined');
packages/material-ui-icons/src/CancelOutlined.js
0
https://github.com/mui/material-ui/commit/81ff109944bbb69cbb59dede3bc23a7e387b3ed3
[ 0.0001736523990985006, 0.0001736523990985006, 0.0001736523990985006, 0.0001736523990985006, 0 ]
{ "id": 0, "code_window": [ "import { MemoryRouter as Router } from 'react-router';\n", "import { Link, LinkProps } from 'react-router-dom';\n", "import Button from '@material-ui/core/Button';\n", "\n", "// required for react-router-dom < 6.0.0\n", "// see https://github.com/ReactTraining/react-router/issues/6056#issuecomment-435524678\n", "const AdapterLink = React.forwardRef<HTMLAnchorElement, LinkProps>((props, ref) => (\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { Omit } from '@material-ui/types';\n" ], "file_path": "docs/src/pages/components/buttons/ButtonRouter.tsx", "type": "add", "edit_start_line_idx": 4 }
'use strict'; // Do this as the first thing so that any code reading it knows the right env. process.env.BABEL_ENV = 'development'; process.env.NODE_ENV = 'development'; // Makes the script crash on unhandled rejections instead of silently // ignoring them. In the future, promise rejections that are not handled will // terminate the Node.js process with a non-zero exit code. process.on('unhandledRejection', err => { throw err; }); // Ensure environment variables are read. require('../config/env'); const fs = require('fs'); const chalk = require('react-dev-utils/chalk'); const webpack = require('webpack'); const WebpackDevServer = require('webpack-dev-server'); const clearConsole = require('react-dev-utils/clearConsole'); const checkRequiredFiles = require('react-dev-utils/checkRequiredFiles'); const { choosePort, createCompiler, prepareProxy, prepareUrls, } = require('react-dev-utils/WebpackDevServerUtils'); const openBrowser = require('react-dev-utils/openBrowser'); const paths = require('../config/paths'); const configFactory = require('../config/webpack.config'); const createDevServerConfig = require('../config/webpackDevServer.config'); const useYarn = fs.existsSync(paths.yarnLockFile); const isInteractive = process.stdout.isTTY; // Warn and crash if required files are missing if (!checkRequiredFiles([paths.appHtml, paths.appIndexJs])) { process.exit(1); } // Tools like Cloud9 rely on this. const DEFAULT_PORT = parseInt(process.env.PORT, 10) || 3000; const HOST = process.env.HOST || '0.0.0.0'; if (process.env.HOST) { console.log( chalk.cyan( `Attempting to bind to HOST environment variable: ${chalk.yellow( chalk.bold(process.env.HOST), )}`, ), ); console.log(`If this was unintentional, check that you haven't mistakenly set it in your shell.`); console.log(`Learn more here: ${chalk.yellow('https://bit.ly/CRA-advanced-config')}`); console.log(); } // We require that you explictly set browsers and do not fall back to // browserslist defaults. const { checkBrowsers } = require('react-dev-utils/browsersHelper'); checkBrowsers(paths.appPath, isInteractive) .then(() => { // We attempt to use the default port but if it is busy, we offer the user to // run on a different port. `choosePort()` Promise resolves to the next free port. return choosePort(HOST, DEFAULT_PORT); }) .then(port => { if (port == null) { // We have not found a port. return; } const config = configFactory('development'); const protocol = process.env.HTTPS === 'true' ? 'https' : 'http'; const appName = require(paths.appPackageJson).name; const useTypeScript = fs.existsSync(paths.appTsConfig); const urls = prepareUrls(protocol, HOST, port); const devSocket = { warnings: warnings => devServer.sockWrite(devServer.sockets, 'warnings', warnings), errors: errors => devServer.sockWrite(devServer.sockets, 'errors', errors), }; // Create a webpack compiler that is configured with custom messages. const compiler = createCompiler({ appName, config, devSocket, urls, useYarn, useTypeScript, webpack, }); // Load proxy config const proxySetting = require(paths.appPackageJson).proxy; const proxyConfig = prepareProxy(proxySetting, paths.appPublic); // Serve webpack assets generated by the compiler over a web server. const serverConfig = createDevServerConfig(proxyConfig, urls.lanUrlForConfig); const devServer = new WebpackDevServer(compiler, serverConfig); // Launch WebpackDevServer. devServer.listen(port, HOST, err => { if (err) { return console.log(err); } if (isInteractive) { clearConsole(); } console.log(chalk.cyan('Starting the development server...\n')); openBrowser(urls.localUrlForBrowser); }); ['SIGINT', 'SIGTERM'].forEach(function(sig) { process.on(sig, function() { devServer.close(); process.exit(); }); }); }) .catch(err => { if (err && err.message) { console.log(err.message); } process.exit(1); });
examples/preact/scripts/start.js
0
https://github.com/mui/material-ui/commit/81ff109944bbb69cbb59dede3bc23a7e387b3ed3
[ 0.000175311099155806, 0.0001707781048025936, 0.0001628747268114239, 0.00017123388533946127, 0.0000034022489217022667 ]
{ "id": 0, "code_window": [ "import { MemoryRouter as Router } from 'react-router';\n", "import { Link, LinkProps } from 'react-router-dom';\n", "import Button from '@material-ui/core/Button';\n", "\n", "// required for react-router-dom < 6.0.0\n", "// see https://github.com/ReactTraining/react-router/issues/6056#issuecomment-435524678\n", "const AdapterLink = React.forwardRef<HTMLAnchorElement, LinkProps>((props, ref) => (\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { Omit } from '@material-ui/types';\n" ], "file_path": "docs/src/pages/components/buttons/ButtonRouter.tsx", "type": "add", "edit_start_line_idx": 4 }
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <React.Fragment><path fill="none" d="M0 0h24v24H0z" /><path d="M17.71 7.71L12 2h-1v7.59L6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 11 14.41V22h1l5.71-5.71-4.3-4.29 4.3-4.29zM13 5.83l1.88 1.88L13 9.59V5.83zm1.88 10.46L13 18.17v-3.76l1.88 1.88z" /></React.Fragment> , 'Bluetooth');
packages/material-ui-icons/src/Bluetooth.js
0
https://github.com/mui/material-ui/commit/81ff109944bbb69cbb59dede3bc23a7e387b3ed3
[ 0.00017128435138147324, 0.00017128435138147324, 0.00017128435138147324, 0.00017128435138147324, 0 ]
{ "id": 1, "code_window": [ " <Link innerRef={ref as any} {...props} />\n", "));\n", "\n", "type Omit<T, K> = Pick<T, Exclude<keyof T, K>>;\n", "const CollisionLink = React.forwardRef<HTMLAnchorElement, Omit<LinkProps, 'innerRef' | 'to'>>(\n", " (props, ref) => <Link innerRef={ref as any} to=\"/getting-started/installation/\" {...props} />,\n", ");\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "docs/src/pages/components/buttons/ButtonRouter.tsx", "type": "replace", "edit_start_line_idx": 11 }
/* eslint-disable jsx-a11y/anchor-is-valid */ import React from 'react'; import { MemoryRouter as Router } from 'react-router'; import { Link as RouterLink, LinkProps as RouterLinkProps } from 'react-router-dom'; import Link from '@material-ui/core/Link'; // required for react-router-dom < 6.0.0 // see https://github.com/ReactTraining/react-router/issues/6056#issuecomment-435524678 const AdapterLink = React.forwardRef<HTMLAnchorElement, RouterLinkProps>((props, ref) => ( <RouterLink innerRef={ref as any} {...props} /> )); type Omit<T, K> = Pick<T, Exclude<keyof T, K>>; const CollisionLink = React.forwardRef<HTMLAnchorElement, Omit<RouterLinkProps, 'innerRef' | 'to'>>( (props, ref) => ( <RouterLink innerRef={ref as any} to="/getting-started/installation/" {...props} /> ), ); export default function LinkRouter() { return ( <Router> <div> <Link component={RouterLink} to="/"> Simple case </Link> <br /> <Link component={AdapterLink} to="/"> Ref forwarding </Link> <br /> <Link component={CollisionLink}>Avoids props collision</Link> </div> </Router> ); }
docs/src/pages/components/links/LinkRouter.tsx
1
https://github.com/mui/material-ui/commit/81ff109944bbb69cbb59dede3bc23a7e387b3ed3
[ 0.9983739852905273, 0.5016348361968994, 0.0003082945477217436, 0.503928542137146, 0.49653011560440063 ]
{ "id": 1, "code_window": [ " <Link innerRef={ref as any} {...props} />\n", "));\n", "\n", "type Omit<T, K> = Pick<T, Exclude<keyof T, K>>;\n", "const CollisionLink = React.forwardRef<HTMLAnchorElement, Omit<LinkProps, 'innerRef' | 'to'>>(\n", " (props, ref) => <Link innerRef={ref as any} to=\"/getting-started/installation/\" {...props} />,\n", ");\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "docs/src/pages/components/buttons/ButtonRouter.tsx", "type": "replace", "edit_start_line_idx": 11 }
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <React.Fragment><path fill="none" d="M0 0h24v24H0V0z" /><path d="M12 4c-4.41 0-8 3.59-8 8s3.59 8 8 8 8-3.59 8-8-3.59-8-8-8zm4.08 12H8.5C6.57 16 5 14.43 5 12.5c0-1.8 1.36-3.29 3.12-3.48.73-1.4 2.19-2.36 3.88-2.36 2.12 0 3.89 1.51 4.29 3.52 1.52.1 2.71 1.35 2.71 2.89 0 1.62-1.31 2.93-2.92 2.93z" opacity=".3" /><path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 18c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8z" /><path d="M16.29 10.19c-.4-2.01-2.16-3.52-4.29-3.52-1.69 0-3.15.96-3.88 2.36C6.36 9.21 5 10.7 5 12.5 5 14.43 6.57 16 8.5 16h7.58c1.61 0 2.92-1.31 2.92-2.92 0-1.54-1.2-2.79-2.71-2.89zM16 14H8.5c-.83 0-1.5-.67-1.5-1.5S7.67 11 8.5 11h.9l.49-1.05c.41-.79 1.22-1.28 2.11-1.28 1.13 0 2.11.8 2.33 1.91l.28 1.42H16c.55 0 1 .45 1 1s-.45 1-1 1z" /></React.Fragment> , 'CloudCircleTwoTone');
packages/material-ui-icons/src/CloudCircleTwoTone.js
0
https://github.com/mui/material-ui/commit/81ff109944bbb69cbb59dede3bc23a7e387b3ed3
[ 0.000906675006262958, 0.000906675006262958, 0.000906675006262958, 0.000906675006262958, 0 ]
{ "id": 1, "code_window": [ " <Link innerRef={ref as any} {...props} />\n", "));\n", "\n", "type Omit<T, K> = Pick<T, Exclude<keyof T, K>>;\n", "const CollisionLink = React.forwardRef<HTMLAnchorElement, Omit<LinkProps, 'innerRef' | 'to'>>(\n", " (props, ref) => <Link innerRef={ref as any} to=\"/getting-started/installation/\" {...props} />,\n", ");\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "docs/src/pages/components/buttons/ButtonRouter.tsx", "type": "replace", "edit_start_line_idx": 11 }
import * as React from 'react'; export interface NoSsrProps { children: React.ReactNode; defer?: boolean; fallback?: React.ReactNode; } declare const NoSsr: React.ComponentType<NoSsrProps>; export default NoSsr;
packages/material-ui/src/NoSsr/NoSsr.d.ts
0
https://github.com/mui/material-ui/commit/81ff109944bbb69cbb59dede3bc23a7e387b3ed3
[ 0.00017542530258651823, 0.00017384956299792975, 0.00017227382340934128, 0.00017384956299792975, 0.0000015757395885884762 ]
{ "id": 1, "code_window": [ " <Link innerRef={ref as any} {...props} />\n", "));\n", "\n", "type Omit<T, K> = Pick<T, Exclude<keyof T, K>>;\n", "const CollisionLink = React.forwardRef<HTMLAnchorElement, Omit<LinkProps, 'innerRef' | 'to'>>(\n", " (props, ref) => <Link innerRef={ref as any} to=\"/getting-started/installation/\" {...props} />,\n", ");\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "docs/src/pages/components/buttons/ButtonRouter.tsx", "type": "replace", "edit_start_line_idx": 11 }
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <React.Fragment><path fill="none" d="M0 0h24v24H0V0z" /><path d="M18 8c0-3.31-2.69-6-6-6S6 4.69 6 8c0 3.49 3.62 8.19 5.23 10.12.4.48 1.13.48 1.53 0C14.38 16.19 18 11.49 18 8zm-8 0c0-1.1.9-2 2-2s2 .9 2 2-.89 2-2 2c-1.1 0-2-.9-2-2zM5 21c0 .55.45 1 1 1h12c.55 0 1-.45 1-1s-.45-1-1-1H6c-.55 0-1 .45-1 1z" /></React.Fragment> , 'PinDropRounded');
packages/material-ui-icons/src/PinDropRounded.js
0
https://github.com/mui/material-ui/commit/81ff109944bbb69cbb59dede3bc23a7e387b3ed3
[ 0.00017266850045416504, 0.00017266850045416504, 0.00017266850045416504, 0.00017266850045416504, 0 ]
{ "id": 2, "code_window": [ "import { MemoryRouter as Router } from 'react-router';\n", "import { Link as RouterLink, LinkProps as RouterLinkProps } from 'react-router-dom';\n", "import Link from '@material-ui/core/Link';\n", "\n", "// required for react-router-dom < 6.0.0\n", "// see https://github.com/ReactTraining/react-router/issues/6056#issuecomment-435524678\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "import { Omit } from '@material-ui/types';\n" ], "file_path": "docs/src/pages/components/links/LinkRouter.tsx", "type": "add", "edit_start_line_idx": 5 }
import React from 'react'; import { MemoryRouter as Router } from 'react-router'; import { Link, LinkProps } from 'react-router-dom'; import Button from '@material-ui/core/Button'; // required for react-router-dom < 6.0.0 // see https://github.com/ReactTraining/react-router/issues/6056#issuecomment-435524678 const AdapterLink = React.forwardRef<HTMLAnchorElement, LinkProps>((props, ref) => ( <Link innerRef={ref as any} {...props} /> )); type Omit<T, K> = Pick<T, Exclude<keyof T, K>>; const CollisionLink = React.forwardRef<HTMLAnchorElement, Omit<LinkProps, 'innerRef' | 'to'>>( (props, ref) => <Link innerRef={ref as any} to="/getting-started/installation/" {...props} />, ); export default function ButtonRouter() { return ( <Router> <Button color="primary" component={AdapterLink} to="/"> Simple case </Button> <Button component={CollisionLink}>Avoids props collision</Button> </Router> ); }
docs/src/pages/components/buttons/ButtonRouter.tsx
1
https://github.com/mui/material-ui/commit/81ff109944bbb69cbb59dede3bc23a7e387b3ed3
[ 0.9896559715270996, 0.3302059471607208, 0.00017547834431752563, 0.0007863782229833305, 0.46630167961120605 ]
{ "id": 2, "code_window": [ "import { MemoryRouter as Router } from 'react-router';\n", "import { Link as RouterLink, LinkProps as RouterLinkProps } from 'react-router-dom';\n", "import Link from '@material-ui/core/Link';\n", "\n", "// required for react-router-dom < 6.0.0\n", "// see https://github.com/ReactTraining/react-router/issues/6056#issuecomment-435524678\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "import { Omit } from '@material-ui/types';\n" ], "file_path": "docs/src/pages/components/links/LinkRouter.tsx", "type": "add", "edit_start_line_idx": 5 }
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <React.Fragment><path fill="none" d="M0 0h24v24H0V0z" /><g><path d="M9.5 9.8h2.8l-2.8 3.4V15h5v-1.8h-2.8l2.8-3.4V8h-5z" /><path d="M18 16v-5c0-3.07-1.63-5.64-4.5-6.32V4c0-.83-.67-1.5-1.5-1.5s-1.5.67-1.5 1.5v.68C7.64 5.36 6 7.92 6 11v5l-2 2v1h16v-1l-2-2zm-2 1H8v-6c0-2.48 1.51-4.5 4-4.5s4 2.02 4 4.5v6zM12 22c1.1 0 2-.9 2-2h-4c0 1.1.9 2 2 2z" /></g></React.Fragment> , 'NotificationsPausedOutlined');
packages/material-ui-icons/src/NotificationsPausedOutlined.js
0
https://github.com/mui/material-ui/commit/81ff109944bbb69cbb59dede3bc23a7e387b3ed3
[ 0.00016645918367430568, 0.00016645918367430568, 0.00016645918367430568, 0.00016645918367430568, 0 ]
{ "id": 2, "code_window": [ "import { MemoryRouter as Router } from 'react-router';\n", "import { Link as RouterLink, LinkProps as RouterLinkProps } from 'react-router-dom';\n", "import Link from '@material-ui/core/Link';\n", "\n", "// required for react-router-dom < 6.0.0\n", "// see https://github.com/ReactTraining/react-router/issues/6056#issuecomment-435524678\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "import { Omit } from '@material-ui/types';\n" ], "file_path": "docs/src/pages/components/links/LinkRouter.tsx", "type": "add", "edit_start_line_idx": 5 }
import React from 'react'; import PropTypes from 'prop-types'; import { pageToTitleI18n } from 'docs/src/modules/utils/helpers'; import PageContext from 'docs/src/modules/components/PageContext'; // TODO: it really wants to be named useTitle but we're not quite there yet. function PageTitle(props) { const { activePage } = React.useContext(PageContext); if (!activePage) { throw new Error('Missing activePage.'); } const title = pageToTitleI18n(activePage, props.t); return props.children(title); } PageTitle.propTypes = { children: PropTypes.func.isRequired, }; export default PageTitle;
docs/src/modules/components/PageTitle.js
0
https://github.com/mui/material-ui/commit/81ff109944bbb69cbb59dede3bc23a7e387b3ed3
[ 0.00017069641035050154, 0.0001692427322268486, 0.00016773668176028877, 0.00016929511912167072, 0.0000012088717085134704 ]
{ "id": 2, "code_window": [ "import { MemoryRouter as Router } from 'react-router';\n", "import { Link as RouterLink, LinkProps as RouterLinkProps } from 'react-router-dom';\n", "import Link from '@material-ui/core/Link';\n", "\n", "// required for react-router-dom < 6.0.0\n", "// see https://github.com/ReactTraining/react-router/issues/6056#issuecomment-435524678\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "import { Omit } from '@material-ui/types';\n" ], "file_path": "docs/src/pages/components/links/LinkRouter.tsx", "type": "add", "edit_start_line_idx": 5 }
import React from 'react'; import PropTypes from 'prop-types'; import clsx from 'clsx'; import ButtonBase from '../ButtonBase'; import IconButton from '../IconButton'; import withStyles from '../styles/withStyles'; export const styles = theme => { const transition = { duration: theme.transitions.duration.shortest, }; return { /* Styles applied to the root element. */ root: { display: 'flex', minHeight: 8 * 6, transition: theme.transitions.create(['min-height', 'background-color'], transition), padding: '0 24px 0 24px', '&:hover:not($disabled)': { cursor: 'pointer', }, '&$expanded': { minHeight: 64, }, '&$focused': { backgroundColor: theme.palette.grey[300], }, '&$disabled': { opacity: 0.38, }, }, /* Styles applied to the root element, children wrapper element and `IconButton` component if `expanded={true}`. */ expanded: {}, /* Styles applied to the root and children wrapper elements when focused. */ focused: {}, /* Styles applied to the root element if `disabled={true}`. */ disabled: {}, /* Styles applied to the children wrapper element. */ content: { display: 'flex', flexGrow: 1, transition: theme.transitions.create(['margin'], transition), margin: '12px 0', '&$expanded': { margin: '20px 0', }, }, /* Styles applied to the `IconButton` component when `expandIcon` is supplied. */ expandIcon: { transform: 'rotate(0deg)', transition: theme.transitions.create('transform', transition), '&:hover': { // Disable the hover effect for the IconButton, // because a hover effect should apply to the entire Expand button and // not only to the IconButton. backgroundColor: 'transparent', }, '&$expanded': { transform: 'rotate(180deg)', }, }, }; }; const ExpansionPanelSummary = React.forwardRef(function ExpansionPanelSummary(props, ref) { const { children, classes, className, disabled = false, expanded, expandIcon, IconButtonProps, onBlur, onChange, onClick, onFocusVisible, ...other } = props; const [focusedState, setFocusedState] = React.useState(false); const handleFocusVisible = event => { setFocusedState(true); if (onFocusVisible) { onFocusVisible(event); } }; const handleBlur = event => { setFocusedState(false); if (onBlur) { onBlur(event); } }; const handleChange = event => { if (onChange) { onChange(event); } if (onClick) { onClick(event); } }; return ( <ButtonBase focusRipple={false} disableRipple disabled={disabled} component="div" aria-expanded={expanded} className={clsx( classes.root, { [classes.disabled]: disabled, [classes.expanded]: expanded, [classes.focused]: focusedState, }, className, )} onFocusVisible={handleFocusVisible} onBlur={handleBlur} onClick={handleChange} ref={ref} {...other} > <div className={clsx(classes.content, { [classes.expanded]: expanded })}>{children}</div> {expandIcon && ( <IconButton disabled={disabled} className={clsx(classes.expandIcon, { [classes.expanded]: expanded, })} edge="end" component="div" tabIndex={-1} aria-hidden {...IconButtonProps} > {expandIcon} </IconButton> )} </ButtonBase> ); }); ExpansionPanelSummary.propTypes = { /** * The content of the expansion panel summary. */ children: PropTypes.node, /** * Override or extend the styles applied to the component. * See [CSS API](#css) below for more details. */ classes: PropTypes.object.isRequired, /** * @ignore */ className: PropTypes.string, /** * @ignore * If `true`, the summary will be displayed in a disabled state. */ disabled: PropTypes.bool, /** * @ignore * If `true`, expands the summary, otherwise collapse it. */ expanded: PropTypes.bool, /** * The icon to display as the expand indicator. */ expandIcon: PropTypes.node, /** * Properties applied to the `IconButton` element wrapping the expand icon. */ IconButtonProps: PropTypes.object, /** * @ignore */ onBlur: PropTypes.func, /** * @ignore */ onChange: PropTypes.func, /** * @ignore */ onClick: PropTypes.func, /** * @ignore */ onFocusVisible: PropTypes.func, }; export default withStyles(styles, { name: 'MuiExpansionPanelSummary' })(ExpansionPanelSummary);
packages/material-ui/src/ExpansionPanelSummary/ExpansionPanelSummary.js
0
https://github.com/mui/material-ui/commit/81ff109944bbb69cbb59dede3bc23a7e387b3ed3
[ 0.000176597575773485, 0.00017062397091649473, 0.0001647852041060105, 0.00017127557657659054, 0.000003131855009996798 ]
{ "id": 3, "code_window": [ "// see https://github.com/ReactTraining/react-router/issues/6056#issuecomment-435524678\n", "const AdapterLink = React.forwardRef<HTMLAnchorElement, RouterLinkProps>((props, ref) => (\n", " <RouterLink innerRef={ref as any} {...props} />\n", "));\n", "\n", "type Omit<T, K> = Pick<T, Exclude<keyof T, K>>;\n", "const CollisionLink = React.forwardRef<HTMLAnchorElement, Omit<RouterLinkProps, 'innerRef' | 'to'>>(\n", " (props, ref) => (\n", " <RouterLink innerRef={ref as any} to=\"/getting-started/installation/\" {...props} />\n", " ),\n", ");\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "docs/src/pages/components/links/LinkRouter.tsx", "type": "replace", "edit_start_line_idx": 12 }
/* eslint-disable jsx-a11y/anchor-is-valid */ import React from 'react'; import { MemoryRouter as Router } from 'react-router'; import { Link as RouterLink, LinkProps as RouterLinkProps } from 'react-router-dom'; import Link from '@material-ui/core/Link'; // required for react-router-dom < 6.0.0 // see https://github.com/ReactTraining/react-router/issues/6056#issuecomment-435524678 const AdapterLink = React.forwardRef<HTMLAnchorElement, RouterLinkProps>((props, ref) => ( <RouterLink innerRef={ref as any} {...props} /> )); type Omit<T, K> = Pick<T, Exclude<keyof T, K>>; const CollisionLink = React.forwardRef<HTMLAnchorElement, Omit<RouterLinkProps, 'innerRef' | 'to'>>( (props, ref) => ( <RouterLink innerRef={ref as any} to="/getting-started/installation/" {...props} /> ), ); export default function LinkRouter() { return ( <Router> <div> <Link component={RouterLink} to="/"> Simple case </Link> <br /> <Link component={AdapterLink} to="/"> Ref forwarding </Link> <br /> <Link component={CollisionLink}>Avoids props collision</Link> </div> </Router> ); }
docs/src/pages/components/links/LinkRouter.tsx
1
https://github.com/mui/material-ui/commit/81ff109944bbb69cbb59dede3bc23a7e387b3ed3
[ 0.9982343912124634, 0.9940415620803833, 0.9870593547821045, 0.9954362511634827, 0.004559196066111326 ]
{ "id": 3, "code_window": [ "// see https://github.com/ReactTraining/react-router/issues/6056#issuecomment-435524678\n", "const AdapterLink = React.forwardRef<HTMLAnchorElement, RouterLinkProps>((props, ref) => (\n", " <RouterLink innerRef={ref as any} {...props} />\n", "));\n", "\n", "type Omit<T, K> = Pick<T, Exclude<keyof T, K>>;\n", "const CollisionLink = React.forwardRef<HTMLAnchorElement, Omit<RouterLinkProps, 'innerRef' | 'to'>>(\n", " (props, ref) => (\n", " <RouterLink innerRef={ref as any} to=\"/getting-started/installation/\" {...props} />\n", " ),\n", ");\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "docs/src/pages/components/links/LinkRouter.tsx", "type": "replace", "edit_start_line_idx": 12 }
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <React.Fragment><path fill="none" d="M0 0h24v24H0V0z" /><path d="M5 17v2h14v-2H5zm4.5-4.2h5l.9 2.2h2.1L12.75 4h-1.5L6.5 15h2.1l.9-2.2zM12 5.98L13.87 11h-3.74L12 5.98z" /></React.Fragment> , 'TextFormatSharp');
packages/material-ui-icons/src/TextFormatSharp.js
0
https://github.com/mui/material-ui/commit/81ff109944bbb69cbb59dede3bc23a7e387b3ed3
[ 0.00016788022185210139, 0.00016788022185210139, 0.00016788022185210139, 0.00016788022185210139, 0 ]
{ "id": 3, "code_window": [ "// see https://github.com/ReactTraining/react-router/issues/6056#issuecomment-435524678\n", "const AdapterLink = React.forwardRef<HTMLAnchorElement, RouterLinkProps>((props, ref) => (\n", " <RouterLink innerRef={ref as any} {...props} />\n", "));\n", "\n", "type Omit<T, K> = Pick<T, Exclude<keyof T, K>>;\n", "const CollisionLink = React.forwardRef<HTMLAnchorElement, Omit<RouterLinkProps, 'innerRef' | 'to'>>(\n", " (props, ref) => (\n", " <RouterLink innerRef={ref as any} to=\"/getting-started/installation/\" {...props} />\n", " ),\n", ");\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "docs/src/pages/components/links/LinkRouter.tsx", "type": "replace", "edit_start_line_idx": 12 }
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <React.Fragment><path fill="none" d="M0 0h24v24H0V0z" /><g><path d="M15.67 4H14V2h-4v2H8.33C7.6 4 7 4.6 7 5.33v15.33C7 21.4 7.6 22 8.33 22h7.33c.74 0 1.34-.6 1.34-1.33V5.33C17 4.6 16.4 4 15.67 4zM11 20v-5.5H9L13 7v5.5h2L11 20z" /></g></React.Fragment> , 'BatteryChargingFullTwoTone');
packages/material-ui-icons/src/BatteryChargingFullTwoTone.js
0
https://github.com/mui/material-ui/commit/81ff109944bbb69cbb59dede3bc23a7e387b3ed3
[ 0.00016944532399065793, 0.00016944532399065793, 0.00016944532399065793, 0.00016944532399065793, 0 ]
{ "id": 3, "code_window": [ "// see https://github.com/ReactTraining/react-router/issues/6056#issuecomment-435524678\n", "const AdapterLink = React.forwardRef<HTMLAnchorElement, RouterLinkProps>((props, ref) => (\n", " <RouterLink innerRef={ref as any} {...props} />\n", "));\n", "\n", "type Omit<T, K> = Pick<T, Exclude<keyof T, K>>;\n", "const CollisionLink = React.forwardRef<HTMLAnchorElement, Omit<RouterLinkProps, 'innerRef' | 'to'>>(\n", " (props, ref) => (\n", " <RouterLink innerRef={ref as any} to=\"/getting-started/installation/\" {...props} />\n", " ),\n", ");\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "docs/src/pages/components/links/LinkRouter.tsx", "type": "replace", "edit_start_line_idx": 12 }
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <React.Fragment><path fill="none" d="M0 0h24v24H0V0z" /><g><path d="M19.23 15.26l-2.54-.29c-.61-.07-1.21.14-1.64.57l-1.84 1.84c-2.83-1.44-5.15-3.75-6.59-6.59l1.85-1.85c.43-.43.64-1.03.57-1.64l-.29-2.52c-.12-1.01-.97-1.77-1.99-1.77H5.03c-1.13 0-2.07.94-2 2.07.53 8.54 7.36 15.36 15.89 15.89 1.13.07 2.07-.87 2.07-2v-1.73c.01-1.01-.75-1.86-1.76-1.98z" /><path d="M13 11h4c.55 0 1-.45 1-1s-.45-1-1-1h-1.59l4.31-4.31c.39-.39.39-1.02 0-1.41s-1.02-.39-1.41 0L14 7.59V6c0-.55-.45-1-1-1s-1 .45-1 1v4c0 .55.45 1 1 1z" /></g></React.Fragment> , 'PhoneCallbackRounded');
packages/material-ui-icons/src/PhoneCallbackRounded.js
0
https://github.com/mui/material-ui/commit/81ff109944bbb69cbb59dede3bc23a7e387b3ed3
[ 0.0001649175537750125, 0.0001649175537750125, 0.0001649175537750125, 0.0001649175537750125, 0 ]
{ "id": 0, "code_window": [ " return reconcileFromExternalRouterImpl(this, component, data, escapeHatch, isTopLevel);\n", " }\n", "\n", " @Method()\n", " activateFromTab() {\n", " return activateFromTabImpl(this);\n", " }\n", "\n", " canSwipeBack(): boolean {\n", " return (this.swipeBackEnabled &&\n", " // this.childNavs.length === 0 &&\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " activateFromTab(tabAlreadySelected: boolean) {\n", " return activateFromTabImpl(this, tabAlreadySelected);\n" ], "file_path": "packages/core/src/components/nav/nav.tsx", "type": "replace", "edit_start_line_idx": 267 }
import { Component, Element, Event, EventEmitter, Method, Prop, State, Watch } from '@stencil/core'; import { FrameworkDelegate } from '../..'; import { asyncRaf, getIonApp, getNavAsChildIfExists } from '../../utils/helpers'; @Component({ tag: 'ion-tab', styleUrl: 'tab.scss' }) export class Tab { private loaded = false; @Element() el: HTMLElement; @State() init = false; @Prop() delegate: FrameworkDelegate; @Prop({ mutable: true }) active = false; @Prop() btnId: string; /** * The title of the tab. */ @Prop() title: string; /** * The icon for the tab. */ @Prop() icon: string; /** * The badge for the tab. */ @Prop() badge: string; /** * The badge color for the tab button. */ @Prop() badgeStyle = 'default'; /** * The component to display inside of the tab. */ @Prop() component: any; /** * The name of the tab. */ @Prop() name: string; /** * If true, the user cannot interact with the tab. Defaults to `false`. */ @Prop() disabled = false; /** * If true, the tab will be selected. Defaults to `false`. */ @Prop({ mutable: true }) selected = false; @Watch('selected') selectedChanged(selected: boolean) { if (selected) { this.ionSelect.emit(); } } /** * If true, the tab button is visible within the tabbar. Defaults to `true`. */ @Prop() show = true; /** * If true, hide the tabs on child pages. */ @Prop() tabsHideOnSubPages = false; /** * Emitted when the current tab is selected. */ @Event() ionSelect: EventEmitter<void>; @Method() getRouteId(): string|null { if (this.name) { return this.name; } if (typeof this.component === 'string') { return this.component; } return null; } @Method() setActive(): Promise<any> { return this.prepareLazyLoaded().then(() => this.showTab()); } private prepareLazyLoaded(): Promise<any> { if (!this.loaded && this.component) { this.loaded = true; const promise = (this.delegate) ? this.delegate.attachViewToDom(this.el, this.component) : attachViewToDom(this.el, this.component); return promise.then(() => asyncRaf()); } return Promise.resolve(); } private showTab(): Promise<any|void> { this.active = true; const nav = getNavAsChildIfExists(this.el); if (!nav) { return Promise.resolve(); } // the tab's nav has been initialized externally return getIonApp().then((ionApp) => { const externalNavPromise = ionApp ? ionApp.getExternalNavPromise() : null; if (externalNavPromise) { return (externalNavPromise as any).then(() => { ionApp.setExternalNavPromise(null); }); } // the tab's nav has not been initialized externally, so // check if we need to initiailize it return nav.componentOnReady() .then(() => nav.activateFromTab()); }); } hostData() { const hidden = !this.active || !this.selected; return { 'aria-hidden': hidden, 'aria-labelledby': this.btnId, 'role': 'tabpanel', class: { 'show-tab': this.active } }; } render() { return <slot/>; } } function attachViewToDom(container: HTMLElement, cmp: string): Promise<any> { const el = document.createElement(cmp) as HTMLStencilElement; container.appendChild(el); if (el.componentOnReady) { return el.componentOnReady(); } return Promise.resolve(); }
packages/core/src/components/tab/tab.tsx
1
https://github.com/ionic-team/ionic-framework/commit/cc1fc2e03221c51967e9b599d4e39fedaf289dcf
[ 0.9986315369606018, 0.05902770161628723, 0.00016627674631308764, 0.00017200397269334644, 0.2349013239145279 ]
{ "id": 0, "code_window": [ " return reconcileFromExternalRouterImpl(this, component, data, escapeHatch, isTopLevel);\n", " }\n", "\n", " @Method()\n", " activateFromTab() {\n", " return activateFromTabImpl(this);\n", " }\n", "\n", " canSwipeBack(): boolean {\n", " return (this.swipeBackEnabled &&\n", " // this.childNavs.length === 0 &&\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " activateFromTab(tabAlreadySelected: boolean) {\n", " return activateFromTabImpl(this, tabAlreadySelected);\n" ], "file_path": "packages/core/src/components/nav/nav.tsx", "type": "replace", "edit_start_line_idx": 267 }
// The file contents for the current environment will overwrite these during build. // The build system defaults to the dev environment which uses `environment.ts`, but if you do // `ng build --env=prod` then `environment.prod.ts` will be used instead. // The list of which env maps to which file can be found in `.angular-cli.json`. export const environment = { production: false };
packages/demos/conference-app/angular/src/environments/environment.ts
0
https://github.com/ionic-team/ionic-framework/commit/cc1fc2e03221c51967e9b599d4e39fedaf289dcf
[ 0.00017036421922966838, 0.00017036421922966838, 0.00017036421922966838, 0.00017036421922966838, 0 ]