hunk
dict
file
stringlengths
0
11.8M
file_path
stringlengths
2
234
label
int64
0
1
commit_url
stringlengths
74
103
dependency_score
sequencelengths
5
5
{ "id": 4, "code_window": [ "// tslint:disable-next-line:ban-types\n", "export default function translate<TKey extends string = string>(namespaces?: TKey[] | TKey, options?: TranslateOptions): <C extends Function>(WrappedComponent: C) => C;\n" ], "labels": [ "keep", "replace" ], "after_edit": [ "export default function translate<TKey extends string = string>(namespaces?: TKey[] | TKey, options?: TranslateOptions): InferableComponentEnhancerWithProps<\"t\">;" ], "file_path": "types/react-i18next/v4/translate.d.ts", "type": "replace", "edit_start_line_idx": 14 }
/*************************************************************************** * * * This file was automatically generated with idlc.js * * build info: * * - fibjs : 0.25.0 * * - date : Jun 12 2018 07:22:40 * * * ***************************************************************************/ /** * @author Richard <[email protected]> * */ /// <reference path="Buffer.d.ts" /> /// <reference path="BufferedStream.d.ts" /> /// <reference path="Chain.d.ts" /> /// <reference path="Cipher.d.ts" /> /// <reference path="Condition.d.ts" /> /// <reference path="DbConnection.d.ts" /> /// <reference path="DgramSocket.d.ts" /> /// <reference path="Digest.d.ts" /> /// <reference path="Event.d.ts" /> /// <reference path="EventEmitter.d.ts" /> /// <reference path="EventInfo.d.ts" /> /// <reference path="Fiber.d.ts" /> /// <reference path="File.d.ts" /> /// <reference path="Handler.d.ts" /> /// <reference path="HandlerEx.d.ts" /> /// <reference path="HeapGraphEdge.d.ts" /> /// <reference path="HeapGraphNode.d.ts" /> /// <reference path="HeapSnapshot.d.ts" /> /// <reference path="HttpClient.d.ts" /> /// <reference path="HttpCollection.d.ts" /> /// <reference path="HttpCookie.d.ts" /> /// <reference path="HttpHandler.d.ts" /> /// <reference path="HttpMessage.d.ts" /> /// <reference path="HttpRequest.d.ts" /> /// <reference path="HttpResponse.d.ts" /> /// <reference path="HttpServer.d.ts" /> /// <reference path="HttpUploadData.d.ts" /> /// <reference path="HttpsServer.d.ts" /> /// <reference path="Image.d.ts" /> /// <reference path="Int64.d.ts" /> /// <reference path="LevelDB.d.ts" /> /// <reference path="Lock.d.ts" /> /// <reference path="LruCache.d.ts" /> /// <reference path="MSSQL.d.ts" /> /// <reference path="MemoryStream.d.ts" /> /// <reference path="Message.d.ts" /> /// <reference path="MongoCollection.d.ts" /> /// <reference path="MongoCursor.d.ts" /> /// <reference path="MongoDB.d.ts" /> /// <reference path="MongoID.d.ts" /> /// <reference path="MySQL.d.ts" /> /// <reference path="PKey.d.ts" /> /// <reference path="Redis.d.ts" /> /// <reference path="RedisHash.d.ts" /> /// <reference path="RedisList.d.ts" /> /// <reference path="RedisSet.d.ts" /> /// <reference path="RedisSortedSet.d.ts" /> /// <reference path="Routing.d.ts" /> /// <reference path="SQLite.d.ts" /> /// <reference path="SandBox.d.ts" /> /// <reference path="SeekableStream.d.ts" /> /// <reference path="Semaphore.d.ts" /> /// <reference path="Service.d.ts" /> /// <reference path="Smtp.d.ts" /> /// <reference path="Socket.d.ts" /> /// <reference path="SslHandler.d.ts" /> /// <reference path="SslServer.d.ts" /> /// <reference path="SslSocket.d.ts" /> /// <reference path="Stat.d.ts" /> /// <reference path="Stats.d.ts" /> /// <reference path="Stream.d.ts" /> /// <reference path="StringDecoder.d.ts" /> /// <reference path="SubProcess.d.ts" /> /// <reference path="TcpServer.d.ts" /> /// <reference path="Timer.d.ts" /> /// <reference path="UrlObject.d.ts" /> /// <reference path="WebSocket.d.ts" /> /// <reference path="WebSocketMessage.d.ts" /> /// <reference path="WebView.d.ts" /> /// <reference path="Worker.d.ts" /> /// <reference path="X509Cert.d.ts" /> /// <reference path="X509Crl.d.ts" /> /// <reference path="X509Req.d.ts" /> /// <reference path="XmlAttr.d.ts" /> /// <reference path="XmlCDATASection.d.ts" /> /// <reference path="XmlCharacterData.d.ts" /> /// <reference path="XmlComment.d.ts" /> /// <reference path="XmlDocument.d.ts" /> /// <reference path="XmlDocumentType.d.ts" /> /// <reference path="XmlElement.d.ts" /> /// <reference path="XmlNamedNodeMap.d.ts" /> /// <reference path="XmlNode.d.ts" /> /// <reference path="XmlNodeList.d.ts" /> /// <reference path="XmlProcessingInstruction.d.ts" /> /// <reference path="XmlText.d.ts" /> /// <reference path="ZipFile.d.ts" /> /// <reference path="ZmqSocket.d.ts" /> /// <reference path="object.d.ts" /> /** module Or Internal Object */ /** * @brief 内存 profiler 模块 * @detail 使用方法:,```JavaScript,var profiler = require('profiler');,``` */ declare module "profiler" { module profiler { /** * * @brief 隐藏节点,当显示给用户时可以被过滤掉 * * */ export const Node_Hidden = 0; /** * * @brief 数组 * * */ export const Node_Array = 1; /** * * @brief 字符串 * * */ export const Node_String = 2; /** * * @brief JS对象(字符串和数组除外) * * */ export const Node_Object = 3; /** * * @brief 编译后的代码 * * */ export const Node_Code = 4; /** * * @brief 函数闭包 * * */ export const Node_Closure = 5; /** * * @brief 正则表达式 * * */ export const Node_RegExp = 6; /** * * @brief 堆中排好序的数字 * * */ export const Node_HeapNumber = 7; /** * * @brief Native对象(非v8堆上的) * * */ export const Node_Native = 8; /** * * @brief Synthetic对象 * * */ export const Node_Synthetic = 9; /** * * @brief 拼接的字符串 * * */ export const Node_ConsString = 10; /** * * @brief 分割的字符串 * * */ export const Node_SlicedString = 11; /** * * @brief 符号(ES6) * * */ export const Node_Symbol = 12; /** * * @brief 堆中排好序的SIMD值(ES7) * * */ export const Node_SimdValue = 13; /** * * @brief 函数中的变量 * * */ export const Edge_ContextVariable = 0; /** * * @brief 数组中的元素 * * */ export const Edge_Element = 1; /** * * @brief 有名对象的属性 * * */ export const Edge_Property = 2; /** * * @brief JS无法进入的链接 * * */ export const Edge_Internal = 3; /** * * @brief 指向需要事先计算出空间大小的节点 * * */ export const Edge_Hidden = 4; /** * * @brief 指向无法事先计算出空间大小的节点 * * */ export const Edge_Shortcut = 5; /** * * @brief 一个弱引用(被GC忽视) * * */ export const Edge_Weak = 6; /** * * @brief 根据指定名称保存一个堆快照 * @param fname 堆快照名称 * * * */ export function saveSnapshot(fname: string): void; /** * * @brief 根据指定名称读取一个堆快照 * @param fname 堆快照名称 * @return 返回读取到的堆快照 * * * */ export function loadSnapshot(fname: string): Class_HeapSnapshot; /** * * @brief 获取当前时间节点的堆快照,堆快照记录了当前时刻JS堆的状态 * @return 返回获取到的堆信息快照 * * * */ export function takeSnapshot(): Class_HeapSnapshot; /** * * @brief 执行给定的函数,并对比执行前后 v8 堆的变化 * @param test 给定要测试的函数 * @return 返回对比的结果 * * * */ export function diff(test: Function): object; /** * * @brief 启动一次运行状态采样日志 * @param fname 给定日志存储文件名 * @param time 指定采样时间,缺省 1 分钟 * @param interval 指定间隔时间,缺省 100 毫秒 * @return 返回采样定时器,可以通过 clear 方法提前停止采样 * * * */ export function start(fname: string, time?: number/** = 60000*/, interval?: number/** = 100*/): Class_Timer; } /** end of `module profiler` */ export = profiler } /** endof `module Or Internal Object` */
types/fibjs/declare/profiler.d.ts
0
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/9440fd14094e78c2db7345583a3aba9b36f0eefb
[ 0.0002088733162963763, 0.00017255739658139646, 0.0001655930682318285, 0.0001714500249363482, 0.000006219141141627915 ]
{ "id": 4, "code_window": [ "// tslint:disable-next-line:ban-types\n", "export default function translate<TKey extends string = string>(namespaces?: TKey[] | TKey, options?: TranslateOptions): <C extends Function>(WrappedComponent: C) => C;\n" ], "labels": [ "keep", "replace" ], "after_edit": [ "export default function translate<TKey extends string = string>(namespaces?: TKey[] | TKey, options?: TranslateOptions): InferableComponentEnhancerWithProps<\"t\">;" ], "file_path": "types/react-i18next/v4/translate.d.ts", "type": "replace", "edit_start_line_idx": 14 }
import * as React from 'react'; import { IconBaseProps } from 'react-icon-base'; export default class IoIosMic extends React.Component<IconBaseProps> { }
types/react-icons/io/ios-mic.d.ts
0
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/9440fd14094e78c2db7345583a3aba9b36f0eefb
[ 0.0001693102967692539, 0.0001693102967692539, 0.0001693102967692539, 0.0001693102967692539, 0 ]
{ "id": 0, "code_window": [ " receiverType: string,\n", " query: (isNot: boolean, timeout: number) => Promise<{ matches: boolean, log?: string[] }>,\n", " options: { timeout?: number } = {},\n", ") {\n", " const testInfo = currentTestInfo();\n", " if (!testInfo)\n", " throw new Error(`${matcherName} must be called during the test`);\n", " expectType(receiver, receiverType, matcherName);\n", "\n", " const matcherOptions = {\n", " isNot: this.isNot,\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "packages/playwright-test/src/matchers/toBeTruthy.ts", "type": "replace", "edit_start_line_idx": 29 }
/** * Copyright Microsoft Corporation. All rights reserved. * * 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 { currentTestInfo } from '../globals'; import type { Expect } from '../types'; import { expectType } from '../util'; import { callLogText } from './toMatchText'; export async function toBeTruthy( this: ReturnType<Expect['getState']>, matcherName: string, receiver: any, receiverType: string, query: (isNot: boolean, timeout: number) => Promise<{ matches: boolean, log?: string[] }>, options: { timeout?: number } = {}, ) { const testInfo = currentTestInfo(); if (!testInfo) throw new Error(`${matcherName} must be called during the test`); expectType(receiver, receiverType, matcherName); const matcherOptions = { isNot: this.isNot, promise: this.promise, }; let defaultExpectTimeout = testInfo.project.expect?.timeout; if (typeof defaultExpectTimeout === 'undefined') defaultExpectTimeout = 5000; const timeout = options.timeout === 0 ? 0 : options.timeout || defaultExpectTimeout; const { matches, log } = await query(this.isNot, timeout); const message = () => { return this.utils.matcherHint(matcherName, undefined, '', matcherOptions) + callLogText(log); }; return { message, pass: matches }; }
packages/playwright-test/src/matchers/toBeTruthy.ts
1
https://github.com/microsoft/playwright/commit/9d03a85c3039fcc968aa7d29777bbca85789fd4a
[ 0.9983799457550049, 0.4991196095943451, 0.00016564881661906838, 0.49902915954589844, 0.49894872307777405 ]
{ "id": 0, "code_window": [ " receiverType: string,\n", " query: (isNot: boolean, timeout: number) => Promise<{ matches: boolean, log?: string[] }>,\n", " options: { timeout?: number } = {},\n", ") {\n", " const testInfo = currentTestInfo();\n", " if (!testInfo)\n", " throw new Error(`${matcherName} must be called during the test`);\n", " expectType(receiver, receiverType, matcherName);\n", "\n", " const matcherOptions = {\n", " isNot: this.isNot,\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "packages/playwright-test/src/matchers/toBeTruthy.ts", "type": "replace", "edit_start_line_idx": 29 }
/** * Copyright Microsoft Corporation. All rights reserved. * * 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 colors from 'colors/safe'; import * as fs from 'fs'; import * as path from 'path'; import { test, expect, stripAscii } from './playwright-test-fixtures'; const files = { 'helper.ts': ` export const test = pwt.test.extend({ auto: [ async ({}, run, testInfo) => { testInfo.snapshotSuffix = ''; await run(); }, { auto: true } ] }); ` }; test('should support golden', async ({ runInlineTest }) => { const result = await runInlineTest({ ...files, 'a.spec.js-snapshots/snapshot.txt': `Hello world`, 'a.spec.js': ` const { test } = require('./helper'); test('is a test', ({}) => { expect('Hello world').toMatchSnapshot('snapshot.txt'); }); ` }); expect(result.exitCode).toBe(0); }); test('should fail on wrong golden', async ({ runInlineTest }) => { const result = await runInlineTest({ ...files, 'a.spec.js-snapshots/snapshot.txt': `Line1 Line2 Line3 Hello world line1 Line5 Line6 Line7`, 'a.spec.js': ` const { test } = require('./helper'); test('is a test', ({}) => { const data = []; data.push('Line1'); data.push('Line22'); data.push('Line3'); data.push('Hi world line2'); data.push('Line5'); data.push('Line6'); data.push('Line7'); expect(data.join('\\n')).toMatchSnapshot('snapshot.txt'); }); ` }); expect(result.exitCode).toBe(1); expect(result.output).toContain('Line1'); expect(result.output).toContain('Line2' + colors.green('2')); expect(result.output).toContain('line' + colors.strikethrough(colors.red('1')) + colors.green('2')); expect(result.output).toContain('Line3'); expect(result.output).toContain('Line5'); expect(result.output).toContain('Line7'); }); test('should write detailed failure result to an output folder', async ({ runInlineTest }, testInfo) => { const result = await runInlineTest({ ...files, 'a.spec.js-snapshots/snapshot.txt': `Hello world`, 'a.spec.js': ` const { test } = require('./helper'); test('is a test', ({}) => { expect('Hello world updated').toMatchSnapshot('snapshot.txt'); }); ` }); expect(result.exitCode).toBe(1); const outputText = stripAscii(result.output); expect(outputText).toContain('Snapshot comparison failed:'); const expectedSnapshotArtifactPath = testInfo.outputPath('test-results', 'a-is-a-test', 'snapshot-expected.txt'); const actualSnapshotArtifactPath = testInfo.outputPath('test-results', 'a-is-a-test', 'snapshot-actual.txt'); expect(outputText).toContain(`Expected: ${expectedSnapshotArtifactPath}`); expect(outputText).toContain(`Received: ${actualSnapshotArtifactPath}`); expect(fs.existsSync(expectedSnapshotArtifactPath)).toBe(true); expect(fs.existsSync(actualSnapshotArtifactPath)).toBe(true); }); test("doesn\'t create comparison artifacts in an output folder for passed negated snapshot matcher", async ({ runInlineTest }, testInfo) => { const result = await runInlineTest({ ...files, 'a.spec.js-snapshots/snapshot.txt': `Hello world`, 'a.spec.js': ` const { test } = require('./helper'); test('is a test', ({}) => { expect('Hello world updated').not.toMatchSnapshot('snapshot.txt'); }); ` }); expect(result.exitCode).toBe(0); const outputText = stripAscii(result.output); const expectedSnapshotArtifactPath = testInfo.outputPath('test-results', 'a-is-a-test', 'snapshot-expected.txt'); const actualSnapshotArtifactPath = testInfo.outputPath('test-results', 'a-is-a-test', 'snapshot-actual.txt'); expect(outputText).not.toContain(`Expected: ${expectedSnapshotArtifactPath}`); expect(outputText).not.toContain(`Received: ${actualSnapshotArtifactPath}`); expect(fs.existsSync(expectedSnapshotArtifactPath)).toBe(false); expect(fs.existsSync(actualSnapshotArtifactPath)).toBe(false); }); test('should pass on different snapshots with negate matcher', async ({ runInlineTest }) => { const result = await runInlineTest({ ...files, 'a.spec.js-snapshots/snapshot.txt': `Hello world`, 'a.spec.js': ` const { test } = require('./helper'); test('is a test', ({}) => { expect('Hello world updated').not.toMatchSnapshot('snapshot.txt'); }); ` }); expect(result.exitCode).toBe(0); }); test('should fail on same snapshots with negate matcher', async ({ runInlineTest }) => { const result = await runInlineTest({ ...files, 'a.spec.js-snapshots/snapshot.txt': `Hello world`, 'a.spec.js': ` const { test } = require('./helper'); test('is a test', ({}) => { expect('Hello world').not.toMatchSnapshot('snapshot.txt'); }); ` }); expect(result.exitCode).toBe(1); expect(result.output).toContain('Snapshot comparison failed:'); expect(result.output).toContain('Expected result should be different from the actual one.'); }); test('should write missing expectations locally', async ({ runInlineTest }, testInfo) => { const result = await runInlineTest({ ...files, 'a.spec.js': ` const { test } = require('./helper'); test('is a test', ({}) => { expect('Hello world').toMatchSnapshot('snapshot.txt'); }); ` }, {}, { CI: '' }); expect(result.exitCode).toBe(1); const snapshotOutputPath = testInfo.outputPath('a.spec.js-snapshots/snapshot.txt'); expect(result.output).toContain(`${snapshotOutputPath} is missing in snapshots, writing actual`); const data = fs.readFileSync(snapshotOutputPath); expect(data.toString()).toBe('Hello world'); }); test('shouldn\'t write missing expectations locally for negated matcher', async ({ runInlineTest }, testInfo) => { const result = await runInlineTest({ ...files, 'a.spec.js': ` const { test } = require('./helper'); test('is a test', ({}) => { expect('Hello world').not.toMatchSnapshot('snapshot.txt'); }); ` }, {}, { CI: '' }); expect(result.exitCode).toBe(1); const snapshotOutputPath = testInfo.outputPath('a.spec.js-snapshots/snapshot.txt'); expect(result.output).toContain(`${snapshotOutputPath} is missing in snapshots, matchers using ".not" won\'t write them automatically.`); expect(fs.existsSync(snapshotOutputPath)).toBe(false); }); test('should update snapshot with the update-snapshots flag', async ({ runInlineTest }, testInfo) => { const EXPECTED_SNAPSHOT = 'Hello world'; const ACTUAL_SNAPSHOT = 'Hello world updated'; const result = await runInlineTest({ ...files, 'a.spec.js-snapshots/snapshot.txt': EXPECTED_SNAPSHOT, 'a.spec.js': ` const { test } = require('./helper'); test('is a test', ({}) => { expect('${ACTUAL_SNAPSHOT}').toMatchSnapshot('snapshot.txt'); }); ` }, { 'update-snapshots': true }); expect(result.exitCode).toBe(0); const snapshotOutputPath = testInfo.outputPath('a.spec.js-snapshots/snapshot.txt'); expect(result.output).toContain(`${snapshotOutputPath} does not match, writing actual.`); const data = fs.readFileSync(snapshotOutputPath); expect(data.toString()).toBe(ACTUAL_SNAPSHOT); }); test('shouldn\'t update snapshot with the update-snapshots flag for negated matcher', async ({ runInlineTest }, testInfo) => { const EXPECTED_SNAPSHOT = 'Hello world'; const ACTUAL_SNAPSHOT = 'Hello world updated'; const result = await runInlineTest({ ...files, 'a.spec.js-snapshots/snapshot.txt': EXPECTED_SNAPSHOT, 'a.spec.js': ` const { test } = require('./helper'); test('is a test', ({}) => { expect('${ACTUAL_SNAPSHOT}').not.toMatchSnapshot('snapshot.txt'); }); ` }, { 'update-snapshots': true }); expect(result.exitCode).toBe(0); const snapshotOutputPath = testInfo.outputPath('a.spec.js-snapshots/snapshot.txt'); const data = fs.readFileSync(snapshotOutputPath); expect(data.toString()).toBe(EXPECTED_SNAPSHOT); }); test('should silently write missing expectations locally with the update-snapshots flag', async ({ runInlineTest }, testInfo) => { const ACTUAL_SNAPSHOT = 'Hello world new'; const result = await runInlineTest({ ...files, 'a.spec.js': ` const { test } = require('./helper'); test('is a test', ({}) => { expect('${ACTUAL_SNAPSHOT}').toMatchSnapshot('snapshot.txt'); }); ` }, { 'update-snapshots': true }); expect(result.exitCode).toBe(0); const snapshotOutputPath = testInfo.outputPath('a.spec.js-snapshots/snapshot.txt'); expect(result.output).toContain(`${snapshotOutputPath} is missing in snapshots, writing actual`); const data = fs.readFileSync(snapshotOutputPath); expect(data.toString()).toBe(ACTUAL_SNAPSHOT); }); test('should silently write missing expectations locally with the update-snapshots flag for negated matcher', async ({ runInlineTest }, testInfo) => { const result = await runInlineTest({ ...files, 'a.spec.js': ` const { test } = require('./helper'); test('is a test', ({}) => { expect('Hello world').not.toMatchSnapshot('snapshot.txt'); }); ` }, { 'update-snapshots': true }); expect(result.exitCode).toBe(1); const snapshotOutputPath = testInfo.outputPath('a.spec.js-snapshots/snapshot.txt'); expect(result.output).toContain(`${snapshotOutputPath} is missing in snapshots, matchers using ".not" won\'t write them automatically.`); expect(fs.existsSync(snapshotOutputPath)).toBe(false); }); test('should match multiple snapshots', async ({ runInlineTest }) => { const result = await runInlineTest({ ...files, 'a.spec.js-snapshots/snapshot1.txt': `Snapshot1`, 'a.spec.js-snapshots/snapshot2.txt': `Snapshot2`, 'a.spec.js-snapshots/snapshot3.txt': `Snapshot3`, 'a.spec.js': ` const { test } = require('./helper'); test('is a test', ({}) => { expect('Snapshot1').toMatchSnapshot('snapshot1.txt'); expect('Snapshot2').toMatchSnapshot('snapshot2.txt'); expect('Snapshot3').toMatchSnapshot('snapshot3.txt'); }); ` }); expect(result.exitCode).toBe(0); }); test('should match snapshots from multiple projects', async ({ runInlineTest }) => { const result = await runInlineTest({ ...files, 'playwright.config.ts': ` import * as path from 'path'; module.exports = { projects: [ { testDir: path.join(__dirname, 'p1') }, { testDir: path.join(__dirname, 'p2') }, ]}; `, 'p1/a.spec.js': ` const { test } = require('../helper'); test('is a test', ({}) => { expect('Snapshot1').toMatchSnapshot('snapshot.txt'); }); `, 'p1/a.spec.js-snapshots/snapshot.txt': `Snapshot1`, 'p2/a.spec.js': ` const { test } = require('../helper'); test('is a test', ({}) => { expect('Snapshot2').toMatchSnapshot('snapshot.txt'); }); `, 'p2/a.spec.js-snapshots/snapshot.txt': `Snapshot2`, }); expect(result.exitCode).toBe(0); }); test('should use provided name', async ({ runInlineTest }) => { const result = await runInlineTest({ ...files, 'a.spec.js-snapshots/provided.txt': `Hello world`, 'a.spec.js': ` const { test } = require('./helper'); test('is a test', ({}) => { expect('Hello world').toMatchSnapshot('provided.txt'); }); ` }); expect(result.exitCode).toBe(0); }); test('should throw without a name', async ({ runInlineTest }) => { const result = await runInlineTest({ ...files, 'a.spec.js': ` const { test } = require('./helper'); test('is a test', ({}) => { expect('Hello world').toMatchSnapshot(); }); ` }); expect(result.exitCode).toBe(1); expect(result.output).toContain('toMatchSnapshot() requires a "name" parameter'); }); test('should use provided name via options', async ({ runInlineTest }) => { const result = await runInlineTest({ ...files, 'a.spec.js-snapshots/provided.txt': `Hello world`, 'a.spec.js': ` const { test } = require('./helper'); test('is a test', ({}) => { expect('Hello world').toMatchSnapshot({ name: 'provided.txt' }); }); ` }); expect(result.exitCode).toBe(0); }); test('should compare binary', async ({ runInlineTest }) => { const result = await runInlineTest({ ...files, 'a.spec.js-snapshots/snapshot.dat': Buffer.from([1, 2, 3, 4]), 'a.spec.js': ` const { test } = require('./helper'); test('is a test', ({}) => { expect(Buffer.from([1,2,3,4])).toMatchSnapshot('snapshot.dat'); }); ` }); expect(result.exitCode).toBe(0); }); test('should compare PNG images', async ({ runInlineTest }) => { const result = await runInlineTest({ ...files, 'a.spec.js-snapshots/snapshot.png': Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+P+/HgAFhAJ/wlseKgAAAABJRU5ErkJggg==', 'base64'), 'a.spec.js': ` const { test } = require('./helper'); test('is a test', ({}) => { expect(Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+P+/HgAFhAJ/wlseKgAAAABJRU5ErkJggg==', 'base64')).toMatchSnapshot('snapshot.png'); }); ` }); expect(result.exitCode).toBe(0); }); test('should compare different PNG images', async ({ runInlineTest }, testInfo) => { const result = await runInlineTest({ ...files, 'a.spec.js-snapshots/snapshot.png': Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+P+/HgAFhAJ/wlseKgAAAABJRU5ErkJggg==', 'base64'), 'a.spec.js': ` const { test } = require('./helper'); test('is a test', ({}) => { expect(Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVQYV2NgYAAAAAMAAWgmWQ0AAAAASUVORK5CYII==', 'base64')).toMatchSnapshot('snapshot.png'); }); ` }); const outputText = stripAscii(result.output); expect(result.exitCode).toBe(1); expect(outputText).toContain('Snapshot comparison failed:'); const expectedSnapshotArtifactPath = testInfo.outputPath('test-results', 'a-is-a-test', 'snapshot-expected.png'); const actualSnapshotArtifactPath = testInfo.outputPath('test-results', 'a-is-a-test', 'snapshot-actual.png'); const diffSnapshotArtifactPath = testInfo.outputPath('test-results', 'a-is-a-test', 'snapshot-diff.png'); expect(outputText).toContain(`Expected: ${expectedSnapshotArtifactPath}`); expect(outputText).toContain(`Received: ${actualSnapshotArtifactPath}`); expect(outputText).toContain(`Diff: ${diffSnapshotArtifactPath}`); expect(fs.existsSync(expectedSnapshotArtifactPath)).toBe(true); expect(fs.existsSync(actualSnapshotArtifactPath)).toBe(true); expect(fs.existsSync(diffSnapshotArtifactPath)).toBe(true); }); test('should respect threshold', async ({ runInlineTest }) => { const expected = fs.readFileSync(path.join(__dirname, 'assets/screenshot-canvas-expected.png')); const actual = fs.readFileSync(path.join(__dirname, 'assets/screenshot-canvas-actual.png')); const result = await runInlineTest({ ...files, 'a.spec.js-snapshots/snapshot.png': expected, 'a.spec.js-snapshots/snapshot2.png': expected, 'a.spec.js': ` const { test } = require('./helper'); test('is a test', ({}) => { expect(Buffer.from('${actual.toString('base64')}', 'base64')).toMatchSnapshot('snapshot.png', { threshold: 0.3 }); expect(Buffer.from('${actual.toString('base64')}', 'base64')).not.toMatchSnapshot('snapshot.png', { threshold: 0.2 }); expect(Buffer.from('${actual.toString('base64')}', 'base64')).toMatchSnapshot('snapshot2.png', { threshold: 0.3 }); expect(Buffer.from('${actual.toString('base64')}', 'base64')).toMatchSnapshot({ name: 'snapshot2.png', threshold: 0.3 }); }); ` }); expect(result.exitCode).toBe(0); }); test('should respect project threshold', async ({ runInlineTest }) => { const expected = fs.readFileSync(path.join(__dirname, 'assets/screenshot-canvas-expected.png')); const actual = fs.readFileSync(path.join(__dirname, 'assets/screenshot-canvas-actual.png')); const result = await runInlineTest({ ...files, 'playwright.config.ts': ` module.exports = { projects: [ { expect: { toMatchSnapshot: { threshold: 0.2 } } }, ]}; `, 'a.spec.js-snapshots/snapshot.png': expected, 'a.spec.js-snapshots/snapshot2.png': expected, 'a.spec.js': ` const { test } = require('./helper'); test('is a test', ({}) => { expect(Buffer.from('${actual.toString('base64')}', 'base64')).toMatchSnapshot('snapshot.png', { threshold: 0.3 }); expect(Buffer.from('${actual.toString('base64')}', 'base64')).not.toMatchSnapshot('snapshot.png'); expect(Buffer.from('${actual.toString('base64')}', 'base64')).toMatchSnapshot('snapshot2.png', { threshold: 0.3 }); expect(Buffer.from('${actual.toString('base64')}', 'base64')).toMatchSnapshot({ name: 'snapshot2.png', threshold: 0.3 }); }); ` }); expect(result.exitCode).toBe(0); }); test('should sanitize snapshot name when passed as string', async ({ runInlineTest }) => { const result = await runInlineTest({ ...files, 'a.spec.js-snapshots/-snapshot-.txt': `Hello world`, 'a.spec.js': ` const { test } = require('./helper');; test('is a test', ({}) => { expect('Hello world').toMatchSnapshot('../../snapshot!.txt'); }); ` }); expect(result.exitCode).toBe(0); }); test('should write missing expectations with sanitized snapshot name', async ({ runInlineTest }, testInfo) => { const result = await runInlineTest({ ...files, 'a.spec.js': ` const { test } = require('./helper');; test('is a test', ({}) => { expect('Hello world').toMatchSnapshot('../../snapshot!.txt'); }); ` }, {}, { CI: '' }); expect(result.exitCode).toBe(1); const snapshotOutputPath = testInfo.outputPath('a.spec.js-snapshots/-snapshot-.txt'); expect(result.output).toContain(`${snapshotOutputPath} is missing in snapshots, writing actual`); const data = fs.readFileSync(snapshotOutputPath); expect(data.toString()).toBe('Hello world'); }); test('should join array of snapshot path segments without sanitizing ', async ({ runInlineTest }) => { const result = await runInlineTest({ ...files, 'a.spec.js-snapshots/test/path/snapshot.txt': `Hello world`, 'a.spec.js': ` const { test } = require('./helper');; test('is a test', ({}) => { expect('Hello world').toMatchSnapshot(['test', 'path', 'snapshot.txt']); }); ` }); expect(result.exitCode).toBe(0); }); test('should update snapshot with array of path segments', async ({ runInlineTest }, testInfo) => { const result = await runInlineTest({ ...files, 'a.spec.js': ` const { test } = require('./helper'); test('is a test', ({}) => { expect('Hello world').toMatchSnapshot(['test', 'path', 'snapshot.txt']); }); ` }, { 'update-snapshots': true }); expect(result.exitCode).toBe(0); const snapshotOutputPath = testInfo.outputPath('a.spec.js-snapshots/test/path/snapshot.txt'); expect(result.output).toContain(`${snapshotOutputPath} is missing in snapshots, writing actual`); const data = fs.readFileSync(snapshotOutputPath); expect(data.toString()).toBe('Hello world'); }); test('should attach expected/actual/diff with snapshot path', async ({ runInlineTest }, testInfo) => { const result = await runInlineTest({ ...files, 'a.spec.js-snapshots/test/path/snapshot.png': Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+P+/HgAFhAJ/wlseKgAAAABJRU5ErkJggg==', 'base64'), 'a.spec.js': ` const { test } = require('./helper'); test.afterEach(async ({}, testInfo) => { console.log('## ' + JSON.stringify(testInfo.attachments)); }); test('is a test', ({}) => { expect(Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVQYV2NgYAAAAAMAAWgmWQ0AAAAASUVORK5CYII==', 'base64')).toMatchSnapshot(['test', 'path', 'snapshot.png']); }); ` }); const outputText = stripAscii(result.output); const attachments = outputText.split('\n').filter(l => l.startsWith('## ')).map(l => l.substring(3)).map(l => JSON.parse(l))[0]; for (const attachment of attachments) attachment.path = attachment.path.replace(/\\/g, '/').replace(/.*test-results\//, ''); expect(attachments).toEqual([ { name: 'expected', contentType: 'image/png', path: 'a-is-a-test/test/path/snapshot-expected.png' }, { name: 'actual', contentType: 'image/png', path: 'a-is-a-test/test/path/snapshot-actual.png' }, { name: 'diff', contentType: 'image/png', path: 'a-is-a-test/test/path/snapshot-diff.png' } ]); }); test('should attach expected/actual/diff', async ({ runInlineTest }, testInfo) => { const result = await runInlineTest({ ...files, 'a.spec.js-snapshots/snapshot.png': Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+P+/HgAFhAJ/wlseKgAAAABJRU5ErkJggg==', 'base64'), 'a.spec.js': ` const { test } = require('./helper'); test.afterEach(async ({}, testInfo) => { console.log('## ' + JSON.stringify(testInfo.attachments)); }); test('is a test', ({}) => { expect(Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVQYV2NgYAAAAAMAAWgmWQ0AAAAASUVORK5CYII==', 'base64')).toMatchSnapshot('snapshot.png'); }); ` }); const outputText = stripAscii(result.output); const attachments = outputText.split('\n').filter(l => l.startsWith('## ')).map(l => l.substring(3)).map(l => JSON.parse(l))[0]; for (const attachment of attachments) attachment.path = attachment.path.replace(/\\/g, '/').replace(/.*test-results\//, ''); expect(attachments).toEqual([ { name: 'expected', contentType: 'image/png', path: 'a-is-a-test/snapshot-expected.png' }, { name: 'actual', contentType: 'image/png', path: 'a-is-a-test/snapshot-actual.png' }, { name: 'diff', contentType: 'image/png', path: 'a-is-a-test/snapshot-diff.png' } ]); }); test('should attach expected/actual and no diff', async ({ runInlineTest }, testInfo) => { const result = await runInlineTest({ ...files, 'a.spec.js-snapshots/snapshot.png': Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAIAAAACCAYAAABytg0kAAAAEklEQVR42mP8z8AARAwMjDAGACwBA/9IB8FMAAAAAElFTkSuQmCC', 'base64'), 'a.spec.js': ` const { test } = require('./helper'); test.afterEach(async ({}, testInfo) => { console.log('## ' + JSON.stringify(testInfo.attachments)); }); test('is a test', ({}) => { expect(Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVQYV2NgYAAAAAMAAWgmWQ0AAAAASUVORK5CYII==', 'base64')).toMatchSnapshot('snapshot.png'); }); ` }); const outputText = stripAscii(result.output); expect(outputText).toContain('Sizes differ; expected image 2px X 2px, but got 1px X 1px.'); const attachments = outputText.split('\n').filter(l => l.startsWith('## ')).map(l => l.substring(3)).map(l => JSON.parse(l))[0]; for (const attachment of attachments) attachment.path = attachment.path.replace(/\\/g, '/').replace(/.*test-results\//, ''); expect(attachments).toEqual([ { name: 'expected', contentType: 'image/png', path: 'a-is-a-test/snapshot-expected.png' }, { name: 'actual', contentType: 'image/png', path: 'a-is-a-test/snapshot-actual.png' }, ]); }); test('should fail with missing expectations and retries', async ({ runInlineTest }, testInfo) => { const result = await runInlineTest({ ...files, 'playwright.config.ts': ` module.exports = { retries: 1 }; `, 'a.spec.js': ` const { test } = require('./helper'); test('is a test', ({}) => { expect('Hello world').toMatchSnapshot('snapshot.txt'); }); ` }); expect(result.exitCode).toBe(1); expect(result.failed).toBe(1); const snapshotOutputPath = testInfo.outputPath('a.spec.js-snapshots/snapshot.txt'); expect(result.output).toContain(`${snapshotOutputPath} is missing in snapshots, writing actual`); const data = fs.readFileSync(snapshotOutputPath); expect(data.toString()).toBe('Hello world'); }); test('should allow comparing text with text without file extension', async ({ runInlineTest }) => { const result = await runInlineTest({ ...files, 'a.spec.js-snapshots/snapshot-no-extension': `Hello world`, 'a.spec.js': ` const { test } = require('./helper'); test('is a test', ({}) => { expect('Hello world').toMatchSnapshot('snapshot-no-extension'); }); ` }); expect(result.exitCode).toBe(0); });
tests/playwright-test/golden.spec.ts
0
https://github.com/microsoft/playwright/commit/9d03a85c3039fcc968aa7d29777bbca85789fd4a
[ 0.9872318506240845, 0.12719833850860596, 0.00016780242731329054, 0.00017808136180974543, 0.2742171883583069 ]
{ "id": 0, "code_window": [ " receiverType: string,\n", " query: (isNot: boolean, timeout: number) => Promise<{ matches: boolean, log?: string[] }>,\n", " options: { timeout?: number } = {},\n", ") {\n", " const testInfo = currentTestInfo();\n", " if (!testInfo)\n", " throw new Error(`${matcherName} must be called during the test`);\n", " expectType(receiver, receiverType, matcherName);\n", "\n", " const matcherOptions = {\n", " isNot: this.isNot,\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "packages/playwright-test/src/matchers/toBeTruthy.ts", "type": "replace", "edit_start_line_idx": 29 }
const path = require('path'); const HtmlWebPackPlugin = require('html-webpack-plugin'); const CopyPlugin = require('copy-webpack-plugin'); const mode = process.env.NODE_ENV === 'production' ? 'production' : 'development'; module.exports = { mode, entry: { app: path.join(__dirname, 'index.tsx'), }, resolve: { extensions: ['.ts', '.js', '.tsx', '.jsx'] }, devtool: mode === 'production' ? false : 'source-map', output: { globalObject: 'self', filename: '[name].bundle.js', path: path.resolve(__dirname, '../../../lib/webpack/traceViewer') }, module: { rules: [ { test: /\.(j|t)sx?$/, loader: 'babel-loader', options: { presets: [ "@babel/preset-typescript", "@babel/preset-react" ] }, exclude: /node_modules/ }, { test: /\.css$/, use: ['style-loader', 'css-loader'] }, ] }, plugins: [ new CopyPlugin({ patterns: [ { from: path.resolve(__dirname, '../../../../../node_modules/@zip.js/zip.js/dist/zip-no-worker-inflate.min.js'), to: 'zip.min.js' }, ], }), new CopyPlugin({ patterns: [ { from: path.resolve(__dirname, 'static'), }, ], }), new HtmlWebPackPlugin({ title: 'Playwright Trace Viewer', template: path.join(__dirname, 'index.html'), }) ] };
packages/playwright-core/src/web/traceViewer/webpack.config.js
0
https://github.com/microsoft/playwright/commit/9d03a85c3039fcc968aa7d29777bbca85789fd4a
[ 0.0001763285108609125, 0.0001741183368721977, 0.0001709829521132633, 0.00017423287499696016, 0.000001486121959715092 ]
{ "id": 0, "code_window": [ " receiverType: string,\n", " query: (isNot: boolean, timeout: number) => Promise<{ matches: boolean, log?: string[] }>,\n", " options: { timeout?: number } = {},\n", ") {\n", " const testInfo = currentTestInfo();\n", " if (!testInfo)\n", " throw new Error(`${matcherName} must be called during the test`);\n", " expectType(receiver, receiverType, matcherName);\n", "\n", " const matcherOptions = {\n", " isNot: this.isNot,\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "packages/playwright-test/src/matchers/toBeTruthy.ts", "type": "replace", "edit_start_line_idx": 29 }
# Project-wide Gradle settings. # IDE (e.g. Android Studio) users: # Gradle settings configured through the IDE *will override* # any settings specified in this file. # For more details on how to configure your build environment visit # http://www.gradle.org/docs/current/userguide/build_environment.html # Specifies the JVM arguments used for the daemon process. # The setting is particularly useful for tweaking memory settings. org.gradle.jvmargs=-Xmx2048m -Dfile.encoding=UTF-8 # When configured, Gradle will run in incubating parallel mode. # This option should only be used with decoupled projects. More details, visit # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects # org.gradle.parallel=true # AndroidX package structure to make it clearer which packages are bundled with the # Android operating system, and which are packaged with your app"s APK # https://developer.android.com/topic/libraries/support-library/androidx-rn android.useAndroidX=true # Automatically convert third-party libraries to use AndroidX android.enableJetifier=true
packages/playwright-core/src/server/android/driver/gradle.properties
0
https://github.com/microsoft/playwright/commit/9d03a85c3039fcc968aa7d29777bbca85789fd4a
[ 0.00017387607658747584, 0.00017307192320004106, 0.00017226775526069105, 0.00017307192320004106, 8.041606633923948e-7 ]
{ "id": 1, "code_window": [ " const matcherOptions = {\n", " isNot: this.isNot,\n", " promise: this.promise,\n", " };\n", "\n", " let defaultExpectTimeout = testInfo.project.expect?.timeout;\n", " if (typeof defaultExpectTimeout === 'undefined')\n", " defaultExpectTimeout = 5000;\n", " const timeout = options.timeout === 0 ? 0 : options.timeout || defaultExpectTimeout;\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " const testInfo = currentTestInfo();\n", " let defaultExpectTimeout = testInfo?.project.expect?.timeout;\n" ], "file_path": "packages/playwright-test/src/matchers/toBeTruthy.ts", "type": "replace", "edit_start_line_idx": 39 }
/** * Copyright Microsoft Corporation. All rights reserved. * * 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 colors from 'colors/safe'; import { ExpectedTextValue } from 'playwright-core/src/protocol/channels'; import { isRegExp, isString } from 'playwright-core/src/utils/utils'; import { currentTestInfo } from '../globals'; import type { Expect } from '../types'; import { expectType } from '../util'; import { printReceivedStringContainExpectedResult, printReceivedStringContainExpectedSubstring } from '../expect'; export async function toMatchText( this: ReturnType<Expect['getState']>, matcherName: string, receiver: any, receiverType: string, query: (isNot: boolean, timeout: number) => Promise<{ matches: boolean, received?: string, log?: string[] }>, expected: string | RegExp, options: { timeout?: number, matchSubstring?: boolean } = {}, ) { const testInfo = currentTestInfo(); if (!testInfo) throw new Error(`${matcherName} must be called during the test`); expectType(receiver, receiverType, matcherName); const matcherOptions = { isNot: this.isNot, promise: this.promise, }; if ( !(typeof expected === 'string') && !(expected && typeof expected.test === 'function') ) { throw new Error( this.utils.matcherErrorMessage( this.utils.matcherHint(matcherName, undefined, undefined, matcherOptions), `${this.utils.EXPECTED_COLOR( 'expected', )} value must be a string or regular expression`, this.utils.printWithType('Expected', expected, this.utils.printExpected), ), ); } let defaultExpectTimeout = testInfo.project.expect?.timeout; if (typeof defaultExpectTimeout === 'undefined') defaultExpectTimeout = 5000; const timeout = options.timeout === 0 ? 0 : options.timeout || defaultExpectTimeout; const { matches: pass, received, log } = await query(this.isNot, timeout); const stringSubstring = options.matchSubstring ? 'substring' : 'string'; const receivedString = received || ''; const message = pass ? () => typeof expected === 'string' ? this.utils.matcherHint(matcherName, undefined, undefined, matcherOptions) + '\n\n' + `Expected ${stringSubstring}: not ${this.utils.printExpected(expected)}\n` + `Received string: ${printReceivedStringContainExpectedSubstring( receivedString, receivedString.indexOf(expected), expected.length, )}` + callLogText(log) : this.utils.matcherHint(matcherName, undefined, undefined, matcherOptions) + '\n\n' + `Expected pattern: not ${this.utils.printExpected(expected)}\n` + `Received string: ${printReceivedStringContainExpectedResult( receivedString, typeof expected.exec === 'function' ? expected.exec(receivedString) : null, )}` + callLogText(log) : () => { const labelExpected = `Expected ${typeof expected === 'string' ? stringSubstring : 'pattern' }`; const labelReceived = 'Received string'; return ( this.utils.matcherHint(matcherName, undefined, undefined, matcherOptions) + '\n\n' + this.utils.printDiffOrStringify( expected, receivedString, labelExpected, labelReceived, this.expand !== false, )) + callLogText(log); }; return { message, pass }; } export function toExpectedTextValues(items: (string | RegExp)[], options: { matchSubstring?: boolean, normalizeWhiteSpace?: boolean } = {}): ExpectedTextValue[] { return items.map(i => ({ string: isString(i) ? i : undefined, regexSource: isRegExp(i) ? i.source : undefined, regexFlags: isRegExp(i) ? i.flags : undefined, matchSubstring: options.matchSubstring, normalizeWhiteSpace: options.normalizeWhiteSpace, })); } export function callLogText(log: string[] | undefined): string { if (!log) return ''; return ` Call log: - ${colors.dim((log || []).join('\n - '))} `; }
packages/playwright-test/src/matchers/toMatchText.ts
1
https://github.com/microsoft/playwright/commit/9d03a85c3039fcc968aa7d29777bbca85789fd4a
[ 0.998112678527832, 0.4541851580142975, 0.00017195002874359488, 0.005085399374365807, 0.4892745614051819 ]
{ "id": 1, "code_window": [ " const matcherOptions = {\n", " isNot: this.isNot,\n", " promise: this.promise,\n", " };\n", "\n", " let defaultExpectTimeout = testInfo.project.expect?.timeout;\n", " if (typeof defaultExpectTimeout === 'undefined')\n", " defaultExpectTimeout = 5000;\n", " const timeout = options.timeout === 0 ? 0 : options.timeout || defaultExpectTimeout;\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " const testInfo = currentTestInfo();\n", " let defaultExpectTimeout = testInfo?.project.expect?.timeout;\n" ], "file_path": "packages/playwright-test/src/matchers/toBeTruthy.ts", "type": "replace", "edit_start_line_idx": 39 }
/** * 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 path from 'path'; import fs from 'fs'; import { test, expect } from './inspectorTest'; const emptyHTML = new URL('file://' + path.join(__dirname, '..', 'assets', 'empty.html')).toString(); const launchOptions = (channel: string) => { return channel ? `Headless = false,\n Channel = "${channel}",` : `Headless = false,`; }; function capitalize(browserName: string): string { return browserName[0].toUpperCase() + browserName.slice(1); } test('should print the correct imports and context options', async ({ browserName, channel, runCLI }) => { const cli = runCLI(['--target=csharp', emptyHTML]); const expectedResult = `using Microsoft.Playwright; using System; using System.Threading.Tasks; class Program { public static async Task Main() { using var playwright = await Playwright.CreateAsync(); await using var browser = await playwright.${capitalize(browserName)}.LaunchAsync(new BrowserTypeLaunchOptions { ${launchOptions(channel)} }); var context = await browser.NewContextAsync();`; await cli.waitFor(expectedResult).catch(e => e); expect(cli.text()).toContain(expectedResult); }); test('should print the correct context options for custom settings', async ({ browserName, channel, runCLI }) => { const cli = runCLI([ '--color-scheme=dark', '--geolocation=37.819722,-122.478611', '--lang=es', '--proxy-server=http://myproxy:3128', '--timezone=Europe/Rome', '--user-agent=hardkodemium', '--viewport-size=1280,720', '--target=csharp', emptyHTML]); const expectedResult = ` using var playwright = await Playwright.CreateAsync(); await using var browser = await playwright.${capitalize(browserName)}.LaunchAsync(new BrowserTypeLaunchOptions { ${launchOptions(channel)} Proxy = new ProxySettings { Server = "http://myproxy:3128", }, }); var context = await browser.NewContextAsync(new BrowserNewContextOptions { ViewportSize = new ViewportSize { Width = 1280, Height = 720, }, Geolocation = new Geolocation { Latitude = 37.819722m, Longitude = -122.478611m, }, Permissions = new[] { ContextPermission.Geolocation }, UserAgent = "hardkodemium", Locale = "es", ColorScheme = ColorScheme.Dark, TimezoneId = "Europe/Rome", });`; await cli.waitFor(expectedResult); expect(cli.text()).toContain(expectedResult); }); test('should print the correct context options when using a device', async ({ browserName, channel, runCLI }) => { test.skip(browserName !== 'chromium'); const cli = runCLI(['--device=Pixel 2', '--target=csharp', emptyHTML]); const expectedResult = ` using var playwright = await Playwright.CreateAsync(); await using var browser = await playwright.${capitalize(browserName)}.LaunchAsync(new BrowserTypeLaunchOptions { ${launchOptions(channel)} }); var context = await browser.NewContextAsync(playwright.Devices["Pixel 2"]);`; await cli.waitFor(expectedResult); expect(cli.text()).toContain(expectedResult); }); test('should print the correct context options when using a device and additional options', async ({ browserName, channel, runCLI }) => { test.skip(browserName !== 'webkit'); const cli = runCLI([ '--device=iPhone 11', '--color-scheme=dark', '--geolocation=37.819722,-122.478611', '--lang=es', '--proxy-server=http://myproxy:3128', '--timezone=Europe/Rome', '--user-agent=hardkodemium', '--viewport-size=1280,720', '--target=csharp', emptyHTML]); const expectedResult = ` using var playwright = await Playwright.CreateAsync(); await using var browser = await playwright.${capitalize(browserName)}.LaunchAsync(new BrowserTypeLaunchOptions { ${launchOptions(channel)} Proxy = new ProxySettings { Server = "http://myproxy:3128", }, }); var context = await browser.NewContextAsync(new BrowserNewContextOptions(playwright.Devices["iPhone 11"]) { UserAgent = "hardkodemium", ViewportSize = new ViewportSize { Width = 1280, Height = 720, }, Geolocation = new Geolocation { Latitude = 37.819722m, Longitude = -122.478611m, }, Permissions = new[] { ContextPermission.Geolocation }, Locale = "es", ColorScheme = ColorScheme.Dark, TimezoneId = "Europe/Rome", });`; await cli.waitFor(expectedResult); expect(cli.text()).toContain(expectedResult); }); test('should print load/save storageState', async ({ browserName, channel, runCLI }, testInfo) => { const loadFileName = testInfo.outputPath('load.json'); const saveFileName = testInfo.outputPath('save.json'); await fs.promises.writeFile(loadFileName, JSON.stringify({ cookies: [], origins: [] }), 'utf8'); const cli = runCLI([`--load-storage=${loadFileName}`, `--save-storage=${saveFileName}`, '--target=csharp', emptyHTML]); const expectedResult1 = ` using var playwright = await Playwright.CreateAsync(); await using var browser = await playwright.${capitalize(browserName)}.LaunchAsync(new BrowserTypeLaunchOptions { ${launchOptions(channel)} }); var context = await browser.NewContextAsync(new BrowserNewContextOptions { StorageStatePath = "${loadFileName.replace(/\\/g, '\\\\')}", });`; await cli.waitFor(expectedResult1); const expectedResult2 = ` await context.StorageStateAsync(new BrowserContextStorageStateOptions { Path = "${saveFileName.replace(/\\/g, '\\\\')}" }); `; await cli.waitFor(expectedResult2); });
tests/inspector/cli-codegen-csharp.spec.ts
0
https://github.com/microsoft/playwright/commit/9d03a85c3039fcc968aa7d29777bbca85789fd4a
[ 0.00017731060506775975, 0.00017154526722151786, 0.0001674637314863503, 0.00017087868764065206, 0.000002517708480809233 ]
{ "id": 1, "code_window": [ " const matcherOptions = {\n", " isNot: this.isNot,\n", " promise: this.promise,\n", " };\n", "\n", " let defaultExpectTimeout = testInfo.project.expect?.timeout;\n", " if (typeof defaultExpectTimeout === 'undefined')\n", " defaultExpectTimeout = 5000;\n", " const timeout = options.timeout === 0 ? 0 : options.timeout || defaultExpectTimeout;\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " const testInfo = currentTestInfo();\n", " let defaultExpectTimeout = testInfo?.project.expect?.timeout;\n" ], "file_path": "packages/playwright-test/src/matchers/toBeTruthy.ts", "type": "replace", "edit_start_line_idx": 39 }
# class: APIRequest * langs: js Exposes API that can be used for the Web API testing. ## async method: APIRequest.newContext * langs: js - returns: <[APIRequestContext]> Creates new instances of [APIRequestContext]. ### option: APIRequest.newContext.useragent = %%-context-option-useragent-%% ### option: APIRequest.newContext.extraHTTPHeaders = %%-context-option-extrahttpheaders-%% ### option: APIRequest.newContext.httpCredentials = %%-context-option-httpcredentials-%% ### option: APIRequest.newContext.proxy = %%-browser-option-proxy-%% ### option: APIRequest.newContext.ignoreHTTPSErrors = %%-context-option-ignorehttpserrors-%% ### option: APIRequest.newContext.timeout - `timeout` <[float]> Maximum time in milliseconds to wait for the response. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. ### option: APIRequest.newContext.baseURL - `baseURL` <[string]> Methods like [`method: APIRequestContext.get`] take the base URL into consideration by using the [`URL()`](https://developer.mozilla.org/en-US/docs/Web/API/URL/URL) constructor for building the corresponding URL. Examples: * baseURL: `http://localhost:3000` and sending request to `/bar.html` results in `http://localhost:3000/bar.html` * baseURL: `http://localhost:3000/foo/` and sending request to `./bar.html` results in `http://localhost:3000/foo/bar.html` ### option: APIRequest.newContext.storageState - `storageState` <[path]|[Object]> - `cookies` <[Array]<[Object]>> - `name` <[string]> - `value` <[string]> - `domain` <[string]> - `path` <[string]> - `expires` <[float]> Unix time in seconds. - `httpOnly` <[boolean]> - `secure` <[boolean]> - `sameSite` <[SameSiteAttribute]<"Strict"|"Lax"|"None">> - `origins` <[Array]<[Object]>> - `origin` <[string]> - `localStorage` <[Array]<[Object]>> - `name` <[string]> - `value` <[string]> Populates context with given storage state. This option can be used to initialize context with logged-in information obtained via [`method: BrowserContext.storageState`] or [`method: APIRequestContext.storageState`]. Either a path to the file with saved storage, or the value returned by one of [`method: BrowserContext.storageState`] or [`method: APIRequestContext.storageState`] methods.
docs/src/api/class-apirequest.md
0
https://github.com/microsoft/playwright/commit/9d03a85c3039fcc968aa7d29777bbca85789fd4a
[ 0.00017010158626362681, 0.00016454682918265462, 0.00015894463285803795, 0.00016476010205224156, 0.0000032827754239406204 ]
{ "id": 1, "code_window": [ " const matcherOptions = {\n", " isNot: this.isNot,\n", " promise: this.promise,\n", " };\n", "\n", " let defaultExpectTimeout = testInfo.project.expect?.timeout;\n", " if (typeof defaultExpectTimeout === 'undefined')\n", " defaultExpectTimeout = 5000;\n", " const timeout = options.timeout === 0 ? 0 : options.timeout || defaultExpectTimeout;\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " const testInfo = currentTestInfo();\n", " let defaultExpectTimeout = testInfo?.project.expect?.timeout;\n" ], "file_path": "packages/playwright-test/src/matchers/toBeTruthy.ts", "type": "replace", "edit_start_line_idx": 39 }
/** * 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 { ElementHandle } from './elementHandle'; import { Page } from './page'; import { FilePayload } from './types'; import * as channels from '../protocol/channels'; import * as api from '../../types/types'; export class FileChooser implements api.FileChooser { private _page: Page; private _elementHandle: ElementHandle<Node>; private _isMultiple: boolean; constructor(page: Page, elementHandle: ElementHandle, isMultiple: boolean) { this._page = page; this._elementHandle = elementHandle; this._isMultiple = isMultiple; } element(): ElementHandle { return this._elementHandle; } isMultiple(): boolean { return this._isMultiple; } page(): Page { return this._page; } async setFiles(files: string | FilePayload | string[] | FilePayload[], options?: channels.ElementHandleSetInputFilesOptions) { return this._page._wrapApiCall(async () => { return this._elementHandle.setInputFiles(files, options); }); } }
packages/playwright-core/src/client/fileChooser.ts
0
https://github.com/microsoft/playwright/commit/9d03a85c3039fcc968aa7d29777bbca85789fd4a
[ 0.00021072266099508852, 0.0001811281981645152, 0.0001712242519715801, 0.00017650271183811128, 0.000013460662557918113 ]
{ "id": 2, "code_window": [ " receiverType: string,\n", " query: (isNot: boolean, timeout: number) => Promise<{ matches: boolean, received?: any, log?: string[] }>,\n", " expected: T,\n", " options: { timeout?: number, contains?: boolean } = {},\n", ") {\n", " const testInfo = currentTestInfo();\n", " if (!testInfo)\n", " throw new Error(`${matcherName} must be called during the test`);\n", " expectType(receiver, receiverType, matcherName);\n", "\n", " const matcherOptions = {\n", " comment: options.contains ? '' : 'deep equality',\n", " isNot: this.isNot,\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "packages/playwright-test/src/matchers/toEqual.ts", "type": "replace", "edit_start_line_idx": 37 }
/** * Copyright Microsoft Corporation. All rights reserved. * * 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 { currentTestInfo } from '../globals'; import type { Expect } from '../types'; import { expectType } from '../util'; import { callLogText } from './toMatchText'; // Omit colon and one or more spaces, so can call getLabelPrinter. const EXPECTED_LABEL = 'Expected'; const RECEIVED_LABEL = 'Received'; // The optional property of matcher context is true if undefined. const isExpand = (expand?: boolean): boolean => expand !== false; export async function toEqual<T>( this: ReturnType<Expect['getState']>, matcherName: string, receiver: any, receiverType: string, query: (isNot: boolean, timeout: number) => Promise<{ matches: boolean, received?: any, log?: string[] }>, expected: T, options: { timeout?: number, contains?: boolean } = {}, ) { const testInfo = currentTestInfo(); if (!testInfo) throw new Error(`${matcherName} must be called during the test`); expectType(receiver, receiverType, matcherName); const matcherOptions = { comment: options.contains ? '' : 'deep equality', isNot: this.isNot, promise: this.promise, }; let defaultExpectTimeout = testInfo.project.expect?.timeout; if (typeof defaultExpectTimeout === 'undefined') defaultExpectTimeout = 5000; const timeout = options.timeout === 0 ? 0 : options.timeout || defaultExpectTimeout; const { matches: pass, received, log } = await query(this.isNot, timeout); const message = pass ? () => this.utils.matcherHint(matcherName, undefined, undefined, matcherOptions) + '\n\n' + `Expected: not ${this.utils.printExpected(expected)}\n` + (this.utils.stringify(expected) !== this.utils.stringify(received) ? `Received: ${this.utils.printReceived(received)}` : '') + callLogText(log) : () => this.utils.matcherHint(matcherName, undefined, undefined, matcherOptions) + '\n\n' + this.utils.printDiffOrStringify( expected, received, EXPECTED_LABEL, RECEIVED_LABEL, isExpand(this.expand), ) + callLogText(log); // Passing the actual and expected objects so that a custom reporter // could access them, for example in order to display a custom visual diff, // or create a different error message return { actual: received, expected, message, name: matcherName, pass }; }
packages/playwright-test/src/matchers/toEqual.ts
1
https://github.com/microsoft/playwright/commit/9d03a85c3039fcc968aa7d29777bbca85789fd4a
[ 0.9984356760978699, 0.4985277056694031, 0.00017426164413336664, 0.4970737099647522, 0.49774840474128723 ]
{ "id": 2, "code_window": [ " receiverType: string,\n", " query: (isNot: boolean, timeout: number) => Promise<{ matches: boolean, received?: any, log?: string[] }>,\n", " expected: T,\n", " options: { timeout?: number, contains?: boolean } = {},\n", ") {\n", " const testInfo = currentTestInfo();\n", " if (!testInfo)\n", " throw new Error(`${matcherName} must be called during the test`);\n", " expectType(receiver, receiverType, matcherName);\n", "\n", " const matcherOptions = {\n", " comment: options.contains ? '' : 'deep equality',\n", " isNot: this.isNot,\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "packages/playwright-test/src/matchers/toEqual.ts", "type": "replace", "edit_start_line_idx": 37 }
/** * 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 React from 'react'; import './callTab.css'; import type { ActionTraceEvent } from '../../../server/trace/common/traceEvents'; import { CallMetadata } from '../../../protocol/callMetadata'; import { parseSerializedValue } from '../../../protocol/serializers'; import { msToString } from '../../uiUtils'; export const CallTab: React.FunctionComponent<{ action: ActionTraceEvent | undefined, }> = ({ action }) => { if (!action) return null; const logs = action.metadata.log; const error = action.metadata.error?.error?.message; const params = { ...action.metadata.params }; // Strip down the waitForEventInfo data, we never need it. delete params.info; const paramKeys = Object.keys(params); return <div className='call-tab'> <div className='call-error' key='error' hidden={!error}> <div className='codicon codicon-issues'/> {error} </div> <div className='call-line'>{action.metadata.apiName} <span className='call-duration'>— {msToString(action.metadata.endTime - action.metadata.startTime)}</span></div> { !!paramKeys.length && <div className='call-section'>Parameters</div> } { !!paramKeys.length && paramKeys.map((name, index) => renderLine(action.metadata, name, params[name], 'param-' + index)) } { !!action.metadata.result && <div className='call-section'>Return value</div> } { !!action.metadata.result && Object.keys(action.metadata.result).map((name, index) => renderLine(action.metadata, name, action.metadata.result[name], 'result-' + index) ) } <div className='call-section'>Log</div> { logs.map((logLine, index) => { return <div key={index} className='call-line'> {logLine} </div>; }) } </div>; }; function renderLine(metadata: CallMetadata, name: string, value: any, key: string) { const { title, type } = toString(metadata, name, value); let text = trimRight(title.replace(/\n/g, '↵'), 80); if (type === 'string') text = `"${text}"`; return <div key={key} className='call-line'>{name}: <span className={type} title={title}>{text}</span></div>; } function toString(metadata: CallMetadata, name: string, value: any): { title: string, type: string } { if (metadata.method.includes('eval')) { if (name === 'arg') value = parseSerializedValue(value.value, new Array(10).fill({ handle: '<handle>' })); if (name === 'value') value = parseSerializedValue(value, new Array(10).fill({ handle: '<handle>' })); } const type = typeof value; if (type !== 'object') return { title: String(value), type }; if (value.guid) return { title: '<handle>', type: 'handle' }; return { title: JSON.stringify(value), type: 'object' }; } function trimRight(text: string, max: number): string { if (text.length > max) return text.substr(0, max) + '\u2026'; return text; }
packages/playwright-core/src/web/traceViewer/ui/callTab.tsx
0
https://github.com/microsoft/playwright/commit/9d03a85c3039fcc968aa7d29777bbca85789fd4a
[ 0.0001773770636646077, 0.00017096065857913345, 0.00016400599270127714, 0.00017124252917710692, 0.000004768103281094227 ]
{ "id": 2, "code_window": [ " receiverType: string,\n", " query: (isNot: boolean, timeout: number) => Promise<{ matches: boolean, received?: any, log?: string[] }>,\n", " expected: T,\n", " options: { timeout?: number, contains?: boolean } = {},\n", ") {\n", " const testInfo = currentTestInfo();\n", " if (!testInfo)\n", " throw new Error(`${matcherName} must be called during the test`);\n", " expectType(receiver, receiverType, matcherName);\n", "\n", " const matcherOptions = {\n", " comment: options.contains ? '' : 'deep equality',\n", " isNot: this.isNot,\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "packages/playwright-test/src/matchers/toEqual.ts", "type": "replace", "edit_start_line_idx": 37 }
/** * 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 work', async ({ page, server }) => { await page.goto(server.EMPTY_PAGE); const [response] = await Promise.all([ page.waitForResponse(server.PREFIX + '/digits/2.png'), page.evaluate(() => { fetch('/digits/1.png'); fetch('/digits/2.png'); fetch('/digits/3.png'); }) ]); expect(response.url()).toBe(server.PREFIX + '/digits/2.png'); }); it('should respect timeout', async ({ page, playwright }) => { let error = null; await page.waitForEvent('response', { predicate: () => false, timeout: 1 }).catch(e => error = e); expect(error).toBeInstanceOf(playwright.errors.TimeoutError); }); it('should respect default timeout', async ({ page, playwright }) => { let error = null; page.setDefaultTimeout(1); await page.waitForEvent('response', () => false).catch(e => error = e); expect(error).toBeInstanceOf(playwright.errors.TimeoutError); }); it('should log the url', async ({ page }) => { const error1 = await page.waitForResponse('foo.css', { timeout: 100 }).catch(e => e); expect(error1.message).toContain('waiting for response "foo.css"'); const error2 = await page.waitForResponse(/foo.css/i, { timeout: 100 }).catch(e => e); expect(error2.message).toContain('waiting for response /foo.css/i'); }); it('should work with predicate', async ({ page, server }) => { await page.goto(server.EMPTY_PAGE); const [response] = await Promise.all([ page.waitForEvent('response', response => response.url() === server.PREFIX + '/digits/2.png'), page.evaluate(() => { fetch('/digits/1.png'); fetch('/digits/2.png'); fetch('/digits/3.png'); }) ]); expect(response.url()).toBe(server.PREFIX + '/digits/2.png'); }); it('should work with async predicate', async ({ page, server }) => { await page.goto(server.EMPTY_PAGE); const [response1, response2] = await Promise.all([ page.waitForEvent('response', async response => { const text = await response.text(); return text.includes('contents of the file'); }), page.waitForResponse(async response => { const text = await response.text(); return text.includes('bar'); }), page.evaluate(() => { fetch('/simple.json').then(r => r.json()); fetch('/file-to-upload.txt').then(r => r.text()); }) ]); expect(response1.url()).toBe(server.PREFIX + '/file-to-upload.txt'); expect(response2.url()).toBe(server.PREFIX + '/simple.json'); }); it('sync predicate should be only called once', async ({ page, server }) => { await page.goto(server.EMPTY_PAGE); let counter = 0; const [response] = await Promise.all([ page.waitForEvent('response', response => { ++counter; return response.url() === server.PREFIX + '/digits/1.png'; }), page.evaluate(async () => { await fetch('/digits/1.png'); await fetch('/digits/2.png'); await fetch('/digits/3.png'); }) ]); expect(response.url()).toBe(server.PREFIX + '/digits/1.png'); expect(counter).toBe(1); }); it('should work with no timeout', async ({ page, server }) => { await page.goto(server.EMPTY_PAGE); const [response] = await Promise.all([ page.waitForResponse(server.PREFIX + '/digits/2.png', { timeout: 0 }), page.evaluate(() => setTimeout(() => { fetch('/digits/1.png'); fetch('/digits/2.png'); fetch('/digits/3.png'); }, 50)) ]); expect(response.url()).toBe(server.PREFIX + '/digits/2.png'); });
tests/page/page-wait-for-response.spec.ts
0
https://github.com/microsoft/playwright/commit/9d03a85c3039fcc968aa7d29777bbca85789fd4a
[ 0.00017860493971966207, 0.00017447699792683125, 0.00017187953926622868, 0.0001744315813994035, 0.0000018971564941239194 ]
{ "id": 2, "code_window": [ " receiverType: string,\n", " query: (isNot: boolean, timeout: number) => Promise<{ matches: boolean, received?: any, log?: string[] }>,\n", " expected: T,\n", " options: { timeout?: number, contains?: boolean } = {},\n", ") {\n", " const testInfo = currentTestInfo();\n", " if (!testInfo)\n", " throw new Error(`${matcherName} must be called during the test`);\n", " expectType(receiver, receiverType, matcherName);\n", "\n", " const matcherOptions = {\n", " comment: options.contains ? '' : 'deep equality',\n", " isNot: this.isNot,\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "packages/playwright-test/src/matchers/toEqual.ts", "type": "replace", "edit_start_line_idx": 37 }
<!DOCTYPE html> <html> <head> <title>Blob Download Example</title> </head> <body> <script> const download = (data, filename) => { const a = document.createElement("a"); a.style = "display: none"; document.body.appendChild(a); a.style = "display: none"; const blob = new Blob([data], { type: "octet/stream" }); const url = window.URL.createObjectURL(blob); a.href = url; a.download = filename; a.click(); window.URL.revokeObjectURL(url); document.body.removeChild(a); }; const downloadIt = () => { download("Hello world", "example.txt"); } </script> <a onclick="javascipt:downloadIt();">Download</a> </body> </html>
tests/assets/download-blob.html
0
https://github.com/microsoft/playwright/commit/9d03a85c3039fcc968aa7d29777bbca85789fd4a
[ 0.0001750259834807366, 0.00017355859745293856, 0.0001716562983347103, 0.0001739934814395383, 0.0000014096202676228131 ]
{ "id": 3, "code_window": [ " comment: options.contains ? '' : 'deep equality',\n", " isNot: this.isNot,\n", " promise: this.promise,\n", " };\n", "\n", " let defaultExpectTimeout = testInfo.project.expect?.timeout;\n", " if (typeof defaultExpectTimeout === 'undefined')\n", " defaultExpectTimeout = 5000;\n", " const timeout = options.timeout === 0 ? 0 : options.timeout || defaultExpectTimeout;\n", "\n", " const { matches: pass, received, log } = await query(this.isNot, timeout);\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " const testInfo = currentTestInfo();\n", " let defaultExpectTimeout = testInfo?.project.expect?.timeout;\n" ], "file_path": "packages/playwright-test/src/matchers/toEqual.ts", "type": "replace", "edit_start_line_idx": 48 }
/** * Copyright Microsoft Corporation. All rights reserved. * * 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 { currentTestInfo } from '../globals'; import type { Expect } from '../types'; import { expectType } from '../util'; import { callLogText } from './toMatchText'; export async function toBeTruthy( this: ReturnType<Expect['getState']>, matcherName: string, receiver: any, receiverType: string, query: (isNot: boolean, timeout: number) => Promise<{ matches: boolean, log?: string[] }>, options: { timeout?: number } = {}, ) { const testInfo = currentTestInfo(); if (!testInfo) throw new Error(`${matcherName} must be called during the test`); expectType(receiver, receiverType, matcherName); const matcherOptions = { isNot: this.isNot, promise: this.promise, }; let defaultExpectTimeout = testInfo.project.expect?.timeout; if (typeof defaultExpectTimeout === 'undefined') defaultExpectTimeout = 5000; const timeout = options.timeout === 0 ? 0 : options.timeout || defaultExpectTimeout; const { matches, log } = await query(this.isNot, timeout); const message = () => { return this.utils.matcherHint(matcherName, undefined, '', matcherOptions) + callLogText(log); }; return { message, pass: matches }; }
packages/playwright-test/src/matchers/toBeTruthy.ts
1
https://github.com/microsoft/playwright/commit/9d03a85c3039fcc968aa7d29777bbca85789fd4a
[ 0.9983034133911133, 0.3302895724773407, 0.00017508273595012724, 0.0018808094318956137, 0.46567854285240173 ]
{ "id": 3, "code_window": [ " comment: options.contains ? '' : 'deep equality',\n", " isNot: this.isNot,\n", " promise: this.promise,\n", " };\n", "\n", " let defaultExpectTimeout = testInfo.project.expect?.timeout;\n", " if (typeof defaultExpectTimeout === 'undefined')\n", " defaultExpectTimeout = 5000;\n", " const timeout = options.timeout === 0 ? 0 : options.timeout || defaultExpectTimeout;\n", "\n", " const { matches: pass, received, log } = await query(this.isNot, timeout);\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " const testInfo = currentTestInfo();\n", " let defaultExpectTimeout = testInfo?.project.expect?.timeout;\n" ], "file_path": "packages/playwright-test/src/matchers/toEqual.ts", "type": "replace", "edit_start_line_idx": 48 }
/** * 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. */ export * from 'playwright-core';
packages/playwright-chromium/index.d.ts
0
https://github.com/microsoft/playwright/commit/9d03a85c3039fcc968aa7d29777bbca85789fd4a
[ 0.00017583508451934904, 0.00017541460692882538, 0.0001749941147863865, 0.00017541460692882538, 4.2048486648127437e-7 ]
{ "id": 3, "code_window": [ " comment: options.contains ? '' : 'deep equality',\n", " isNot: this.isNot,\n", " promise: this.promise,\n", " };\n", "\n", " let defaultExpectTimeout = testInfo.project.expect?.timeout;\n", " if (typeof defaultExpectTimeout === 'undefined')\n", " defaultExpectTimeout = 5000;\n", " const timeout = options.timeout === 0 ? 0 : options.timeout || defaultExpectTimeout;\n", "\n", " const { matches: pass, received, log } = await query(this.isNot, timeout);\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " const testInfo = currentTestInfo();\n", " let defaultExpectTimeout = testInfo?.project.expect?.timeout;\n" ], "file_path": "packages/playwright-test/src/matchers/toEqual.ts", "type": "replace", "edit_start_line_idx": 48 }
<script> console.log(1); //# sourceURL=nicename.js </script>
tests/assets/jscoverage/sourceurl.html
0
https://github.com/microsoft/playwright/commit/9d03a85c3039fcc968aa7d29777bbca85789fd4a
[ 0.00016835246060509235, 0.00016835246060509235, 0.00016835246060509235, 0.00016835246060509235, 0 ]
{ "id": 3, "code_window": [ " comment: options.contains ? '' : 'deep equality',\n", " isNot: this.isNot,\n", " promise: this.promise,\n", " };\n", "\n", " let defaultExpectTimeout = testInfo.project.expect?.timeout;\n", " if (typeof defaultExpectTimeout === 'undefined')\n", " defaultExpectTimeout = 5000;\n", " const timeout = options.timeout === 0 ? 0 : options.timeout || defaultExpectTimeout;\n", "\n", " const { matches: pass, received, log } = await query(this.isNot, timeout);\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " const testInfo = currentTestInfo();\n", " let defaultExpectTimeout = testInfo?.project.expect?.timeout;\n" ], "file_path": "packages/playwright-test/src/matchers/toEqual.ts", "type": "replace", "edit_start_line_idx": 48 }
#!/bin/bash set -e set +x set -o pipefail if [[ ($1 == '--help') || ($1 == '-h') ]]; then echo "usage: $(basename "$0") [firefox-linux|firefox-win32|firefox-win64|webkit-gtk|webkit-wpe|webkit-gtk-wpe|webkit-win64|webkit-mac-10.15] [-f|--force]" echo echo "Prepares checkout under browser folder, applies patches, builds, archives, and uploads if build is missing." echo "Script will bail out early if the build for the browser version is already present." echo echo "Pass -f to upload anyway." echo echo "NOTE: This script is safe to run in a cronjob - it aquires a lock so that it does not run twice." exit 0 fi if [[ $# == 0 ]]; then echo "missing build flavor!" echo "try './$(basename "$0") --help' for more information" exit 1 fi CURRENT_ARCH="$(uname -m)" CURRENT_HOST_OS="$(uname)" CURRENT_HOST_OS_VERSION="" if [[ "$CURRENT_HOST_OS" == "Darwin" ]]; then CURRENT_HOST_OS_VERSION=$(sw_vers -productVersion | grep -o '^\d\+.\d\+') elif [[ "$CURRENT_HOST_OS" == "Linux" ]]; then CURRENT_HOST_OS="$(bash -c 'source /etc/os-release && echo $NAME')" CURRENT_HOST_OS_VERSION="$(bash -c 'source /etc/os-release && echo $VERSION_ID')" fi BROWSER_NAME="" BROWSER_DISPLAY_NAME="" EXTRA_BUILD_ARGS="" EXTRA_ARCHIVE_ARGS="" BUILD_FLAVOR="$1" BUILD_BLOB_NAME="" EXPECTED_HOST_OS="" EXPECTED_HOST_OS_VERSION="" EXPECTED_ARCH="x86_64" BUILDS_LIST="EXPECTED_BUILDS" # =========================== # WINLDD COMPILATION # =========================== if [[ "$BUILD_FLAVOR" == "winldd-win64" ]]; then BROWSER_NAME="winldd" EXPECTED_HOST_OS="MINGW" BUILD_BLOB_NAME="winldd-win64.zip" # =========================== # FFMPEG COMPILATION # =========================== elif [[ "$BUILD_FLAVOR" == "ffmpeg-mac" ]]; then BROWSER_NAME="ffmpeg" EXTRA_BUILD_ARGS="--mac" EXPECTED_HOST_OS="Darwin" EXPECTED_HOST_OS_VERSION="11.6" BUILD_BLOB_NAME="ffmpeg-mac.zip" elif [[ "$BUILD_FLAVOR" == "ffmpeg-linux" ]]; then BROWSER_NAME="ffmpeg" EXTRA_BUILD_ARGS="--linux" EXPECTED_HOST_OS="Ubuntu" EXPECTED_HOST_OS_VERSION="20.04" BUILD_BLOB_NAME="ffmpeg-linux.zip" elif [[ "$BUILD_FLAVOR" == "ffmpeg-cross-compile-win32" ]]; then BROWSER_NAME="ffmpeg" EXTRA_BUILD_ARGS="--cross-compile-win32" EXPECTED_HOST_OS="Ubuntu" EXPECTED_HOST_OS_VERSION="20.04" BUILD_BLOB_NAME="ffmpeg-win32.zip" elif [[ "$BUILD_FLAVOR" == "ffmpeg-cross-compile-win64" ]]; then BROWSER_NAME="ffmpeg" EXTRA_BUILD_ARGS="--cross-compile-win64" EXPECTED_HOST_OS="Ubuntu" EXPECTED_HOST_OS_VERSION="20.04" BUILD_BLOB_NAME="ffmpeg-win64.zip" # =========================== # CHROMIUM COMPILATION # =========================== elif [[ "$BUILD_FLAVOR" == "chromium-win32" ]]; then BROWSER_NAME="chromium" EXTRA_BUILD_ARGS="--compile-win32" EXTRA_ARCHIVE_ARGS="--compile-win32" EXPECTED_HOST_OS="MINGW" BUILD_BLOB_NAME="chromium-win32.zip" elif [[ "$BUILD_FLAVOR" == "chromium-win64" ]]; then BROWSER_NAME="chromium" EXTRA_BUILD_ARGS="--compile-win64" EXTRA_ARCHIVE_ARGS="--compile-win64" EXPECTED_HOST_OS="MINGW" BUILD_BLOB_NAME="chromium-win64.zip" elif [[ "$BUILD_FLAVOR" == "chromium-mac" ]]; then BROWSER_NAME="chromium" EXTRA_BUILD_ARGS="--compile-mac" EXTRA_ARCHIVE_ARGS="--compile-mac" EXPECTED_HOST_OS="Darwin" EXPECTED_HOST_OS_VERSION="10.15" BUILD_BLOB_NAME="chromium-mac.zip" elif [[ "$BUILD_FLAVOR" == "chromium-mac-arm64" ]]; then BROWSER_NAME="chromium" EXTRA_BUILD_ARGS="--compile-mac-arm64" EXTRA_ARCHIVE_ARGS="--compile-mac-arm64" EXPECTED_HOST_OS="Darwin" EXPECTED_HOST_OS_VERSION="10.15" BUILD_BLOB_NAME="chromium-mac-arm64.zip" elif [[ "$BUILD_FLAVOR" == "chromium-linux" ]]; then BROWSER_NAME="chromium" EXTRA_BUILD_ARGS="--compile-linux" EXTRA_ARCHIVE_ARGS="--compile-linux" EXPECTED_HOST_OS="Ubuntu" EXPECTED_HOST_OS_VERSION="18.04" BUILD_BLOB_NAME="chromium-linux.zip" # =========================== # CHROMIUM-WITH-SYMBOLS COMPILATION # =========================== elif [[ "$BUILD_FLAVOR" == "chromium-with-symbols-win32" ]]; then BROWSER_NAME="chromium" BROWSER_DISPLAY_NAME="chromium-with-symbols" EXTRA_BUILD_ARGS="--compile-win32 --symbols" EXTRA_ARCHIVE_ARGS="--compile-win32" EXPECTED_HOST_OS="MINGW" BUILD_BLOB_NAME="chromium-with-symbols-win32.zip" BUILDS_LIST="EXPECTED_BUILDS_WITH_SYMBOLS" elif [[ "$BUILD_FLAVOR" == "chromium-with-symbols-win64" ]]; then BROWSER_NAME="chromium" BROWSER_DISPLAY_NAME="chromium-with-symbols" EXTRA_BUILD_ARGS="--compile-win64 --symbols" EXTRA_ARCHIVE_ARGS="--compile-win64" EXPECTED_HOST_OS="MINGW" BUILD_BLOB_NAME="chromium-with-symbols-win64.zip" BUILDS_LIST="EXPECTED_BUILDS_WITH_SYMBOLS" elif [[ "$BUILD_FLAVOR" == "chromium-with-symbols-mac" ]]; then BROWSER_NAME="chromium" BROWSER_DISPLAY_NAME="chromium-with-symbols" EXTRA_BUILD_ARGS="--compile-mac --symbols" EXTRA_ARCHIVE_ARGS="--compile-mac" EXPECTED_HOST_OS="Darwin" EXPECTED_HOST_OS_VERSION="10.15" BUILD_BLOB_NAME="chromium-with-symbols-mac.zip" BUILDS_LIST="EXPECTED_BUILDS_WITH_SYMBOLS" elif [[ "$BUILD_FLAVOR" == "chromium-with-symbols-mac-arm64" ]]; then BROWSER_NAME="chromium" BROWSER_DISPLAY_NAME="chromium-with-symbols" EXTRA_BUILD_ARGS="--compile-mac-arm64 --symbols" EXTRA_ARCHIVE_ARGS="--compile-mac-arm64" EXPECTED_HOST_OS="Darwin" EXPECTED_HOST_OS_VERSION="10.15" BUILD_BLOB_NAME="chromium-with-symbols-mac-arm64.zip" BUILDS_LIST="EXPECTED_BUILDS_WITH_SYMBOLS" elif [[ "$BUILD_FLAVOR" == "chromium-with-symbols-linux" ]]; then BROWSER_NAME="chromium" BROWSER_DISPLAY_NAME="chromium-with-symbols" EXTRA_BUILD_ARGS="--compile-linux --symbols" EXTRA_ARCHIVE_ARGS="--compile-linux" EXPECTED_HOST_OS="Ubuntu" EXPECTED_HOST_OS_VERSION="18.04" BUILD_BLOB_NAME="chromium-with-symbols-linux.zip" BUILDS_LIST="EXPECTED_BUILDS_WITH_SYMBOLS" # =========================== # CHROMIUM MIRRORING # =========================== elif [[ "$BUILD_FLAVOR" == "chromium-linux-mirror-to-cdn" ]]; then BROWSER_NAME="chromium" EXTRA_BUILD_ARGS="--mirror-linux" EXTRA_ARCHIVE_ARGS="--mirror-linux" EXPECTED_HOST_OS="Ubuntu" EXPECTED_HOST_OS_VERSION="18.04" BUILD_BLOB_NAME="chromium-linux.zip" elif [[ "$BUILD_FLAVOR" == "chromium-mac-mirror-to-cdn" ]]; then BROWSER_NAME="chromium" EXTRA_BUILD_ARGS="--mirror-mac" EXTRA_ARCHIVE_ARGS="--mirror-mac" EXPECTED_HOST_OS="Ubuntu" EXPECTED_HOST_OS_VERSION="18.04" BUILD_BLOB_NAME="chromium-mac.zip" elif [[ "$BUILD_FLAVOR" == "chromium-win32-mirror-to-cdn" ]]; then BROWSER_NAME="chromium" EXTRA_BUILD_ARGS="--mirror-win32" EXTRA_ARCHIVE_ARGS="--mirror-win32" EXPECTED_HOST_OS="Ubuntu" EXPECTED_HOST_OS_VERSION="18.04" BUILD_BLOB_NAME="chromium-win32.zip" elif [[ "$BUILD_FLAVOR" == "chromium-win64-mirror-to-cdn" ]]; then BROWSER_NAME="chromium" EXTRA_BUILD_ARGS="--mirror-win64" EXTRA_ARCHIVE_ARGS="--mirror-win64" EXPECTED_HOST_OS="Ubuntu" EXPECTED_HOST_OS_VERSION="18.04" BUILD_BLOB_NAME="chromium-win64.zip" # =========================== # FIREFOX COMPILATION # =========================== elif [[ "$BUILD_FLAVOR" == "firefox-ubuntu-18.04" ]]; then BROWSER_NAME="firefox" EXTRA_BUILD_ARGS="--full" EXPECTED_HOST_OS="Ubuntu" EXPECTED_HOST_OS_VERSION="18.04" BUILD_BLOB_NAME="firefox-ubuntu-18.04.zip" elif [[ "$BUILD_FLAVOR" == "firefox-ubuntu-20.04" ]]; then BROWSER_NAME="firefox" EXTRA_BUILD_ARGS="--full" EXPECTED_HOST_OS="Ubuntu" EXPECTED_HOST_OS_VERSION="20.04" BUILD_BLOB_NAME="firefox-ubuntu-20.04.zip" elif [[ "$BUILD_FLAVOR" == "firefox-mac-11" ]]; then BROWSER_NAME="firefox" EXTRA_BUILD_ARGS="--full" EXPECTED_HOST_OS="Darwin" EXPECTED_HOST_OS_VERSION="11.6" EXPECTED_ARCH="x86_64" BUILD_BLOB_NAME="firefox-mac-11.zip" elif [[ "$BUILD_FLAVOR" == "firefox-mac-11-arm64" ]]; then BROWSER_NAME="firefox" EXTRA_BUILD_ARGS="--full" EXPECTED_HOST_OS="Darwin" EXPECTED_HOST_OS_VERSION="11.6" EXPECTED_ARCH="arm64" BUILD_BLOB_NAME="firefox-mac-11-arm64.zip" elif [[ "$BUILD_FLAVOR" == "firefox-win32" ]]; then BROWSER_NAME="firefox" EXTRA_BUILD_ARGS="--full" EXPECTED_HOST_OS="MINGW" BUILD_BLOB_NAME="firefox-win32.zip" elif [[ "$BUILD_FLAVOR" == "firefox-win64" ]]; then BROWSER_NAME="firefox" EXTRA_BUILD_ARGS="--win64 --full" EXPECTED_HOST_OS="MINGW" BUILD_BLOB_NAME="firefox-win64.zip" # =============================== # FIREFOX-BETA COMPILATION # =============================== elif [[ "$BUILD_FLAVOR" == "firefox-beta-ubuntu-18.04" ]]; then BROWSER_NAME="firefox-beta" EXTRA_BUILD_ARGS="--full" EXPECTED_HOST_OS="Ubuntu" EXPECTED_HOST_OS_VERSION="18.04" BUILD_BLOB_NAME="firefox-beta-ubuntu-18.04.zip" elif [[ "$BUILD_FLAVOR" == "firefox-beta-ubuntu-20.04" ]]; then BROWSER_NAME="firefox-beta" EXTRA_BUILD_ARGS="--full" EXPECTED_HOST_OS="Ubuntu" EXPECTED_HOST_OS_VERSION="20.04" BUILD_BLOB_NAME="firefox-beta-ubuntu-20.04.zip" elif [[ "$BUILD_FLAVOR" == "firefox-beta-mac-11" ]]; then BROWSER_NAME="firefox-beta" EXTRA_BUILD_ARGS="--full" EXPECTED_HOST_OS="Darwin" EXPECTED_HOST_OS_VERSION="11.6" EXPECTED_ARCH="x86_64" BUILD_BLOB_NAME="firefox-beta-mac-11.zip" elif [[ "$BUILD_FLAVOR" == "firefox-beta-mac-11-arm64" ]]; then BROWSER_NAME="firefox-beta" EXTRA_BUILD_ARGS="--full" EXPECTED_HOST_OS="Darwin" EXPECTED_HOST_OS_VERSION="11.6" EXPECTED_ARCH="arm64" BUILD_BLOB_NAME="firefox-beta-mac-11-arm64.zip" elif [[ "$BUILD_FLAVOR" == "firefox-beta-win32" ]]; then BROWSER_NAME="firefox-beta" EXTRA_BUILD_ARGS="--full" EXPECTED_HOST_OS="MINGW" BUILD_BLOB_NAME="firefox-beta-win32.zip" elif [[ "$BUILD_FLAVOR" == "firefox-beta-win64" ]]; then BROWSER_NAME="firefox-beta" EXTRA_BUILD_ARGS="--win64 --full" EXPECTED_HOST_OS="MINGW" BUILD_BLOB_NAME="firefox-beta-win64.zip" # =========================== # WEBKIT COMPILATION # =========================== elif [[ "$BUILD_FLAVOR" == "webkit-ubuntu-18.04" ]]; then BROWSER_NAME="webkit" EXTRA_BUILD_ARGS="--full" EXPECTED_HOST_OS="Ubuntu" EXPECTED_HOST_OS_VERSION="18.04" BUILD_BLOB_NAME="webkit-ubuntu-18.04.zip" elif [[ "$BUILD_FLAVOR" == "webkit-ubuntu-20.04" ]]; then BROWSER_NAME="webkit" EXTRA_BUILD_ARGS="--full" EXPECTED_HOST_OS="Ubuntu" EXPECTED_HOST_OS_VERSION="20.04" BUILD_BLOB_NAME="webkit-ubuntu-20.04.zip" elif [[ "$BUILD_FLAVOR" == "webkit-win64" ]]; then BROWSER_NAME="webkit" EXPECTED_HOST_OS="MINGW" BUILD_BLOB_NAME="webkit-win64.zip" elif [[ "$BUILD_FLAVOR" == "webkit-mac-10.15" ]]; then BROWSER_NAME="webkit" EXPECTED_HOST_OS="Darwin" EXPECTED_HOST_OS_VERSION="10.15" BUILD_BLOB_NAME="webkit-mac-10.15.zip" elif [[ "$BUILD_FLAVOR" == "webkit-mac-11-arm64" ]]; then BROWSER_NAME="webkit" EXPECTED_HOST_OS="Darwin" EXPECTED_HOST_OS_VERSION="11.6" EXPECTED_ARCH="arm64" BUILD_BLOB_NAME="webkit-mac-11-arm64.zip" # =========================== # Unknown input # =========================== else echo ERROR: unknown build flavor - "$BUILD_FLAVOR" exit 1 fi if [[ -z "$BROWSER_DISPLAY_NAME" ]]; then BROWSER_DISPLAY_NAME="${BROWSER_NAME}" fi if [[ "$CURRENT_ARCH" != "$EXPECTED_ARCH" ]]; then echo "ERROR: cannot build $BUILD_FLAVOR" echo " -- expected arch: $EXPECTED_ARCH" echo " -- current arch: $CURRENT_ARCH" exit 1 fi if [[ "$CURRENT_HOST_OS" != $EXPECTED_HOST_OS* ]]; then echo "ERROR: cannot build $BUILD_FLAVOR" echo " -- expected OS: $EXPECTED_HOST_OS" echo " -- current OS: $CURRENT_HOST_OS" exit 1 fi if [[ "$CURRENT_HOST_OS_VERSION" != "$EXPECTED_HOST_OS_VERSION" ]]; then echo "ERROR: cannot build $BUILD_FLAVOR" echo " -- expected OS Version: $EXPECTED_HOST_OS_VERSION" echo " -- current OS Version: $CURRENT_HOST_OS_VERSION" exit 1 fi if [[ $(uname) == MINGW* ]]; then ZIP_PATH="$PWD/archive-$BROWSER_NAME.zip" LOG_PATH="$PWD/log-$BROWSER_NAME.zip" else ZIP_PATH="/tmp/archive-$BROWSER_NAME.zip" LOG_PATH="/tmp/log-$BROWSER_NAME.zip" fi if [[ -f "$ZIP_PATH" ]]; then echo "Archive $ZIP_PATH already exists - remove and re-run the script." exit 1 fi trap "rm -rf ${ZIP_PATH}; rm -rf ${LOG_PATH}; cd $(pwd -P);" INT TERM EXIT cd "$(dirname "$0")" BUILD_NUMBER=$(head -1 ./$BROWSER_NAME/BUILD_NUMBER) BUILD_BLOB_PATH="${BROWSER_NAME}/${BUILD_NUMBER}/${BUILD_BLOB_NAME}" LOG_BLOB_NAME="${BUILD_BLOB_NAME%.zip}.log.gz" LOG_BLOB_PATH="${BROWSER_NAME}/${BUILD_NUMBER}/${LOG_BLOB_NAME}" # pull from upstream and check if a new build has to be uploaded. if ! [[ ($2 == '-f') || ($2 == '--force') ]]; then if ./upload.sh "${BUILD_BLOB_PATH}" --check; then echo "Build is already uploaded - no changes." exit 0 fi else echo "Force-rebuilding the build." fi function generate_and_upload_browser_build { echo "-- preparing checkout" if ! ./prepare_checkout.sh $BROWSER_NAME; then return 20 fi echo "-- cleaning" if ! ./$BROWSER_NAME/clean.sh; then return 21 fi echo "-- building" if ! ./$BROWSER_NAME/build.sh $EXTRA_BUILD_ARGS; then return 22 fi echo "-- archiving to $ZIP_PATH" if ! ./$BROWSER_NAME/archive.sh "$ZIP_PATH" $EXTRA_ARCHIVE_ARGS; then return 23 fi echo "-- uploading" if ! ./upload.sh "$BUILD_BLOB_PATH" "$ZIP_PATH"; then return 24 fi return 0 } function create_roll_into_playwright_pr { curl -X POST \ -H "Accept: application/vnd.github.v3+json" \ -H "Authorization: token ${GH_TOKEN}" \ --data '{"event_type": "roll_into_pw", "client_payload": {"browser": "'"$1"'", "revision": "'"$2"'"}}' \ https://api.github.com/repos/microsoft/playwright/dispatches } source ./send_telegram_message.sh BUILD_ALIAS="$BUILD_FLAVOR r$BUILD_NUMBER" send_telegram_message "$BUILD_ALIAS -- started" if generate_and_upload_browser_build 2>&1 | ./sanitize_and_compress_log.js $LOG_PATH; then # Report successful build. Note: MINGW might not have `du` command. UPLOAD_SIZE="" if command -v du >/dev/null && command -v awk >/dev/null; then UPLOAD_SIZE="$(du -h "$ZIP_PATH" | awk '{print $1}') " fi send_telegram_message "$BUILD_ALIAS -- ${UPLOAD_SIZE}uploaded" # Check if we uploaded the last build. ( for i in $(cat "${BROWSER_NAME}/${BUILDS_LIST}"); do URL="https://playwright2.blob.core.windows.net/builds/${BROWSER_NAME}/${BUILD_NUMBER}/$i" if ! [[ $(curl -s -L -I "$URL" | head -1 | cut -f2 -d' ') == 200 ]]; then # Exit subshell echo "Missing build at ${URL}" exit fi done; LAST_COMMIT_MESSAGE=$(git log --format=%s -n 1 HEAD -- "./${BROWSER_NAME}/BUILD_NUMBER") send_telegram_message "<b>${BROWSER_DISPLAY_NAME} r${BUILD_NUMBER} COMPLETE! ✅</b> ${LAST_COMMIT_MESSAGE}" create_roll_into_playwright_pr $BROWSER_NAME $BUILD_NUMBER ) else RESULT_CODE="$?" if (( RESULT_CODE == 10 )); then FAILED_STEP="./download_gtk_and_wpe_and_zip_together.sh" elif (( RESULT_CODE == 11 )); then FAILED_STEP="./upload.sh" elif (( RESULT_CODE == 20 )); then FAILED_STEP="./prepare_checkout.sh" elif (( RESULT_CODE == 21 )); then FAILED_STEP="./clean.sh" elif (( RESULT_CODE == 22 )); then FAILED_STEP="./build.sh" elif (( RESULT_CODE == 23 )); then FAILED_STEP="./archive.sh" elif (( RESULT_CODE == 24 )); then FAILED_STEP="./upload.sh" else FAILED_STEP="<unknown step>" fi # Upload logs only in case of failure and report failure. ./upload.sh "${LOG_BLOB_PATH}" ${LOG_PATH} || true send_telegram_message "$BUILD_ALIAS -- ${FAILED_STEP} failed! ❌ <a href='https://playwright.azureedge.net/builds/${LOG_BLOB_PATH}'>${LOG_BLOB_NAME}</a> -- <a href='$GITHUB_SERVER_URL/$GITHUB_REPOSITORY/actions/runs/$GITHUB_RUN_ID'>GitHub Action Logs</a>" exit 1 fi
browser_patches/checkout_build_archive_upload.sh
0
https://github.com/microsoft/playwright/commit/9d03a85c3039fcc968aa7d29777bbca85789fd4a
[ 0.0001775413693394512, 0.00017046753782778978, 0.0001632606436032802, 0.0001704682072158903, 0.0000035285722788103158 ]
{ "id": 4, "code_window": [ " query: (isNot: boolean, timeout: number) => Promise<{ matches: boolean, received?: string, log?: string[] }>,\n", " expected: string | RegExp,\n", " options: { timeout?: number, matchSubstring?: boolean } = {},\n", ") {\n", " const testInfo = currentTestInfo();\n", " if (!testInfo)\n", " throw new Error(`${matcherName} must be called during the test`);\n", " expectType(receiver, receiverType, matcherName);\n", "\n", " const matcherOptions = {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "packages/playwright-test/src/matchers/toMatchText.ts", "type": "replace", "edit_start_line_idx": 37 }
/** * Copyright Microsoft Corporation. All rights reserved. * * 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 { currentTestInfo } from '../globals'; import type { Expect } from '../types'; import { expectType } from '../util'; import { callLogText } from './toMatchText'; // Omit colon and one or more spaces, so can call getLabelPrinter. const EXPECTED_LABEL = 'Expected'; const RECEIVED_LABEL = 'Received'; // The optional property of matcher context is true if undefined. const isExpand = (expand?: boolean): boolean => expand !== false; export async function toEqual<T>( this: ReturnType<Expect['getState']>, matcherName: string, receiver: any, receiverType: string, query: (isNot: boolean, timeout: number) => Promise<{ matches: boolean, received?: any, log?: string[] }>, expected: T, options: { timeout?: number, contains?: boolean } = {}, ) { const testInfo = currentTestInfo(); if (!testInfo) throw new Error(`${matcherName} must be called during the test`); expectType(receiver, receiverType, matcherName); const matcherOptions = { comment: options.contains ? '' : 'deep equality', isNot: this.isNot, promise: this.promise, }; let defaultExpectTimeout = testInfo.project.expect?.timeout; if (typeof defaultExpectTimeout === 'undefined') defaultExpectTimeout = 5000; const timeout = options.timeout === 0 ? 0 : options.timeout || defaultExpectTimeout; const { matches: pass, received, log } = await query(this.isNot, timeout); const message = pass ? () => this.utils.matcherHint(matcherName, undefined, undefined, matcherOptions) + '\n\n' + `Expected: not ${this.utils.printExpected(expected)}\n` + (this.utils.stringify(expected) !== this.utils.stringify(received) ? `Received: ${this.utils.printReceived(received)}` : '') + callLogText(log) : () => this.utils.matcherHint(matcherName, undefined, undefined, matcherOptions) + '\n\n' + this.utils.printDiffOrStringify( expected, received, EXPECTED_LABEL, RECEIVED_LABEL, isExpand(this.expand), ) + callLogText(log); // Passing the actual and expected objects so that a custom reporter // could access them, for example in order to display a custom visual diff, // or create a different error message return { actual: received, expected, message, name: matcherName, pass }; }
packages/playwright-test/src/matchers/toEqual.ts
1
https://github.com/microsoft/playwright/commit/9d03a85c3039fcc968aa7d29777bbca85789fd4a
[ 0.9978713989257812, 0.4904363453388214, 0.000168824743013829, 0.47102636098861694, 0.47732383012771606 ]
{ "id": 4, "code_window": [ " query: (isNot: boolean, timeout: number) => Promise<{ matches: boolean, received?: string, log?: string[] }>,\n", " expected: string | RegExp,\n", " options: { timeout?: number, matchSubstring?: boolean } = {},\n", ") {\n", " const testInfo = currentTestInfo();\n", " if (!testInfo)\n", " throw new Error(`${matcherName} must be called during the test`);\n", " expectType(receiver, receiverType, matcherName);\n", "\n", " const matcherOptions = {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "packages/playwright-test/src/matchers/toMatchText.ts", "type": "replace", "edit_start_line_idx": 37 }
# class: Browser * extends: [EventEmitter] A Browser is created via [`method: BrowserType.launch`]. An example of using a [Browser] to create a [Page]: ```js const { firefox } = require('playwright'); // Or 'chromium' or 'webkit'. (async () => { const browser = await firefox.launch(); const page = await browser.newPage(); await page.goto('https://example.com'); await browser.close(); })(); ``` ```java import com.microsoft.playwright.*; public class Example { public static void main(String[] args) { try (Playwright playwright = Playwright.create()) { BrowserType firefox = playwright.firefox() Browser browser = firefox.launch(); Page page = browser.newPage(); page.navigate('https://example.com'); browser.close(); } } } ``` ```python async import asyncio from playwright.async_api import async_playwright async def run(playwright): firefox = playwright.firefox browser = await firefox.launch() page = await browser.new_page() await page.goto("https://example.com") await browser.close() async def main(): async with async_playwright() as playwright: await run(playwright) asyncio.run(main()) ``` ```python sync from playwright.sync_api import sync_playwright def run(playwright): firefox = playwright.firefox browser = firefox.launch() page = browser.new_page() page.goto("https://example.com") browser.close() with sync_playwright() as playwright: run(playwright) ``` ```csharp using Microsoft.Playwright; using System.Threading.Tasks; class Program { public static async Task Main() { using var playwright = await Playwright.CreateAsync(); var firefox = playwright.Firefox; var browser = await firefox.LaunchAsync(new BrowserTypeLaunchOptions { Headless = false }); var page = await browser.NewPageAsync(); await page.GotoAsync("https://www.bing.com"); await browser.CloseAsync(); } } ``` ## event: Browser.disconnected - argument: <[Browser]> Emitted when Browser gets disconnected from the browser application. This might happen because of one of the following: * Browser application is closed or crashed. * The [`method: Browser.close`] method was called. ## async method: Browser.close In case this browser is obtained using [`method: BrowserType.launch`], closes the browser and all of its pages (if any were opened). In case this browser is connected to, clears all created contexts belonging to this browser and disconnects from the browser server. The [Browser] object itself is considered to be disposed and cannot be used anymore. ## method: Browser.contexts - returns: <[Array]<[BrowserContext]>> Returns an array of all open browser contexts. In a newly created browser, this will return zero browser contexts. ```js const browser = await pw.webkit.launch(); console.log(browser.contexts().length); // prints `0` const context = await browser.newContext(); console.log(browser.contexts().length); // prints `1` ``` ```java Browser browser = pw.webkit().launch(); System.out.println(browser.contexts().size()); // prints "0" BrowserContext context = browser.newContext(); System.out.println(browser.contexts().size()); // prints "1" ``` ```python async browser = await pw.webkit.launch() print(len(browser.contexts())) # prints `0` context = await browser.new_context() print(len(browser.contexts())) # prints `1` ``` ```python sync browser = pw.webkit.launch() print(len(browser.contexts())) # prints `0` context = browser.new_context() print(len(browser.contexts())) # prints `1` ``` ```csharp using var playwright = await Playwright.CreateAsync(); var browser = await playwright.Webkit.LaunchAsync(); System.Console.WriteLine(browser.Contexts.Count); // prints "0" var context = await browser.NewContextAsync(); System.Console.WriteLine(browser.Contexts.Count); // prints "1" ``` ## method: Browser.isConnected - returns: <[boolean]> Indicates that the browser is connected. ## async method: Browser.newBrowserCDPSession * langs: js, python - returns: <[CDPSession]> :::note CDP Sessions are only supported on Chromium-based browsers. ::: Returns the newly created browser session. ## async method: Browser.newContext - returns: <[BrowserContext]> Creates a new browser context. It won't share cookies/cache with other browser contexts. ```js (async () => { const browser = await playwright.firefox.launch(); // Or 'chromium' or 'webkit'. // Create a new incognito browser context. const context = await browser.newContext(); // Create a new page in a pristine context. const page = await context.newPage(); await page.goto('https://example.com'); })(); ``` ```java Browser browser = playwright.firefox().launch(); // Or 'chromium' or 'webkit'. // Create a new incognito browser context. BrowserContext context = browser.newContext(); // Create a new page in a pristine context. Page page = context.newPage(); page.navigate('https://example.com'); ``` ```python async browser = await playwright.firefox.launch() # or "chromium" or "webkit". # create a new incognito browser context. context = await browser.new_context() # create a new page in a pristine context. page = await context.new_page() await page.goto("https://example.com") ``` ```python sync browser = playwright.firefox.launch() # or "chromium" or "webkit". # create a new incognito browser context. context = browser.new_context() # create a new page in a pristine context. page = context.new_page() page.goto("https://example.com") ``` ```csharp using var playwright = await Playwright.CreateAsync(); var browser = await playwright.Firefox.LaunchAsync(); // Create a new incognito browser context. var context = await browser.NewContextAsync(); // Create a new page in a pristine context. var page = await context.NewPageAsync(); ; await page.GotoAsync("https://www.bing.com"); ``` ### option: Browser.newContext.-inline- = %%-shared-context-params-list-%% ### option: Browser.newContext.proxy = %%-context-option-proxy-%% ### option: Browser.newContext.storageState = %%-js-python-context-option-storage-state-%% ### option: Browser.newContext.storageState = %%-csharp-java-context-option-storage-state-%% ### option: Browser.newContext.storageStatePath = %%-csharp-java-context-option-storage-state-path-%% ## async method: Browser.newPage - returns: <[Page]> Creates a new page in a new browser context. Closing this page will close the context as well. This is a convenience API that should only be used for the single-page scenarios and short snippets. Production code and testing frameworks should explicitly create [`method: Browser.newContext`] followed by the [`method: BrowserContext.newPage`] to control their exact life times. ### option: Browser.newPage.-inline- = %%-shared-context-params-list-%% ### option: Browser.newPage.proxy = %%-context-option-proxy-%% ### option: Browser.newPage.storageState = %%-js-python-context-option-storage-state-%% ### option: Browser.newPage.storageState = %%-csharp-java-context-option-storage-state-%% ### option: Browser.newPage.storageStatePath = %%-csharp-java-context-option-storage-state-path-%% ## async method: Browser.startTracing * langs: java, js, python :::note This API controls [Chromium Tracing](https://www.chromium.org/developers/how-tos/trace-event-profiling-tool) which is a low-level chromium-specific debugging tool. API to control [Playwright Tracing](../trace-viewer) could be found [here](./class-tracing). ::: You can use [`method: Browser.startTracing`] and [`method: Browser.stopTracing`] to create a trace file that can be opened in Chrome DevTools performance panel. ```js await browser.startTracing(page, {path: 'trace.json'}); await page.goto('https://www.google.com'); await browser.stopTracing(); ``` ```java browser.startTracing(page, new Browser.StartTracingOptions() .setPath(Paths.get("trace.json"))); page.goto('https://www.google.com'); browser.stopTracing(); ``` ```python async await browser.start_tracing(page, path="trace.json") await page.goto("https://www.google.com") await browser.stop_tracing() ``` ```python sync browser.start_tracing(page, path="trace.json") page.goto("https://www.google.com") browser.stop_tracing() ``` ### param: Browser.startTracing.page - `page` <[Page]> Optional, if specified, tracing includes screenshots of the given page. ### option: Browser.startTracing.path - `path` <[path]> A path to write the trace file to. ### option: Browser.startTracing.screenshots - `screenshots` <[boolean]> captures screenshots in the trace. ### option: Browser.startTracing.categories - `categories` <[Array]<[string]>> specify custom categories to use instead of default. ## async method: Browser.stopTracing * langs: java, js, python - returns: <[Buffer]> :::note This API controls [Chromium Tracing](https://www.chromium.org/developers/how-tos/trace-event-profiling-tool) which is a low-level chromium-specific debugging tool. API to control [Playwright Tracing](../trace-viewer) could be found [here](./class-tracing). ::: Returns the buffer with trace data. ## method: Browser.version - returns: <[string]> Returns the browser version.
docs/src/api/class-browser.md
0
https://github.com/microsoft/playwright/commit/9d03a85c3039fcc968aa7d29777bbca85789fd4a
[ 0.0001767684007063508, 0.0001710887299850583, 0.00016184149717446417, 0.00017327610112261027, 0.000004245143827574793 ]
{ "id": 4, "code_window": [ " query: (isNot: boolean, timeout: number) => Promise<{ matches: boolean, received?: string, log?: string[] }>,\n", " expected: string | RegExp,\n", " options: { timeout?: number, matchSubstring?: boolean } = {},\n", ") {\n", " const testInfo = currentTestInfo();\n", " if (!testInfo)\n", " throw new Error(`${matcherName} must be called during the test`);\n", " expectType(receiver, receiverType, matcherName);\n", "\n", " const matcherOptions = {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "packages/playwright-test/src/matchers/toMatchText.ts", "type": "replace", "edit_start_line_idx": 37 }
/** * 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 { Frame, NavigationEvent } from '../server/frames'; import * as channels from '../protocol/channels'; import { Dispatcher, DispatcherScope, lookupNullableDispatcher, existingDispatcher } from './dispatcher'; import { ElementHandleDispatcher } from './elementHandlerDispatcher'; import { parseArgument, serializeResult } from './jsHandleDispatcher'; import { ResponseDispatcher, RequestDispatcher } from './networkDispatchers'; import { CallMetadata } from '../server/instrumentation'; export class FrameDispatcher extends Dispatcher<Frame, channels.FrameInitializer, channels.FrameEvents> implements channels.FrameChannel { private _frame: Frame; static from(scope: DispatcherScope, frame: Frame): FrameDispatcher { const result = existingDispatcher<FrameDispatcher>(frame); return result || new FrameDispatcher(scope, frame); } static fromNullable(scope: DispatcherScope, frame: Frame | null): FrameDispatcher | undefined { if (!frame) return; return FrameDispatcher.from(scope, frame); } private constructor(scope: DispatcherScope, frame: Frame) { super(scope, frame, 'Frame', { url: frame.url(), name: frame.name(), parentFrame: FrameDispatcher.fromNullable(scope, frame.parentFrame()), loadStates: Array.from(frame._subtreeLifecycleEvents), }); this._frame = frame; frame.on(Frame.Events.AddLifecycle, lifecycleEvent => { this._dispatchEvent('loadstate', { add: lifecycleEvent }); }); frame.on(Frame.Events.RemoveLifecycle, lifecycleEvent => { this._dispatchEvent('loadstate', { remove: lifecycleEvent }); }); frame.on(Frame.Events.Navigation, (event: NavigationEvent) => { const params = { url: event.url, name: event.name, error: event.error ? event.error.message : undefined }; if (event.newDocument) (params as any).newDocument = { request: RequestDispatcher.fromNullable(this._scope, event.newDocument.request || null) }; this._dispatchEvent('navigated', params); }); } async goto(params: channels.FrameGotoParams, metadata: CallMetadata): Promise<channels.FrameGotoResult> { return { response: lookupNullableDispatcher<ResponseDispatcher>(await this._frame.goto(metadata, params.url, params)) }; } async frameElement(): Promise<channels.FrameFrameElementResult> { return { element: ElementHandleDispatcher.from(this._scope, await this._frame.frameElement()) }; } async evaluateExpression(params: channels.FrameEvaluateExpressionParams, metadata: CallMetadata): Promise<channels.FrameEvaluateExpressionResult> { return { value: serializeResult(await this._frame.evaluateExpressionAndWaitForSignals(params.expression, params.isFunction, parseArgument(params.arg), 'main')) }; } async evaluateExpressionHandle(params: channels.FrameEvaluateExpressionHandleParams, metadata: CallMetadata): Promise<channels.FrameEvaluateExpressionHandleResult> { return { handle: ElementHandleDispatcher.fromJSHandle(this._scope, await this._frame.evaluateExpressionHandleAndWaitForSignals(params.expression, params.isFunction, parseArgument(params.arg), 'main')) }; } async waitForSelector(params: channels.FrameWaitForSelectorParams, metadata: CallMetadata): Promise<channels.FrameWaitForSelectorResult> { return { element: ElementHandleDispatcher.fromNullable(this._scope, await this._frame.waitForSelector(metadata, params.selector, params)) }; } async dispatchEvent(params: channels.FrameDispatchEventParams, metadata: CallMetadata): Promise<void> { return this._frame.dispatchEvent(metadata, params.selector, params.type, parseArgument(params.eventInit), params); } async evalOnSelector(params: channels.FrameEvalOnSelectorParams, metadata: CallMetadata): Promise<channels.FrameEvalOnSelectorResult> { return { value: serializeResult(await this._frame.evalOnSelectorAndWaitForSignals(params.selector, !!params.strict, params.expression, params.isFunction, parseArgument(params.arg))) }; } async evalOnSelectorAll(params: channels.FrameEvalOnSelectorAllParams, metadata: CallMetadata): Promise<channels.FrameEvalOnSelectorAllResult> { return { value: serializeResult(await this._frame.evalOnSelectorAllAndWaitForSignals(params.selector, params.expression, params.isFunction, parseArgument(params.arg))) }; } async querySelector(params: channels.FrameQuerySelectorParams, metadata: CallMetadata): Promise<channels.FrameQuerySelectorResult> { return { element: ElementHandleDispatcher.fromNullable(this._scope, await this._frame.querySelector(params.selector, params)) }; } async querySelectorAll(params: channels.FrameQuerySelectorAllParams, metadata: CallMetadata): Promise<channels.FrameQuerySelectorAllResult> { const elements = await this._frame.querySelectorAll(params.selector); return { elements: elements.map(e => ElementHandleDispatcher.from(this._scope, e)) }; } async content(): Promise<channels.FrameContentResult> { return { value: await this._frame.content() }; } async setContent(params: channels.FrameSetContentParams, metadata: CallMetadata): Promise<void> { return await this._frame.setContent(metadata, params.html, params); } async addScriptTag(params: channels.FrameAddScriptTagParams, metadata: CallMetadata): Promise<channels.FrameAddScriptTagResult> { return { element: ElementHandleDispatcher.from(this._scope, await this._frame.addScriptTag(params)) }; } async addStyleTag(params: channels.FrameAddStyleTagParams, metadata: CallMetadata): Promise<channels.FrameAddStyleTagResult> { return { element: ElementHandleDispatcher.from(this._scope, await this._frame.addStyleTag(params)) }; } async click(params: channels.FrameClickParams, metadata: CallMetadata): Promise<void> { return await this._frame.click(metadata, params.selector, params); } async dblclick(params: channels.FrameDblclickParams, metadata: CallMetadata): Promise<void> { return await this._frame.dblclick(metadata, params.selector, params); } async dragAndDrop(params: channels.FrameDragAndDropParams, metadata: CallMetadata): Promise<void> { return await this._frame.dragAndDrop(metadata, params.source, params.target, params); } async tap(params: channels.FrameTapParams, metadata: CallMetadata): Promise<void> { return await this._frame.tap(metadata, params.selector, params); } async fill(params: channels.FrameFillParams, metadata: CallMetadata): Promise<void> { return await this._frame.fill(metadata, params.selector, params.value, params); } async focus(params: channels.FrameFocusParams, metadata: CallMetadata): Promise<void> { await this._frame.focus(metadata, params.selector, params); } async textContent(params: channels.FrameTextContentParams, metadata: CallMetadata): Promise<channels.FrameTextContentResult> { const value = await this._frame.textContent(metadata, params.selector, params); return { value: value === null ? undefined : value }; } async innerText(params: channels.FrameInnerTextParams, metadata: CallMetadata): Promise<channels.FrameInnerTextResult> { return { value: await this._frame.innerText(metadata, params.selector, params) }; } async innerHTML(params: channels.FrameInnerHTMLParams, metadata: CallMetadata): Promise<channels.FrameInnerHTMLResult> { return { value: await this._frame.innerHTML(metadata, params.selector, params) }; } async getAttribute(params: channels.FrameGetAttributeParams, metadata: CallMetadata): Promise<channels.FrameGetAttributeResult> { const value = await this._frame.getAttribute(metadata, params.selector, params.name, params); return { value: value === null ? undefined : value }; } async inputValue(params: channels.FrameInputValueParams, metadata: CallMetadata): Promise<channels.FrameInputValueResult> { const value = await this._frame.inputValue(metadata, params.selector, params); return { value }; } async isChecked(params: channels.FrameIsCheckedParams, metadata: CallMetadata): Promise<channels.FrameIsCheckedResult> { return { value: await this._frame.isChecked(metadata, params.selector, params) }; } async isDisabled(params: channels.FrameIsDisabledParams, metadata: CallMetadata): Promise<channels.FrameIsDisabledResult> { return { value: await this._frame.isDisabled(metadata, params.selector, params) }; } async isEditable(params: channels.FrameIsEditableParams, metadata: CallMetadata): Promise<channels.FrameIsEditableResult> { return { value: await this._frame.isEditable(metadata, params.selector, params) }; } async isEnabled(params: channels.FrameIsEnabledParams, metadata: CallMetadata): Promise<channels.FrameIsEnabledResult> { return { value: await this._frame.isEnabled(metadata, params.selector, params) }; } async isHidden(params: channels.FrameIsHiddenParams, metadata: CallMetadata): Promise<channels.FrameIsHiddenResult> { return { value: await this._frame.isHidden(metadata, params.selector, params) }; } async isVisible(params: channels.FrameIsVisibleParams, metadata: CallMetadata): Promise<channels.FrameIsVisibleResult> { return { value: await this._frame.isVisible(metadata, params.selector, params) }; } async hover(params: channels.FrameHoverParams, metadata: CallMetadata): Promise<void> { return await this._frame.hover(metadata, params.selector, params); } async selectOption(params: channels.FrameSelectOptionParams, metadata: CallMetadata): Promise<channels.FrameSelectOptionResult> { const elements = (params.elements || []).map(e => (e as ElementHandleDispatcher)._elementHandle); return { values: await this._frame.selectOption(metadata, params.selector, elements, params.options || [], params) }; } async setInputFiles(params: channels.FrameSetInputFilesParams, metadata: CallMetadata): Promise<void> { return await this._frame.setInputFiles(metadata, params.selector, params.files, params); } async type(params: channels.FrameTypeParams, metadata: CallMetadata): Promise<void> { return await this._frame.type(metadata, params.selector, params.text, params); } async press(params: channels.FramePressParams, metadata: CallMetadata): Promise<void> { return await this._frame.press(metadata, params.selector, params.key, params); } async check(params: channels.FrameCheckParams, metadata: CallMetadata): Promise<void> { return await this._frame.check(metadata, params.selector, params); } async uncheck(params: channels.FrameUncheckParams, metadata: CallMetadata): Promise<void> { return await this._frame.uncheck(metadata, params.selector, params); } async waitForTimeout(params: channels.FrameWaitForTimeoutParams, metadata: CallMetadata): Promise<void> { return await this._frame.waitForTimeout(metadata, params.timeout); } async waitForFunction(params: channels.FrameWaitForFunctionParams, metadata: CallMetadata): Promise<channels.FrameWaitForFunctionResult> { return { handle: ElementHandleDispatcher.fromJSHandle(this._scope, await this._frame._waitForFunctionExpression(metadata, params.expression, params.isFunction, parseArgument(params.arg), params)) }; } async title(params: channels.FrameTitleParams, metadata: CallMetadata): Promise<channels.FrameTitleResult> { return { value: await this._frame.title() }; } async expect(params: channels.FrameExpectParams, metadata: CallMetadata): Promise<channels.FrameExpectResult> { const expectedValue = params.expectedValue ? parseArgument(params.expectedValue) : undefined; const result = await this._frame.expect(metadata, params.selector, { ...params, expectedValue }); if (result.received !== undefined) result.received = serializeResult(result.received); if (result.matches === params.isNot) metadata.error = { error: { name: 'Expect', message: 'Expect failed' } }; return result; } }
packages/playwright-core/src/dispatchers/frameDispatcher.ts
0
https://github.com/microsoft/playwright/commit/9d03a85c3039fcc968aa7d29777bbca85789fd4a
[ 0.0001773577678250149, 0.00017501733964309096, 0.0001675300154602155, 0.00017558217223268002, 0.0000020594202396750916 ]
{ "id": 4, "code_window": [ " query: (isNot: boolean, timeout: number) => Promise<{ matches: boolean, received?: string, log?: string[] }>,\n", " expected: string | RegExp,\n", " options: { timeout?: number, matchSubstring?: boolean } = {},\n", ") {\n", " const testInfo = currentTestInfo();\n", " if (!testInfo)\n", " throw new Error(`${matcherName} must be called during the test`);\n", " expectType(receiver, receiverType, matcherName);\n", "\n", " const matcherOptions = {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "packages/playwright-test/src/matchers/toMatchText.ts", "type": "replace", "edit_start_line_idx": 37 }
/** * 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 channels from '../protocol/channels'; import * as api from '../../types/types'; export class Coverage implements api.Coverage { private _channel: channels.PageChannel; constructor(channel: channels.PageChannel) { this._channel = channel; } async startJSCoverage(options: channels.PageStartJSCoverageOptions = {}) { await this._channel.startJSCoverage(options); } async stopJSCoverage(): Promise<channels.PageStopJSCoverageResult['entries']> { return (await this._channel.stopJSCoverage()).entries; } async startCSSCoverage(options: channels.PageStartCSSCoverageOptions = {}) { await this._channel.startCSSCoverage(options); } async stopCSSCoverage(): Promise<channels.PageStopCSSCoverageResult['entries']> { return (await this._channel.stopCSSCoverage()).entries; } }
packages/playwright-core/src/client/coverage.ts
0
https://github.com/microsoft/playwright/commit/9d03a85c3039fcc968aa7d29777bbca85789fd4a
[ 0.00017601843865122646, 0.00017383134400006384, 0.00016950817371252924, 0.0001752086536725983, 0.0000024548653527745046 ]
{ "id": 5, "code_window": [ " this.utils.printWithType('Expected', expected, this.utils.printExpected),\n", " ),\n", " );\n", " }\n", "\n", " let defaultExpectTimeout = testInfo.project.expect?.timeout;\n", " if (typeof defaultExpectTimeout === 'undefined')\n", " defaultExpectTimeout = 5000;\n", " const timeout = options.timeout === 0 ? 0 : options.timeout || defaultExpectTimeout;\n", "\n", " const { matches: pass, received, log } = await query(this.isNot, timeout);\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " const testInfo = currentTestInfo();\n", " let defaultExpectTimeout = testInfo?.project.expect?.timeout;\n" ], "file_path": "packages/playwright-test/src/matchers/toMatchText.ts", "type": "replace", "edit_start_line_idx": 62 }
/** * Copyright Microsoft Corporation. All rights reserved. * * 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 { currentTestInfo } from '../globals'; import type { Expect } from '../types'; import { expectType } from '../util'; import { callLogText } from './toMatchText'; // Omit colon and one or more spaces, so can call getLabelPrinter. const EXPECTED_LABEL = 'Expected'; const RECEIVED_LABEL = 'Received'; // The optional property of matcher context is true if undefined. const isExpand = (expand?: boolean): boolean => expand !== false; export async function toEqual<T>( this: ReturnType<Expect['getState']>, matcherName: string, receiver: any, receiverType: string, query: (isNot: boolean, timeout: number) => Promise<{ matches: boolean, received?: any, log?: string[] }>, expected: T, options: { timeout?: number, contains?: boolean } = {}, ) { const testInfo = currentTestInfo(); if (!testInfo) throw new Error(`${matcherName} must be called during the test`); expectType(receiver, receiverType, matcherName); const matcherOptions = { comment: options.contains ? '' : 'deep equality', isNot: this.isNot, promise: this.promise, }; let defaultExpectTimeout = testInfo.project.expect?.timeout; if (typeof defaultExpectTimeout === 'undefined') defaultExpectTimeout = 5000; const timeout = options.timeout === 0 ? 0 : options.timeout || defaultExpectTimeout; const { matches: pass, received, log } = await query(this.isNot, timeout); const message = pass ? () => this.utils.matcherHint(matcherName, undefined, undefined, matcherOptions) + '\n\n' + `Expected: not ${this.utils.printExpected(expected)}\n` + (this.utils.stringify(expected) !== this.utils.stringify(received) ? `Received: ${this.utils.printReceived(received)}` : '') + callLogText(log) : () => this.utils.matcherHint(matcherName, undefined, undefined, matcherOptions) + '\n\n' + this.utils.printDiffOrStringify( expected, received, EXPECTED_LABEL, RECEIVED_LABEL, isExpand(this.expand), ) + callLogText(log); // Passing the actual and expected objects so that a custom reporter // could access them, for example in order to display a custom visual diff, // or create a different error message return { actual: received, expected, message, name: matcherName, pass }; }
packages/playwright-test/src/matchers/toEqual.ts
1
https://github.com/microsoft/playwright/commit/9d03a85c3039fcc968aa7d29777bbca85789fd4a
[ 0.9981510043144226, 0.49764570593833923, 0.00017443817341700196, 0.4958796501159668, 0.4971000850200653 ]
{ "id": 5, "code_window": [ " this.utils.printWithType('Expected', expected, this.utils.printExpected),\n", " ),\n", " );\n", " }\n", "\n", " let defaultExpectTimeout = testInfo.project.expect?.timeout;\n", " if (typeof defaultExpectTimeout === 'undefined')\n", " defaultExpectTimeout = 5000;\n", " const timeout = options.timeout === 0 ? 0 : options.timeout || defaultExpectTimeout;\n", "\n", " const { matches: pass, received, log } = await query(this.isNot, timeout);\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " const testInfo = currentTestInfo();\n", " let defaultExpectTimeout = testInfo?.project.expect?.timeout;\n" ], "file_path": "packages/playwright-test/src/matchers/toMatchText.ts", "type": "replace", "edit_start_line_idx": 62 }
/** * 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 path from 'path'; import { Generator } from './generator'; (async () => { const rootDir = path.resolve(process.cwd(), process.argv[2] || ''); const generator = new Generator(rootDir); await generator.run(); })().catch(error => { console.error(error); process.exit(1); });
packages/create-playwright/src/cli.ts
0
https://github.com/microsoft/playwright/commit/9d03a85c3039fcc968aa7d29777bbca85789fd4a
[ 0.0001790914684534073, 0.00017616046534385532, 0.00017449524602852762, 0.00017489468154963106, 0.0000020789375412277877 ]
{ "id": 5, "code_window": [ " this.utils.printWithType('Expected', expected, this.utils.printExpected),\n", " ),\n", " );\n", " }\n", "\n", " let defaultExpectTimeout = testInfo.project.expect?.timeout;\n", " if (typeof defaultExpectTimeout === 'undefined')\n", " defaultExpectTimeout = 5000;\n", " const timeout = options.timeout === 0 ? 0 : options.timeout || defaultExpectTimeout;\n", "\n", " const { matches: pass, received, log } = await query(this.isNot, timeout);\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " const testInfo = currentTestInfo();\n", " let defaultExpectTimeout = testInfo?.project.expect?.timeout;\n" ], "file_path": "packages/playwright-test/src/matchers/toMatchText.ts", "type": "replace", "edit_start_line_idx": 62 }
# -*- Mode: python; indent-tabs-mode: nil; tab-width: 40 -*- # vim: set filetype=python: # This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. Classes = [ { 'cid': '{d69ecefe-3df7-4d11-9dc7-f604edb96da2}', 'contract_ids': ['@mozilla.org/juggler/remotedebuggingpipe;1'], 'type': 'nsIRemoteDebuggingPipe', 'constructor': 'mozilla::nsRemoteDebuggingPipe::GetSingleton', 'headers': ['/juggler/pipe/nsRemoteDebuggingPipe.h'], }, ]
browser_patches/firefox-beta/juggler/pipe/components.conf
0
https://github.com/microsoft/playwright/commit/9d03a85c3039fcc968aa7d29777bbca85789fd4a
[ 0.00017749668040778488, 0.000175629451405257, 0.00017376220785081387, 0.000175629451405257, 0.0000018672362784855068 ]
{ "id": 5, "code_window": [ " this.utils.printWithType('Expected', expected, this.utils.printExpected),\n", " ),\n", " );\n", " }\n", "\n", " let defaultExpectTimeout = testInfo.project.expect?.timeout;\n", " if (typeof defaultExpectTimeout === 'undefined')\n", " defaultExpectTimeout = 5000;\n", " const timeout = options.timeout === 0 ? 0 : options.timeout || defaultExpectTimeout;\n", "\n", " const { matches: pass, received, log } = await query(this.isNot, timeout);\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " const testInfo = currentTestInfo();\n", " let defaultExpectTimeout = testInfo?.project.expect?.timeout;\n" ], "file_path": "packages/playwright-test/src/matchers/toMatchText.ts", "type": "replace", "edit_start_line_idx": 62 }
Copyright (c) 2011, Edgar Tolentino and Pablo Impallari (www.impallari.com|[email protected]), Copyright (c) 2011, Igino Marini. (www.ikern.com|[email protected]), with Reserved Font Names "Dosis". This Font Software is licensed under the SIL Open Font License, Version 1.1. This license is copied below, and is also available with a FAQ at: http://scripts.sil.org/OFL ----------------------------------------------------------- SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 ----------------------------------------------------------- PREAMBLE The goals of the Open Font License (OFL) are to stimulate worldwide development of collaborative font projects, to support the font creation efforts of academic and linguistic communities, and to provide a free and open framework in which fonts may be shared and improved in partnership with others. The OFL allows the licensed fonts to be used, studied, modified and redistributed freely as long as they are not sold by themselves. The fonts, including any derivative works, can be bundled, embedded, redistributed and/or sold with any software provided that any reserved names are not used by derivative works. The fonts and derivatives, however, cannot be released under any other type of license. The requirement for fonts to remain under this license does not apply to any document created using the fonts or their derivatives. DEFINITIONS "Font Software" refers to the set of files released by the Copyright Holder(s) under this license and clearly marked as such. This may include source files, build scripts and documentation. "Reserved Font Name" refers to any names specified as such after the copyright statement(s). "Original Version" refers to the collection of Font Software components as distributed by the Copyright Holder(s). "Modified Version" refers to any derivative made by adding to, deleting, or substituting -- in part or in whole -- any of the components of the Original Version, by changing formats or by porting the Font Software to a new environment. "Author" refers to any designer, engineer, programmer, technical writer or other person who contributed to the Font Software. PERMISSION & CONDITIONS Permission is hereby granted, free of charge, to any person obtaining a copy of the Font Software, to use, study, copy, merge, embed, modify, redistribute, and sell modified and unmodified copies of the Font Software, subject to the following conditions: 1) Neither the Font Software nor any of its individual components, in Original or Modified Versions, may be sold by itself. 2) Original or Modified Versions of the Font Software may be bundled, redistributed and/or sold with any software, provided that each copy contains the above copyright notice and this license. These can be included either as stand-alone text files, human-readable headers or in the appropriate machine-readable metadata fields within text or binary files as long as those fields can be easily viewed by the user. 3) No Modified Version of the Font Software may use the Reserved Font Name(s) unless explicit written permission is granted by the corresponding Copyright Holder. This restriction only applies to the primary font name as presented to the users. 4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font Software shall not be used to promote, endorse or advertise any Modified Version, except to acknowledge the contribution(s) of the Copyright Holder(s) and the Author(s) or with their explicit written permission. 5) The Font Software, modified or unmodified, in part or in whole, must be distributed entirely under this license, and must not be distributed under any other license. The requirement for fonts to remain under this license does not apply to any document created using the Font Software. TERMINATION This license becomes null and void if any of the above conditions are not met. DISCLAIMER THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM OTHER DEALINGS IN THE FONT SOFTWARE.
tests/assets/csscoverage/OFL.txt
0
https://github.com/microsoft/playwright/commit/9d03a85c3039fcc968aa7d29777bbca85789fd4a
[ 0.00017799936176743358, 0.00017498516535852104, 0.00016615043568890542, 0.00017631551600061357, 0.000003498140358715318 ]
{ "id": 0, "code_window": [ "import Divider from '@mui/material/Divider';\n", "import IconButton from '@mui/material/IconButton';\n", "import MenuIcon from '@mui/icons-material/Menu';\n", "import ChevronLeftIcon from '@mui/icons-material/ChevronLeft';\n", "import ChevronRightIcon from '@mui/icons-material/ChevronRight';\n", "import ListItem from '@mui/material/ListItem';\n", "import ListItemIcon from '@mui/material/ListItemIcon';\n", "import ListItemText from '@mui/material/ListItemText';\n", "import InboxIcon from '@mui/icons-material/MoveToInbox';\n", "import MailIcon from '@mui/icons-material/Mail';\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "import ListItemButton from '@mui/material/ListItemButton';\n" ], "file_path": "docs/data/material/components/drawers/MiniDrawer.js", "type": "replace", "edit_start_line_idx": 14 }
import * as React from 'react'; import { styled, useTheme, Theme, CSSObject } from '@mui/material/styles'; import Box from '@mui/material/Box'; import MuiDrawer from '@mui/material/Drawer'; import MuiAppBar, { AppBarProps as MuiAppBarProps } from '@mui/material/AppBar'; import Toolbar from '@mui/material/Toolbar'; import List from '@mui/material/List'; import CssBaseline from '@mui/material/CssBaseline'; import Typography from '@mui/material/Typography'; import Divider from '@mui/material/Divider'; import IconButton from '@mui/material/IconButton'; import MenuIcon from '@mui/icons-material/Menu'; import ChevronLeftIcon from '@mui/icons-material/ChevronLeft'; import ChevronRightIcon from '@mui/icons-material/ChevronRight'; import ListItem from '@mui/material/ListItem'; import ListItemIcon from '@mui/material/ListItemIcon'; import ListItemText from '@mui/material/ListItemText'; import InboxIcon from '@mui/icons-material/MoveToInbox'; import MailIcon from '@mui/icons-material/Mail'; const drawerWidth = 240; const openedMixin = (theme: Theme): CSSObject => ({ width: drawerWidth, transition: theme.transitions.create('width', { easing: theme.transitions.easing.sharp, duration: theme.transitions.duration.enteringScreen, }), overflowX: 'hidden', }); const closedMixin = (theme: Theme): CSSObject => ({ transition: theme.transitions.create('width', { easing: theme.transitions.easing.sharp, duration: theme.transitions.duration.leavingScreen, }), overflowX: 'hidden', width: `calc(${theme.spacing(7)} + 1px)`, [theme.breakpoints.up('sm')]: { width: `calc(${theme.spacing(9)} + 1px)`, }, }); const DrawerHeader = styled('div')(({ theme }) => ({ display: 'flex', alignItems: 'center', justifyContent: 'flex-end', padding: theme.spacing(0, 1), // necessary for content to be below app bar ...theme.mixins.toolbar, })); interface AppBarProps extends MuiAppBarProps { open?: boolean; } const AppBar = styled(MuiAppBar, { shouldForwardProp: (prop) => prop !== 'open', })<AppBarProps>(({ theme, open }) => ({ zIndex: theme.zIndex.drawer + 1, transition: theme.transitions.create(['width', 'margin'], { easing: theme.transitions.easing.sharp, duration: theme.transitions.duration.leavingScreen, }), ...(open && { marginLeft: drawerWidth, width: `calc(100% - ${drawerWidth}px)`, transition: theme.transitions.create(['width', 'margin'], { easing: theme.transitions.easing.sharp, duration: theme.transitions.duration.enteringScreen, }), }), })); const Drawer = styled(MuiDrawer, { shouldForwardProp: (prop) => prop !== 'open' })( ({ theme, open }) => ({ width: drawerWidth, flexShrink: 0, whiteSpace: 'nowrap', boxSizing: 'border-box', ...(open && { ...openedMixin(theme), '& .MuiDrawer-paper': openedMixin(theme), }), ...(!open && { ...closedMixin(theme), '& .MuiDrawer-paper': closedMixin(theme), }), }), ); export default function MiniDrawer() { const theme = useTheme(); const [open, setOpen] = React.useState(false); const handleDrawerOpen = () => { setOpen(true); }; const handleDrawerClose = () => { setOpen(false); }; return ( <Box sx={{ display: 'flex' }}> <CssBaseline /> <AppBar position="fixed" open={open}> <Toolbar> <IconButton color="inherit" aria-label="open drawer" onClick={handleDrawerOpen} edge="start" sx={{ marginRight: '36px', ...(open && { display: 'none' }), }} > <MenuIcon /> </IconButton> <Typography variant="h6" noWrap component="div"> Mini variant drawer </Typography> </Toolbar> </AppBar> <Drawer variant="permanent" open={open}> <DrawerHeader> <IconButton onClick={handleDrawerClose}> {theme.direction === 'rtl' ? <ChevronRightIcon /> : <ChevronLeftIcon />} </IconButton> </DrawerHeader> <Divider /> <List> {['Inbox', 'Starred', 'Send email', 'Drafts'].map((text, index) => ( <ListItem button key={text}> <ListItemIcon> {index % 2 === 0 ? <InboxIcon /> : <MailIcon />} </ListItemIcon> <ListItemText primary={text} /> </ListItem> ))} </List> <Divider /> <List> {['All mail', 'Trash', 'Spam'].map((text, index) => ( <ListItem button key={text}> <ListItemIcon> {index % 2 === 0 ? <InboxIcon /> : <MailIcon />} </ListItemIcon> <ListItemText primary={text} /> </ListItem> ))} </List> </Drawer> <Box component="main" sx={{ flexGrow: 1, p: 3 }}> <DrawerHeader /> <Typography paragraph> Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Rhoncus dolor purus non enim praesent elementum facilisis leo vel. Risus at ultrices mi tempus imperdiet. Semper risus in hendrerit gravida rutrum quisque non tellus. Convallis convallis tellus id interdum velit laoreet id donec ultrices. Odio morbi quis commodo odio aenean sed adipiscing. Amet nisl suscipit adipiscing bibendum est ultricies integer quis. Cursus euismod quis viverra nibh cras. Metus vulputate eu scelerisque felis imperdiet proin fermentum leo. Mauris commodo quis imperdiet massa tincidunt. Cras tincidunt lobortis feugiat vivamus at augue. At augue eget arcu dictum varius duis at consectetur lorem. Velit sed ullamcorper morbi tincidunt. Lorem donec massa sapien faucibus et molestie ac. </Typography> <Typography paragraph> Consequat mauris nunc congue nisi vitae suscipit. Fringilla est ullamcorper eget nulla facilisi etiam dignissim diam. Pulvinar elementum integer enim neque volutpat ac tincidunt. Ornare suspendisse sed nisi lacus sed viverra tellus. Purus sit amet volutpat consequat mauris. Elementum eu facilisis sed odio morbi. Euismod lacinia at quis risus sed vulputate odio. Morbi tincidunt ornare massa eget egestas purus viverra accumsan in. In hendrerit gravida rutrum quisque non tellus orci ac. Pellentesque nec nam aliquam sem et tortor. Habitant morbi tristique senectus et. Adipiscing elit duis tristique sollicitudin nibh sit. Ornare aenean euismod elementum nisi quis eleifend. Commodo viverra maecenas accumsan lacus vel facilisis. Nulla posuere sollicitudin aliquam ultrices sagittis orci a. </Typography> </Box> </Box> ); }
docs/data/material/components/drawers/MiniDrawer.tsx
1
https://github.com/mui/material-ui/commit/1db2ae2530d6a5ccb26c63ad7e9bbe5926ab0ea5
[ 0.9780145883560181, 0.0517195463180542, 0.00016186620632652193, 0.0001771598617779091, 0.21832992136478424 ]
{ "id": 0, "code_window": [ "import Divider from '@mui/material/Divider';\n", "import IconButton from '@mui/material/IconButton';\n", "import MenuIcon from '@mui/icons-material/Menu';\n", "import ChevronLeftIcon from '@mui/icons-material/ChevronLeft';\n", "import ChevronRightIcon from '@mui/icons-material/ChevronRight';\n", "import ListItem from '@mui/material/ListItem';\n", "import ListItemIcon from '@mui/material/ListItemIcon';\n", "import ListItemText from '@mui/material/ListItemText';\n", "import InboxIcon from '@mui/icons-material/MoveToInbox';\n", "import MailIcon from '@mui/icons-material/Mail';\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "import ListItemButton from '@mui/material/ListItemButton';\n" ], "file_path": "docs/data/material/components/drawers/MiniDrawer.js", "type": "replace", "edit_start_line_idx": 14 }
"use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; var _createSvgIcon = _interopRequireDefault(require("./utils/createSvgIcon")); var _jsxRuntime = require("react/jsx-runtime"); var _default = (0, _createSvgIcon.default)( /*#__PURE__*/(0, _jsxRuntime.jsx)("path", { d: "M16 4h-2c-1.1 0-2 .9-2 2v5c0 1.1.9 2 2 2h2c1.1 0 2-.9 2-2V6c0-1.1-.9-2-2-2zm0 7h-2V6h2v5zm-6.5 5H18v2H9.49c-.88 0-1.66-.58-1.92-1.43L5 8V4h2v4l2.5 8zM8 19h10v2H8v-2z" }), 'FlightClassOutlined'); exports.default = _default;
packages/mui-icons-material/lib/FlightClassOutlined.js
0
https://github.com/mui/material-ui/commit/1db2ae2530d6a5ccb26c63ad7e9bbe5926ab0ea5
[ 0.00016870808030944318, 0.0001674044760875404, 0.00016610085731372237, 0.0001674044760875404, 0.0000013036114978604019 ]
{ "id": 0, "code_window": [ "import Divider from '@mui/material/Divider';\n", "import IconButton from '@mui/material/IconButton';\n", "import MenuIcon from '@mui/icons-material/Menu';\n", "import ChevronLeftIcon from '@mui/icons-material/ChevronLeft';\n", "import ChevronRightIcon from '@mui/icons-material/ChevronRight';\n", "import ListItem from '@mui/material/ListItem';\n", "import ListItemIcon from '@mui/material/ListItemIcon';\n", "import ListItemText from '@mui/material/ListItemText';\n", "import InboxIcon from '@mui/icons-material/MoveToInbox';\n", "import MailIcon from '@mui/icons-material/Mail';\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "import ListItemButton from '@mui/material/ListItemButton';\n" ], "file_path": "docs/data/material/components/drawers/MiniDrawer.js", "type": "replace", "edit_start_line_idx": 14 }
import createSvgIcon from './utils/createSvgIcon'; import { jsx as _jsx } from "react/jsx-runtime"; export default createSvgIcon( /*#__PURE__*/_jsx("path", { d: "M12 5C4.19 5 2 9.48 2 12c0 3.86 3.13 7 6.99 7h6.02C17.7 19 22 16.92 22 12c0 0 0-7-10-7zm0 2c7.64 0 7.99 4.51 8 5H4c0-.2.09-5 8-5zm2.86 10H9.14c-2.1 0-3.92-1.24-4.71-3h15.15c-.8 1.76-2.62 3-4.72 3z" }), 'HomeMiniOutlined');
packages/mui-icons-material/lib/esm/HomeMiniOutlined.js
0
https://github.com/mui/material-ui/commit/1db2ae2530d6a5ccb26c63ad7e9bbe5926ab0ea5
[ 0.00016904721269384027, 0.00016904721269384027, 0.00016904721269384027, 0.00016904721269384027, 0 ]
{ "id": 0, "code_window": [ "import Divider from '@mui/material/Divider';\n", "import IconButton from '@mui/material/IconButton';\n", "import MenuIcon from '@mui/icons-material/Menu';\n", "import ChevronLeftIcon from '@mui/icons-material/ChevronLeft';\n", "import ChevronRightIcon from '@mui/icons-material/ChevronRight';\n", "import ListItem from '@mui/material/ListItem';\n", "import ListItemIcon from '@mui/material/ListItemIcon';\n", "import ListItemText from '@mui/material/ListItemText';\n", "import InboxIcon from '@mui/icons-material/MoveToInbox';\n", "import MailIcon from '@mui/icons-material/Mail';\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "import ListItemButton from '@mui/material/ListItemButton';\n" ], "file_path": "docs/data/material/components/drawers/MiniDrawer.js", "type": "replace", "edit_start_line_idx": 14 }
import createSvgIcon from './utils/createSvgIcon'; import { jsx as _jsx } from "react/jsx-runtime"; export default createSvgIcon( /*#__PURE__*/_jsx("path", { d: "m12 4-1.41 1.41L16.17 11H4v2h12.17l-5.58 5.59L12 20l8-8-8-8z" }), 'ArrowForwardTwoTone');
packages/mui-icons-material/lib/esm/ArrowForwardTwoTone.js
0
https://github.com/mui/material-ui/commit/1db2ae2530d6a5ccb26c63ad7e9bbe5926ab0ea5
[ 0.00017093813221435994, 0.00017093813221435994, 0.00017093813221435994, 0.00017093813221435994, 0 ]
{ "id": 1, "code_window": [ " overflowX: 'hidden',\n", " width: `calc(${theme.spacing(7)} + 1px)`,\n", " [theme.breakpoints.up('sm')]: {\n", " width: `calc(${theme.spacing(9)} + 1px)`,\n", " },\n", "});\n", "\n", "const DrawerHeader = styled('div')(({ theme }) => ({\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " width: `calc(${theme.spacing(8)} + 1px)`,\n" ], "file_path": "docs/data/material/components/drawers/MiniDrawer.js", "type": "replace", "edit_start_line_idx": 39 }
import * as React from 'react'; import { styled, useTheme, Theme, CSSObject } from '@mui/material/styles'; import Box from '@mui/material/Box'; import MuiDrawer from '@mui/material/Drawer'; import MuiAppBar, { AppBarProps as MuiAppBarProps } from '@mui/material/AppBar'; import Toolbar from '@mui/material/Toolbar'; import List from '@mui/material/List'; import CssBaseline from '@mui/material/CssBaseline'; import Typography from '@mui/material/Typography'; import Divider from '@mui/material/Divider'; import IconButton from '@mui/material/IconButton'; import MenuIcon from '@mui/icons-material/Menu'; import ChevronLeftIcon from '@mui/icons-material/ChevronLeft'; import ChevronRightIcon from '@mui/icons-material/ChevronRight'; import ListItem from '@mui/material/ListItem'; import ListItemIcon from '@mui/material/ListItemIcon'; import ListItemText from '@mui/material/ListItemText'; import InboxIcon from '@mui/icons-material/MoveToInbox'; import MailIcon from '@mui/icons-material/Mail'; const drawerWidth = 240; const openedMixin = (theme: Theme): CSSObject => ({ width: drawerWidth, transition: theme.transitions.create('width', { easing: theme.transitions.easing.sharp, duration: theme.transitions.duration.enteringScreen, }), overflowX: 'hidden', }); const closedMixin = (theme: Theme): CSSObject => ({ transition: theme.transitions.create('width', { easing: theme.transitions.easing.sharp, duration: theme.transitions.duration.leavingScreen, }), overflowX: 'hidden', width: `calc(${theme.spacing(7)} + 1px)`, [theme.breakpoints.up('sm')]: { width: `calc(${theme.spacing(9)} + 1px)`, }, }); const DrawerHeader = styled('div')(({ theme }) => ({ display: 'flex', alignItems: 'center', justifyContent: 'flex-end', padding: theme.spacing(0, 1), // necessary for content to be below app bar ...theme.mixins.toolbar, })); interface AppBarProps extends MuiAppBarProps { open?: boolean; } const AppBar = styled(MuiAppBar, { shouldForwardProp: (prop) => prop !== 'open', })<AppBarProps>(({ theme, open }) => ({ zIndex: theme.zIndex.drawer + 1, transition: theme.transitions.create(['width', 'margin'], { easing: theme.transitions.easing.sharp, duration: theme.transitions.duration.leavingScreen, }), ...(open && { marginLeft: drawerWidth, width: `calc(100% - ${drawerWidth}px)`, transition: theme.transitions.create(['width', 'margin'], { easing: theme.transitions.easing.sharp, duration: theme.transitions.duration.enteringScreen, }), }), })); const Drawer = styled(MuiDrawer, { shouldForwardProp: (prop) => prop !== 'open' })( ({ theme, open }) => ({ width: drawerWidth, flexShrink: 0, whiteSpace: 'nowrap', boxSizing: 'border-box', ...(open && { ...openedMixin(theme), '& .MuiDrawer-paper': openedMixin(theme), }), ...(!open && { ...closedMixin(theme), '& .MuiDrawer-paper': closedMixin(theme), }), }), ); export default function MiniDrawer() { const theme = useTheme(); const [open, setOpen] = React.useState(false); const handleDrawerOpen = () => { setOpen(true); }; const handleDrawerClose = () => { setOpen(false); }; return ( <Box sx={{ display: 'flex' }}> <CssBaseline /> <AppBar position="fixed" open={open}> <Toolbar> <IconButton color="inherit" aria-label="open drawer" onClick={handleDrawerOpen} edge="start" sx={{ marginRight: '36px', ...(open && { display: 'none' }), }} > <MenuIcon /> </IconButton> <Typography variant="h6" noWrap component="div"> Mini variant drawer </Typography> </Toolbar> </AppBar> <Drawer variant="permanent" open={open}> <DrawerHeader> <IconButton onClick={handleDrawerClose}> {theme.direction === 'rtl' ? <ChevronRightIcon /> : <ChevronLeftIcon />} </IconButton> </DrawerHeader> <Divider /> <List> {['Inbox', 'Starred', 'Send email', 'Drafts'].map((text, index) => ( <ListItem button key={text}> <ListItemIcon> {index % 2 === 0 ? <InboxIcon /> : <MailIcon />} </ListItemIcon> <ListItemText primary={text} /> </ListItem> ))} </List> <Divider /> <List> {['All mail', 'Trash', 'Spam'].map((text, index) => ( <ListItem button key={text}> <ListItemIcon> {index % 2 === 0 ? <InboxIcon /> : <MailIcon />} </ListItemIcon> <ListItemText primary={text} /> </ListItem> ))} </List> </Drawer> <Box component="main" sx={{ flexGrow: 1, p: 3 }}> <DrawerHeader /> <Typography paragraph> Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Rhoncus dolor purus non enim praesent elementum facilisis leo vel. Risus at ultrices mi tempus imperdiet. Semper risus in hendrerit gravida rutrum quisque non tellus. Convallis convallis tellus id interdum velit laoreet id donec ultrices. Odio morbi quis commodo odio aenean sed adipiscing. Amet nisl suscipit adipiscing bibendum est ultricies integer quis. Cursus euismod quis viverra nibh cras. Metus vulputate eu scelerisque felis imperdiet proin fermentum leo. Mauris commodo quis imperdiet massa tincidunt. Cras tincidunt lobortis feugiat vivamus at augue. At augue eget arcu dictum varius duis at consectetur lorem. Velit sed ullamcorper morbi tincidunt. Lorem donec massa sapien faucibus et molestie ac. </Typography> <Typography paragraph> Consequat mauris nunc congue nisi vitae suscipit. Fringilla est ullamcorper eget nulla facilisi etiam dignissim diam. Pulvinar elementum integer enim neque volutpat ac tincidunt. Ornare suspendisse sed nisi lacus sed viverra tellus. Purus sit amet volutpat consequat mauris. Elementum eu facilisis sed odio morbi. Euismod lacinia at quis risus sed vulputate odio. Morbi tincidunt ornare massa eget egestas purus viverra accumsan in. In hendrerit gravida rutrum quisque non tellus orci ac. Pellentesque nec nam aliquam sem et tortor. Habitant morbi tristique senectus et. Adipiscing elit duis tristique sollicitudin nibh sit. Ornare aenean euismod elementum nisi quis eleifend. Commodo viverra maecenas accumsan lacus vel facilisis. Nulla posuere sollicitudin aliquam ultrices sagittis orci a. </Typography> </Box> </Box> ); }
docs/data/material/components/drawers/MiniDrawer.tsx
1
https://github.com/mui/material-ui/commit/1db2ae2530d6a5ccb26c63ad7e9bbe5926ab0ea5
[ 0.9971447587013245, 0.11361099779605865, 0.0001647343160584569, 0.016218530014157295, 0.2892378568649292 ]
{ "id": 1, "code_window": [ " overflowX: 'hidden',\n", " width: `calc(${theme.spacing(7)} + 1px)`,\n", " [theme.breakpoints.up('sm')]: {\n", " width: `calc(${theme.spacing(9)} + 1px)`,\n", " },\n", "});\n", "\n", "const DrawerHeader = styled('div')(({ theme }) => ({\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " width: `calc(${theme.spacing(8)} + 1px)`,\n" ], "file_path": "docs/data/material/components/drawers/MiniDrawer.js", "type": "replace", "edit_start_line_idx": 39 }
import * as React from 'react'; import TextField from '@mui/material/TextField'; import Stack from '@mui/material/Stack'; import AdapterDateFns from '@mui/lab/AdapterDateFns'; import LocalizationProvider from '@mui/lab/LocalizationProvider'; import TimePicker from '@mui/lab/TimePicker'; export default function TimeValidationTimePicker() { const [value, setValue] = React.useState(new Date('2020-01-01 12:00')); return ( <LocalizationProvider dateAdapter={AdapterDateFns}> <Stack spacing={3}> <TimePicker renderInput={(params) => <TextField {...params} />} value={value} label="min/max time" onChange={(newValue) => { setValue(newValue); }} minTime={new Date(0, 0, 0, 8)} maxTime={new Date(0, 0, 0, 18, 45)} /> <TimePicker renderInput={(params) => <TextField {...params} />} label="Disable odd hours" value={value} onChange={(newValue) => { setValue(newValue); }} shouldDisableTime={(timeValue, clockType) => { if (clockType === 'hours' && timeValue % 2) { return true; } return false; }} /> </Stack> </LocalizationProvider> ); }
docs/data/material/components/time-picker/TimeValidationTimePicker.js
0
https://github.com/mui/material-ui/commit/1db2ae2530d6a5ccb26c63ad7e9bbe5926ab0ea5
[ 0.00017495089559815824, 0.00017242712783627212, 0.00016990852600429207, 0.00017155797104351223, 0.000001886286327135167 ]
{ "id": 1, "code_window": [ " overflowX: 'hidden',\n", " width: `calc(${theme.spacing(7)} + 1px)`,\n", " [theme.breakpoints.up('sm')]: {\n", " width: `calc(${theme.spacing(9)} + 1px)`,\n", " },\n", "});\n", "\n", "const DrawerHeader = styled('div')(({ theme }) => ({\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " width: `calc(${theme.spacing(8)} + 1px)`,\n" ], "file_path": "docs/data/material/components/drawers/MiniDrawer.js", "type": "replace", "edit_start_line_idx": 39 }
"use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; var React = _interopRequireWildcard(require("react")); var _createSvgIcon = _interopRequireDefault(require("./utils/createSvgIcon")); var _jsxRuntime = require("react/jsx-runtime"); function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); } function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; } var _default = (0, _createSvgIcon.default)( /*#__PURE__*/(0, _jsxRuntime.jsxs)(React.Fragment, { children: [/*#__PURE__*/(0, _jsxRuntime.jsx)("path", { fillOpacity: ".3", d: "M2 22h20V2L2 22z" }), /*#__PURE__*/(0, _jsxRuntime.jsx)("path", { d: "M12 12L2 22h10V12z" })] }), 'SignalCellular1BarOutlined'); exports.default = _default;
packages/mui-icons-material/lib/SignalCellular1BarOutlined.js
0
https://github.com/mui/material-ui/commit/1db2ae2530d6a5ccb26c63ad7e9bbe5926ab0ea5
[ 0.0010199652751907706, 0.0004532393941190094, 0.0001676591346040368, 0.000172093728906475, 0.00040073980926536024 ]
{ "id": 1, "code_window": [ " overflowX: 'hidden',\n", " width: `calc(${theme.spacing(7)} + 1px)`,\n", " [theme.breakpoints.up('sm')]: {\n", " width: `calc(${theme.spacing(9)} + 1px)`,\n", " },\n", "});\n", "\n", "const DrawerHeader = styled('div')(({ theme }) => ({\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " width: `calc(${theme.spacing(8)} + 1px)`,\n" ], "file_path": "docs/data/material/components/drawers/MiniDrawer.js", "type": "replace", "edit_start_line_idx": 39 }
import * as React from 'react'; import Timeline from '@mui/lab/Timeline'; import TimelineItem from '@mui/lab/TimelineItem'; import TimelineSeparator from '@mui/lab/TimelineSeparator'; import TimelineConnector from '@mui/lab/TimelineConnector'; import TimelineContent from '@mui/lab/TimelineContent'; import TimelineOppositeContent from '@mui/lab/TimelineOppositeContent'; import TimelineDot from '@mui/lab/TimelineDot'; import FastfoodIcon from '@mui/icons-material/Fastfood'; import LaptopMacIcon from '@mui/icons-material/LaptopMac'; import HotelIcon from '@mui/icons-material/Hotel'; import RepeatIcon from '@mui/icons-material/Repeat'; import Typography from '@mui/material/Typography'; export default function CustomizedTimeline() { return ( <Timeline position="alternate"> <TimelineItem> <TimelineOppositeContent sx={{ m: 'auto 0' }} align="right" variant="body2" color="text.secondary" > 9:30 am </TimelineOppositeContent> <TimelineSeparator> <TimelineConnector /> <TimelineDot> <FastfoodIcon /> </TimelineDot> <TimelineConnector /> </TimelineSeparator> <TimelineContent sx={{ py: '12px', px: 2 }}> <Typography variant="h6" component="span"> Eat </Typography> <Typography>Because you need strength</Typography> </TimelineContent> </TimelineItem> <TimelineItem> <TimelineOppositeContent sx={{ m: 'auto 0' }} variant="body2" color="text.secondary" > 10:00 am </TimelineOppositeContent> <TimelineSeparator> <TimelineConnector /> <TimelineDot color="primary"> <LaptopMacIcon /> </TimelineDot> <TimelineConnector /> </TimelineSeparator> <TimelineContent sx={{ py: '12px', px: 2 }}> <Typography variant="h6" component="span"> Code </Typography> <Typography>Because it&apos;s awesome!</Typography> </TimelineContent> </TimelineItem> <TimelineItem> <TimelineSeparator> <TimelineConnector /> <TimelineDot color="primary" variant="outlined"> <HotelIcon /> </TimelineDot> <TimelineConnector sx={{ bgcolor: 'secondary.main' }} /> </TimelineSeparator> <TimelineContent sx={{ py: '12px', px: 2 }}> <Typography variant="h6" component="span"> Sleep </Typography> <Typography>Because you need rest</Typography> </TimelineContent> </TimelineItem> <TimelineItem> <TimelineSeparator> <TimelineConnector sx={{ bgcolor: 'secondary.main' }} /> <TimelineDot color="secondary"> <RepeatIcon /> </TimelineDot> <TimelineConnector /> </TimelineSeparator> <TimelineContent sx={{ py: '12px', px: 2 }}> <Typography variant="h6" component="span"> Repeat </Typography> <Typography>Because this is the life you love!</Typography> </TimelineContent> </TimelineItem> </Timeline> ); }
docs/data/material/components/timeline/CustomizedTimeline.js
0
https://github.com/mui/material-ui/commit/1db2ae2530d6a5ccb26c63ad7e9bbe5926ab0ea5
[ 0.0001744147448334843, 0.00017160018614958972, 0.00016805800260044634, 0.00017184714670293033, 0.000001979499074877822 ]
{ "id": 2, "code_window": [ " aria-label=\"open drawer\"\n", " onClick={handleDrawerOpen}\n", " edge=\"start\"\n", " sx={{\n", " marginRight: '36px',\n", " ...(open && { display: 'none' }),\n", " }}\n", " >\n", " <MenuIcon />\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " marginRight: 5,\n" ], "file_path": "docs/data/material/components/drawers/MiniDrawer.js", "type": "replace", "edit_start_line_idx": 110 }
import * as React from 'react'; import { styled, useTheme, Theme, CSSObject } from '@mui/material/styles'; import Box from '@mui/material/Box'; import MuiDrawer from '@mui/material/Drawer'; import MuiAppBar, { AppBarProps as MuiAppBarProps } from '@mui/material/AppBar'; import Toolbar from '@mui/material/Toolbar'; import List from '@mui/material/List'; import CssBaseline from '@mui/material/CssBaseline'; import Typography from '@mui/material/Typography'; import Divider from '@mui/material/Divider'; import IconButton from '@mui/material/IconButton'; import MenuIcon from '@mui/icons-material/Menu'; import ChevronLeftIcon from '@mui/icons-material/ChevronLeft'; import ChevronRightIcon from '@mui/icons-material/ChevronRight'; import ListItem from '@mui/material/ListItem'; import ListItemIcon from '@mui/material/ListItemIcon'; import ListItemText from '@mui/material/ListItemText'; import InboxIcon from '@mui/icons-material/MoveToInbox'; import MailIcon from '@mui/icons-material/Mail'; const drawerWidth = 240; const openedMixin = (theme: Theme): CSSObject => ({ width: drawerWidth, transition: theme.transitions.create('width', { easing: theme.transitions.easing.sharp, duration: theme.transitions.duration.enteringScreen, }), overflowX: 'hidden', }); const closedMixin = (theme: Theme): CSSObject => ({ transition: theme.transitions.create('width', { easing: theme.transitions.easing.sharp, duration: theme.transitions.duration.leavingScreen, }), overflowX: 'hidden', width: `calc(${theme.spacing(7)} + 1px)`, [theme.breakpoints.up('sm')]: { width: `calc(${theme.spacing(9)} + 1px)`, }, }); const DrawerHeader = styled('div')(({ theme }) => ({ display: 'flex', alignItems: 'center', justifyContent: 'flex-end', padding: theme.spacing(0, 1), // necessary for content to be below app bar ...theme.mixins.toolbar, })); interface AppBarProps extends MuiAppBarProps { open?: boolean; } const AppBar = styled(MuiAppBar, { shouldForwardProp: (prop) => prop !== 'open', })<AppBarProps>(({ theme, open }) => ({ zIndex: theme.zIndex.drawer + 1, transition: theme.transitions.create(['width', 'margin'], { easing: theme.transitions.easing.sharp, duration: theme.transitions.duration.leavingScreen, }), ...(open && { marginLeft: drawerWidth, width: `calc(100% - ${drawerWidth}px)`, transition: theme.transitions.create(['width', 'margin'], { easing: theme.transitions.easing.sharp, duration: theme.transitions.duration.enteringScreen, }), }), })); const Drawer = styled(MuiDrawer, { shouldForwardProp: (prop) => prop !== 'open' })( ({ theme, open }) => ({ width: drawerWidth, flexShrink: 0, whiteSpace: 'nowrap', boxSizing: 'border-box', ...(open && { ...openedMixin(theme), '& .MuiDrawer-paper': openedMixin(theme), }), ...(!open && { ...closedMixin(theme), '& .MuiDrawer-paper': closedMixin(theme), }), }), ); export default function MiniDrawer() { const theme = useTheme(); const [open, setOpen] = React.useState(false); const handleDrawerOpen = () => { setOpen(true); }; const handleDrawerClose = () => { setOpen(false); }; return ( <Box sx={{ display: 'flex' }}> <CssBaseline /> <AppBar position="fixed" open={open}> <Toolbar> <IconButton color="inherit" aria-label="open drawer" onClick={handleDrawerOpen} edge="start" sx={{ marginRight: '36px', ...(open && { display: 'none' }), }} > <MenuIcon /> </IconButton> <Typography variant="h6" noWrap component="div"> Mini variant drawer </Typography> </Toolbar> </AppBar> <Drawer variant="permanent" open={open}> <DrawerHeader> <IconButton onClick={handleDrawerClose}> {theme.direction === 'rtl' ? <ChevronRightIcon /> : <ChevronLeftIcon />} </IconButton> </DrawerHeader> <Divider /> <List> {['Inbox', 'Starred', 'Send email', 'Drafts'].map((text, index) => ( <ListItem button key={text}> <ListItemIcon> {index % 2 === 0 ? <InboxIcon /> : <MailIcon />} </ListItemIcon> <ListItemText primary={text} /> </ListItem> ))} </List> <Divider /> <List> {['All mail', 'Trash', 'Spam'].map((text, index) => ( <ListItem button key={text}> <ListItemIcon> {index % 2 === 0 ? <InboxIcon /> : <MailIcon />} </ListItemIcon> <ListItemText primary={text} /> </ListItem> ))} </List> </Drawer> <Box component="main" sx={{ flexGrow: 1, p: 3 }}> <DrawerHeader /> <Typography paragraph> Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Rhoncus dolor purus non enim praesent elementum facilisis leo vel. Risus at ultrices mi tempus imperdiet. Semper risus in hendrerit gravida rutrum quisque non tellus. Convallis convallis tellus id interdum velit laoreet id donec ultrices. Odio morbi quis commodo odio aenean sed adipiscing. Amet nisl suscipit adipiscing bibendum est ultricies integer quis. Cursus euismod quis viverra nibh cras. Metus vulputate eu scelerisque felis imperdiet proin fermentum leo. Mauris commodo quis imperdiet massa tincidunt. Cras tincidunt lobortis feugiat vivamus at augue. At augue eget arcu dictum varius duis at consectetur lorem. Velit sed ullamcorper morbi tincidunt. Lorem donec massa sapien faucibus et molestie ac. </Typography> <Typography paragraph> Consequat mauris nunc congue nisi vitae suscipit. Fringilla est ullamcorper eget nulla facilisi etiam dignissim diam. Pulvinar elementum integer enim neque volutpat ac tincidunt. Ornare suspendisse sed nisi lacus sed viverra tellus. Purus sit amet volutpat consequat mauris. Elementum eu facilisis sed odio morbi. Euismod lacinia at quis risus sed vulputate odio. Morbi tincidunt ornare massa eget egestas purus viverra accumsan in. In hendrerit gravida rutrum quisque non tellus orci ac. Pellentesque nec nam aliquam sem et tortor. Habitant morbi tristique senectus et. Adipiscing elit duis tristique sollicitudin nibh sit. Ornare aenean euismod elementum nisi quis eleifend. Commodo viverra maecenas accumsan lacus vel facilisis. Nulla posuere sollicitudin aliquam ultrices sagittis orci a. </Typography> </Box> </Box> ); }
docs/data/material/components/drawers/MiniDrawer.tsx
1
https://github.com/mui/material-ui/commit/1db2ae2530d6a5ccb26c63ad7e9bbe5926ab0ea5
[ 0.9961923360824585, 0.05336208641529083, 0.00016492385475430638, 0.00017335046140942723, 0.22223569452762604 ]
{ "id": 2, "code_window": [ " aria-label=\"open drawer\"\n", " onClick={handleDrawerOpen}\n", " edge=\"start\"\n", " sx={{\n", " marginRight: '36px',\n", " ...(open && { display: 'none' }),\n", " }}\n", " >\n", " <MenuIcon />\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " marginRight: 5,\n" ], "file_path": "docs/data/material/components/drawers/MiniDrawer.js", "type": "replace", "edit_start_line_idx": 110 }
<svg xmlns="http://www.w3.org/2000/svg" enable-background="new 0 0 24 24" height="24" viewBox="0 0 24 24" width="24"><g><path d="M0,0h24v24H0V0z" fill="none"/></g><g><g><path d="M3,11h8V3H3V11z M5,5h4v4H5V5z"/><path d="M13,3v8h8V3H13z M19,9h-4V5h4V9z"/><path d="M3,21h8v-8H3V21z M5,15h4v4H5V15z"/><polygon points="18,13 16,13 16,16 13,16 13,18 16,18 16,21 18,21 18,18 21,18 21,16 18,16"/></g></g></svg>
packages/mui-icons-material/material-icons/dashboard_customize_outlined_24px.svg
0
https://github.com/mui/material-ui/commit/1db2ae2530d6a5ccb26c63ad7e9bbe5926ab0ea5
[ 0.0001750488590914756, 0.0001750488590914756, 0.0001750488590914756, 0.0001750488590914756, 0 ]
{ "id": 2, "code_window": [ " aria-label=\"open drawer\"\n", " onClick={handleDrawerOpen}\n", " edge=\"start\"\n", " sx={{\n", " marginRight: '36px',\n", " ...(open && { display: 'none' }),\n", " }}\n", " >\n", " <MenuIcon />\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " marginRight: 5,\n" ], "file_path": "docs/data/material/components/drawers/MiniDrawer.js", "type": "replace", "edit_start_line_idx": 110 }
import * as React from 'react'; import { Theme } from '@mui/material/styles'; import { SxProps } from '@mui/system'; import Box from '@mui/material/Box'; import Grid from '@mui/material/Grid'; import Container from '@mui/material/Container'; import Button from '../components/Button'; import Typography from '../components/Typography'; const item: SxProps<Theme> = { display: 'flex', flexDirection: 'column', alignItems: 'center', px: 5, }; const number = { fontSize: 24, fontFamily: 'default', color: 'secondary.main', fontWeight: 'medium', }; const image = { height: 55, my: 4, }; function ProductHowItWorks() { return ( <Box component="section" sx={{ display: 'flex', bgcolor: 'secondary.light', overflow: 'hidden' }} > <Container sx={{ mt: 10, mb: 15, position: 'relative', display: 'flex', flexDirection: 'column', alignItems: 'center', }} > <Box component="img" src="/static/themes/onepirate/productCurvyLines.png" alt="curvy lines" sx={{ pointerEvents: 'none', position: 'absolute', top: -180, opacity: 0.7, }} /> <Typography variant="h4" marked="center" component="h2" sx={{ mb: 14 }}> How it works </Typography> <div> <Grid container spacing={5}> <Grid item xs={12} md={4}> <Box sx={item}> <Box sx={number}>1.</Box> <Box component="img" src="/static/themes/onepirate/productHowItWorks1.svg" alt="suitcase" sx={image} /> <Typography variant="h5" align="center"> Appointment every Wednesday 9am. </Typography> </Box> </Grid> <Grid item xs={12} md={4}> <Box sx={item}> <Box sx={number}>2.</Box> <Box component="img" src="/static/themes/onepirate/productHowItWorks2.svg" alt="graph" sx={image} /> <Typography variant="h5" align="center"> First come, first served. Our offers are in limited quantities, so be quick. </Typography> </Box> </Grid> <Grid item xs={12} md={4}> <Box sx={item}> <Box sx={number}>3.</Box> <Box component="img" src="/static/themes/onepirate/productHowItWorks3.svg" alt="clock" sx={image} /> <Typography variant="h5" align="center"> {'New offers every week. New experiences, new surprises. '} {'Your Sundays will no longer be alike.'} </Typography> </Box> </Grid> </Grid> </div> <Button color="secondary" size="large" variant="contained" component="a" href="/premium-themes/onepirate/sign-up/" sx={{ mt: 8 }} > Get started </Button> </Container> </Box> ); } export default ProductHowItWorks;
docs/src/pages/premium-themes/onepirate/modules/views/ProductHowItWorks.tsx
0
https://github.com/mui/material-ui/commit/1db2ae2530d6a5ccb26c63ad7e9bbe5926ab0ea5
[ 0.00017547013703733683, 0.00017061676771845669, 0.00016415696882177144, 0.00017117102106567472, 0.000003017877816091641 ]
{ "id": 2, "code_window": [ " aria-label=\"open drawer\"\n", " onClick={handleDrawerOpen}\n", " edge=\"start\"\n", " sx={{\n", " marginRight: '36px',\n", " ...(open && { display: 'none' }),\n", " }}\n", " >\n", " <MenuIcon />\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " marginRight: 5,\n" ], "file_path": "docs/data/material/components/drawers/MiniDrawer.js", "type": "replace", "edit_start_line_idx": 110 }
"use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; var _createSvgIcon = _interopRequireDefault(require("./utils/createSvgIcon")); var _jsxRuntime = require("react/jsx-runtime"); var _default = (0, _createSvgIcon.default)( /*#__PURE__*/(0, _jsxRuntime.jsx)("path", { d: "m15.73 14.85-2.52 2.52c-2.83-1.44-5.15-3.75-6.59-6.59l2.53-2.53L8.54 3H3.03C2.45 13.18 10.82 21.55 21 20.97v-5.51l-5.27-.61zM18 9h-2.59l5.02-5.02-1.41-1.41L14 7.59V5h-2v6h6z" }), 'PhoneCallbackSharp'); exports.default = _default;
packages/mui-icons-material/lib/PhoneCallbackSharp.js
0
https://github.com/mui/material-ui/commit/1db2ae2530d6a5ccb26c63ad7e9bbe5926ab0ea5
[ 0.00016732566291466355, 0.00016687829338479787, 0.0001664309238549322, 0.00016687829338479787, 4.473695298656821e-7 ]
{ "id": 3, "code_window": [ " </DrawerHeader>\n", " <Divider />\n", " <List>\n", " {['Inbox', 'Starred', 'Send email', 'Drafts'].map((text, index) => (\n", " <ListItem button key={text}>\n", " <ListItemIcon>\n", " {index % 2 === 0 ? <InboxIcon /> : <MailIcon />}\n", " </ListItemIcon>\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep" ], "after_edit": [ " <ListItemButton\n", " key={text}\n", " sx={{\n", " minHeight: 48,\n", " justifyContent: open ? 'initial' : 'center',\n", " px: 2.5,\n", " }}\n", " >\n", " <ListItemIcon\n", " sx={{\n", " minWidth: 0,\n", " mr: open ? 3 : 'auto',\n", " justifyContent: 'center',\n", " }}\n", " >\n" ], "file_path": "docs/data/material/components/drawers/MiniDrawer.js", "type": "replace", "edit_start_line_idx": 130 }
import * as React from 'react'; import { styled, useTheme, Theme, CSSObject } from '@mui/material/styles'; import Box from '@mui/material/Box'; import MuiDrawer from '@mui/material/Drawer'; import MuiAppBar, { AppBarProps as MuiAppBarProps } from '@mui/material/AppBar'; import Toolbar from '@mui/material/Toolbar'; import List from '@mui/material/List'; import CssBaseline from '@mui/material/CssBaseline'; import Typography from '@mui/material/Typography'; import Divider from '@mui/material/Divider'; import IconButton from '@mui/material/IconButton'; import MenuIcon from '@mui/icons-material/Menu'; import ChevronLeftIcon from '@mui/icons-material/ChevronLeft'; import ChevronRightIcon from '@mui/icons-material/ChevronRight'; import ListItem from '@mui/material/ListItem'; import ListItemIcon from '@mui/material/ListItemIcon'; import ListItemText from '@mui/material/ListItemText'; import InboxIcon from '@mui/icons-material/MoveToInbox'; import MailIcon from '@mui/icons-material/Mail'; const drawerWidth = 240; const openedMixin = (theme: Theme): CSSObject => ({ width: drawerWidth, transition: theme.transitions.create('width', { easing: theme.transitions.easing.sharp, duration: theme.transitions.duration.enteringScreen, }), overflowX: 'hidden', }); const closedMixin = (theme: Theme): CSSObject => ({ transition: theme.transitions.create('width', { easing: theme.transitions.easing.sharp, duration: theme.transitions.duration.leavingScreen, }), overflowX: 'hidden', width: `calc(${theme.spacing(7)} + 1px)`, [theme.breakpoints.up('sm')]: { width: `calc(${theme.spacing(9)} + 1px)`, }, }); const DrawerHeader = styled('div')(({ theme }) => ({ display: 'flex', alignItems: 'center', justifyContent: 'flex-end', padding: theme.spacing(0, 1), // necessary for content to be below app bar ...theme.mixins.toolbar, })); interface AppBarProps extends MuiAppBarProps { open?: boolean; } const AppBar = styled(MuiAppBar, { shouldForwardProp: (prop) => prop !== 'open', })<AppBarProps>(({ theme, open }) => ({ zIndex: theme.zIndex.drawer + 1, transition: theme.transitions.create(['width', 'margin'], { easing: theme.transitions.easing.sharp, duration: theme.transitions.duration.leavingScreen, }), ...(open && { marginLeft: drawerWidth, width: `calc(100% - ${drawerWidth}px)`, transition: theme.transitions.create(['width', 'margin'], { easing: theme.transitions.easing.sharp, duration: theme.transitions.duration.enteringScreen, }), }), })); const Drawer = styled(MuiDrawer, { shouldForwardProp: (prop) => prop !== 'open' })( ({ theme, open }) => ({ width: drawerWidth, flexShrink: 0, whiteSpace: 'nowrap', boxSizing: 'border-box', ...(open && { ...openedMixin(theme), '& .MuiDrawer-paper': openedMixin(theme), }), ...(!open && { ...closedMixin(theme), '& .MuiDrawer-paper': closedMixin(theme), }), }), ); export default function MiniDrawer() { const theme = useTheme(); const [open, setOpen] = React.useState(false); const handleDrawerOpen = () => { setOpen(true); }; const handleDrawerClose = () => { setOpen(false); }; return ( <Box sx={{ display: 'flex' }}> <CssBaseline /> <AppBar position="fixed" open={open}> <Toolbar> <IconButton color="inherit" aria-label="open drawer" onClick={handleDrawerOpen} edge="start" sx={{ marginRight: '36px', ...(open && { display: 'none' }), }} > <MenuIcon /> </IconButton> <Typography variant="h6" noWrap component="div"> Mini variant drawer </Typography> </Toolbar> </AppBar> <Drawer variant="permanent" open={open}> <DrawerHeader> <IconButton onClick={handleDrawerClose}> {theme.direction === 'rtl' ? <ChevronRightIcon /> : <ChevronLeftIcon />} </IconButton> </DrawerHeader> <Divider /> <List> {['Inbox', 'Starred', 'Send email', 'Drafts'].map((text, index) => ( <ListItem button key={text}> <ListItemIcon> {index % 2 === 0 ? <InboxIcon /> : <MailIcon />} </ListItemIcon> <ListItemText primary={text} /> </ListItem> ))} </List> <Divider /> <List> {['All mail', 'Trash', 'Spam'].map((text, index) => ( <ListItem button key={text}> <ListItemIcon> {index % 2 === 0 ? <InboxIcon /> : <MailIcon />} </ListItemIcon> <ListItemText primary={text} /> </ListItem> ))} </List> </Drawer> <Box component="main" sx={{ flexGrow: 1, p: 3 }}> <DrawerHeader /> <Typography paragraph> Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Rhoncus dolor purus non enim praesent elementum facilisis leo vel. Risus at ultrices mi tempus imperdiet. Semper risus in hendrerit gravida rutrum quisque non tellus. Convallis convallis tellus id interdum velit laoreet id donec ultrices. Odio morbi quis commodo odio aenean sed adipiscing. Amet nisl suscipit adipiscing bibendum est ultricies integer quis. Cursus euismod quis viverra nibh cras. Metus vulputate eu scelerisque felis imperdiet proin fermentum leo. Mauris commodo quis imperdiet massa tincidunt. Cras tincidunt lobortis feugiat vivamus at augue. At augue eget arcu dictum varius duis at consectetur lorem. Velit sed ullamcorper morbi tincidunt. Lorem donec massa sapien faucibus et molestie ac. </Typography> <Typography paragraph> Consequat mauris nunc congue nisi vitae suscipit. Fringilla est ullamcorper eget nulla facilisi etiam dignissim diam. Pulvinar elementum integer enim neque volutpat ac tincidunt. Ornare suspendisse sed nisi lacus sed viverra tellus. Purus sit amet volutpat consequat mauris. Elementum eu facilisis sed odio morbi. Euismod lacinia at quis risus sed vulputate odio. Morbi tincidunt ornare massa eget egestas purus viverra accumsan in. In hendrerit gravida rutrum quisque non tellus orci ac. Pellentesque nec nam aliquam sem et tortor. Habitant morbi tristique senectus et. Adipiscing elit duis tristique sollicitudin nibh sit. Ornare aenean euismod elementum nisi quis eleifend. Commodo viverra maecenas accumsan lacus vel facilisis. Nulla posuere sollicitudin aliquam ultrices sagittis orci a. </Typography> </Box> </Box> ); }
docs/data/material/components/drawers/MiniDrawer.tsx
1
https://github.com/mui/material-ui/commit/1db2ae2530d6a5ccb26c63ad7e9bbe5926ab0ea5
[ 0.9973767995834351, 0.05865292623639107, 0.00016419720486737788, 0.00018177373567596078, 0.2225048691034317 ]
{ "id": 3, "code_window": [ " </DrawerHeader>\n", " <Divider />\n", " <List>\n", " {['Inbox', 'Starred', 'Send email', 'Drafts'].map((text, index) => (\n", " <ListItem button key={text}>\n", " <ListItemIcon>\n", " {index % 2 === 0 ? <InboxIcon /> : <MailIcon />}\n", " </ListItemIcon>\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep" ], "after_edit": [ " <ListItemButton\n", " key={text}\n", " sx={{\n", " minHeight: 48,\n", " justifyContent: open ? 'initial' : 'center',\n", " px: 2.5,\n", " }}\n", " >\n", " <ListItemIcon\n", " sx={{\n", " minWidth: 0,\n", " mr: open ? 3 : 'auto',\n", " justifyContent: 'center',\n", " }}\n", " >\n" ], "file_path": "docs/data/material/components/drawers/MiniDrawer.js", "type": "replace", "edit_start_line_idx": 130 }
"use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; var _createSvgIcon = _interopRequireDefault(require("./utils/createSvgIcon")); var _jsxRuntime = require("react/jsx-runtime"); var _default = (0, _createSvgIcon.default)( /*#__PURE__*/(0, _jsxRuntime.jsx)("path", { d: "M15.6 10.79c.97-.67 1.65-1.77 1.65-2.79 0-2.26-1.75-4-4-4H8c-.55 0-1 .45-1 1v12c0 .55.45 1 1 1h5.78c2.07 0 3.96-1.69 3.97-3.77.01-1.53-.85-2.84-2.15-3.44zM10 6.5h3c.83 0 1.5.67 1.5 1.5s-.67 1.5-1.5 1.5h-3v-3zm3.5 9H10v-3h3.5c.83 0 1.5.67 1.5 1.5s-.67 1.5-1.5 1.5z" }), 'FormatBoldRounded'); exports.default = _default;
packages/mui-icons-material/lib/FormatBoldRounded.js
0
https://github.com/mui/material-ui/commit/1db2ae2530d6a5ccb26c63ad7e9bbe5926ab0ea5
[ 0.00016782194143161178, 0.00016585533739998937, 0.00016388874792028219, 0.00016585533739998937, 0.0000019665967556647956 ]
{ "id": 3, "code_window": [ " </DrawerHeader>\n", " <Divider />\n", " <List>\n", " {['Inbox', 'Starred', 'Send email', 'Drafts'].map((text, index) => (\n", " <ListItem button key={text}>\n", " <ListItemIcon>\n", " {index % 2 === 0 ? <InboxIcon /> : <MailIcon />}\n", " </ListItemIcon>\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep" ], "after_edit": [ " <ListItemButton\n", " key={text}\n", " sx={{\n", " minHeight: 48,\n", " justifyContent: open ? 'initial' : 'center',\n", " px: 2.5,\n", " }}\n", " >\n", " <ListItemIcon\n", " sx={{\n", " minWidth: 0,\n", " mr: open ? 3 : 'auto',\n", " justifyContent: 'center',\n", " }}\n", " >\n" ], "file_path": "docs/data/material/components/drawers/MiniDrawer.js", "type": "replace", "edit_start_line_idx": 130 }
"use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; var _createSvgIcon = _interopRequireDefault(require("./utils/createSvgIcon")); var _jsxRuntime = require("react/jsx-runtime"); var _default = (0, _createSvgIcon.default)([/*#__PURE__*/(0, _jsxRuntime.jsx)("path", { d: "M19 19V5L5 19h14zm-2-3.5V17h-5v-1.5h5z", opacity: ".3" }, "0"), /*#__PURE__*/(0, _jsxRuntime.jsx)("path", { d: "M12 15.5h5V17h-5zM19 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-2zM5.5 7.5h2v-2H9v2h2V9H9v2H7.5V9h-2V7.5zM19 19H5L19 5v14z" }, "1")], 'IsoTwoTone'); exports.default = _default;
packages/mui-icons-material/lib/IsoTwoTone.js
0
https://github.com/mui/material-ui/commit/1db2ae2530d6a5ccb26c63ad7e9bbe5926ab0ea5
[ 0.0001713988749543205, 0.00017003672837745398, 0.00016782194143161178, 0.00017088939785026014, 0.0000015798491403984372 ]
{ "id": 3, "code_window": [ " </DrawerHeader>\n", " <Divider />\n", " <List>\n", " {['Inbox', 'Starred', 'Send email', 'Drafts'].map((text, index) => (\n", " <ListItem button key={text}>\n", " <ListItemIcon>\n", " {index % 2 === 0 ? <InboxIcon /> : <MailIcon />}\n", " </ListItemIcon>\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep" ], "after_edit": [ " <ListItemButton\n", " key={text}\n", " sx={{\n", " minHeight: 48,\n", " justifyContent: open ? 'initial' : 'center',\n", " px: 2.5,\n", " }}\n", " >\n", " <ListItemIcon\n", " sx={{\n", " minWidth: 0,\n", " mr: open ? 3 : 'auto',\n", " justifyContent: 'center',\n", " }}\n", " >\n" ], "file_path": "docs/data/material/components/drawers/MiniDrawer.js", "type": "replace", "edit_start_line_idx": 130 }
"use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; var _createSvgIcon = _interopRequireDefault(require("./utils/createSvgIcon")); var _jsxRuntime = require("react/jsx-runtime"); var _default = (0, _createSvgIcon.default)( /*#__PURE__*/(0, _jsxRuntime.jsx)("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-2zm-8.75 10.5H10v.75c0 .41-.34.75-.75.75s-.75-.34-.75-.75v-.75h-2c-.55 0-1-.45-1-1V9.75c0-.41.34-.75.75-.75s.75.34.75.75V12h1.5V9.75c0-.41.34-.75.75-.75s.75.34.75.75V12h.25c.41 0 .75.34.75.75s-.34.75-.75.75zm4.84 1.5c-.22 0-.42-.1-.55-.27L13 12.75v1.55c0 .39-.31.7-.7.7h-.1c-.39 0-.7-.31-.7-.7V9.7c0-.39.31-.7.7-.7h.09c.4 0 .71.31.71.7v1.55l1.54-1.98c.13-.17.34-.27.55-.27.58 0 .91.66.56 1.12L14.25 12l1.41 1.88c.34.46.01 1.12-.57 1.12zm3.41-2.5h-1v1c0 .28-.22.5-.5.5s-.5-.22-.5-.5v-1h-1c-.28 0-.5-.22-.5-.5s.22-.5.5-.5h1v-1c0-.28.22-.5.5-.5s.5.22.5.5v1h1c.28 0 .5.22.5.5s-.22.5-.5.5z" }), 'FourKPlusRounded'); exports.default = _default;
packages/mui-icons-material/lib/FourKPlusRounded.js
0
https://github.com/mui/material-ui/commit/1db2ae2530d6a5ccb26c63ad7e9bbe5926ab0ea5
[ 0.0001722056622384116, 0.0001700138091109693, 0.00016782194143161178, 0.0001700138091109693, 0.0000021918604033999145 ]
{ "id": 4, "code_window": [ " {index % 2 === 0 ? <InboxIcon /> : <MailIcon />}\n", " </ListItemIcon>\n", " <ListItemText primary={text} />\n", " </ListItem>\n", " ))}\n", " </List>\n", " <Divider />\n", " <List>\n" ], "labels": [ "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " <ListItemText primary={text} sx={{ opacity: open ? 1 : 0 }} />\n", " </ListItemButton>\n" ], "file_path": "docs/data/material/components/drawers/MiniDrawer.js", "type": "replace", "edit_start_line_idx": 134 }
import * as React from 'react'; import { styled, useTheme } from '@mui/material/styles'; import Box from '@mui/material/Box'; import MuiDrawer from '@mui/material/Drawer'; import MuiAppBar from '@mui/material/AppBar'; import Toolbar from '@mui/material/Toolbar'; import List from '@mui/material/List'; import CssBaseline from '@mui/material/CssBaseline'; import Typography from '@mui/material/Typography'; import Divider from '@mui/material/Divider'; import IconButton from '@mui/material/IconButton'; import MenuIcon from '@mui/icons-material/Menu'; import ChevronLeftIcon from '@mui/icons-material/ChevronLeft'; import ChevronRightIcon from '@mui/icons-material/ChevronRight'; import ListItem from '@mui/material/ListItem'; import ListItemIcon from '@mui/material/ListItemIcon'; import ListItemText from '@mui/material/ListItemText'; import InboxIcon from '@mui/icons-material/MoveToInbox'; import MailIcon from '@mui/icons-material/Mail'; const drawerWidth = 240; const openedMixin = (theme) => ({ width: drawerWidth, transition: theme.transitions.create('width', { easing: theme.transitions.easing.sharp, duration: theme.transitions.duration.enteringScreen, }), overflowX: 'hidden', }); const closedMixin = (theme) => ({ transition: theme.transitions.create('width', { easing: theme.transitions.easing.sharp, duration: theme.transitions.duration.leavingScreen, }), overflowX: 'hidden', width: `calc(${theme.spacing(7)} + 1px)`, [theme.breakpoints.up('sm')]: { width: `calc(${theme.spacing(9)} + 1px)`, }, }); const DrawerHeader = styled('div')(({ theme }) => ({ display: 'flex', alignItems: 'center', justifyContent: 'flex-end', padding: theme.spacing(0, 1), // necessary for content to be below app bar ...theme.mixins.toolbar, })); const AppBar = styled(MuiAppBar, { shouldForwardProp: (prop) => prop !== 'open', })(({ theme, open }) => ({ zIndex: theme.zIndex.drawer + 1, transition: theme.transitions.create(['width', 'margin'], { easing: theme.transitions.easing.sharp, duration: theme.transitions.duration.leavingScreen, }), ...(open && { marginLeft: drawerWidth, width: `calc(100% - ${drawerWidth}px)`, transition: theme.transitions.create(['width', 'margin'], { easing: theme.transitions.easing.sharp, duration: theme.transitions.duration.enteringScreen, }), }), })); const Drawer = styled(MuiDrawer, { shouldForwardProp: (prop) => prop !== 'open' })( ({ theme, open }) => ({ width: drawerWidth, flexShrink: 0, whiteSpace: 'nowrap', boxSizing: 'border-box', ...(open && { ...openedMixin(theme), '& .MuiDrawer-paper': openedMixin(theme), }), ...(!open && { ...closedMixin(theme), '& .MuiDrawer-paper': closedMixin(theme), }), }), ); export default function MiniDrawer() { const theme = useTheme(); const [open, setOpen] = React.useState(false); const handleDrawerOpen = () => { setOpen(true); }; const handleDrawerClose = () => { setOpen(false); }; return ( <Box sx={{ display: 'flex' }}> <CssBaseline /> <AppBar position="fixed" open={open}> <Toolbar> <IconButton color="inherit" aria-label="open drawer" onClick={handleDrawerOpen} edge="start" sx={{ marginRight: '36px', ...(open && { display: 'none' }), }} > <MenuIcon /> </IconButton> <Typography variant="h6" noWrap component="div"> Mini variant drawer </Typography> </Toolbar> </AppBar> <Drawer variant="permanent" open={open}> <DrawerHeader> <IconButton onClick={handleDrawerClose}> {theme.direction === 'rtl' ? <ChevronRightIcon /> : <ChevronLeftIcon />} </IconButton> </DrawerHeader> <Divider /> <List> {['Inbox', 'Starred', 'Send email', 'Drafts'].map((text, index) => ( <ListItem button key={text}> <ListItemIcon> {index % 2 === 0 ? <InboxIcon /> : <MailIcon />} </ListItemIcon> <ListItemText primary={text} /> </ListItem> ))} </List> <Divider /> <List> {['All mail', 'Trash', 'Spam'].map((text, index) => ( <ListItem button key={text}> <ListItemIcon> {index % 2 === 0 ? <InboxIcon /> : <MailIcon />} </ListItemIcon> <ListItemText primary={text} /> </ListItem> ))} </List> </Drawer> <Box component="main" sx={{ flexGrow: 1, p: 3 }}> <DrawerHeader /> <Typography paragraph> Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Rhoncus dolor purus non enim praesent elementum facilisis leo vel. Risus at ultrices mi tempus imperdiet. Semper risus in hendrerit gravida rutrum quisque non tellus. Convallis convallis tellus id interdum velit laoreet id donec ultrices. Odio morbi quis commodo odio aenean sed adipiscing. Amet nisl suscipit adipiscing bibendum est ultricies integer quis. Cursus euismod quis viverra nibh cras. Metus vulputate eu scelerisque felis imperdiet proin fermentum leo. Mauris commodo quis imperdiet massa tincidunt. Cras tincidunt lobortis feugiat vivamus at augue. At augue eget arcu dictum varius duis at consectetur lorem. Velit sed ullamcorper morbi tincidunt. Lorem donec massa sapien faucibus et molestie ac. </Typography> <Typography paragraph> Consequat mauris nunc congue nisi vitae suscipit. Fringilla est ullamcorper eget nulla facilisi etiam dignissim diam. Pulvinar elementum integer enim neque volutpat ac tincidunt. Ornare suspendisse sed nisi lacus sed viverra tellus. Purus sit amet volutpat consequat mauris. Elementum eu facilisis sed odio morbi. Euismod lacinia at quis risus sed vulputate odio. Morbi tincidunt ornare massa eget egestas purus viverra accumsan in. In hendrerit gravida rutrum quisque non tellus orci ac. Pellentesque nec nam aliquam sem et tortor. Habitant morbi tristique senectus et. Adipiscing elit duis tristique sollicitudin nibh sit. Ornare aenean euismod elementum nisi quis eleifend. Commodo viverra maecenas accumsan lacus vel facilisis. Nulla posuere sollicitudin aliquam ultrices sagittis orci a. </Typography> </Box> </Box> ); }
docs/data/material/components/drawers/MiniDrawer.js
1
https://github.com/mui/material-ui/commit/1db2ae2530d6a5ccb26c63ad7e9bbe5926ab0ea5
[ 0.9937121868133545, 0.10314185172319412, 0.00016363624308723956, 0.00017116563685704023, 0.299533873796463 ]
{ "id": 4, "code_window": [ " {index % 2 === 0 ? <InboxIcon /> : <MailIcon />}\n", " </ListItemIcon>\n", " <ListItemText primary={text} />\n", " </ListItem>\n", " ))}\n", " </List>\n", " <Divider />\n", " <List>\n" ], "labels": [ "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " <ListItemText primary={text} sx={{ opacity: open ? 1 : 0 }} />\n", " </ListItemButton>\n" ], "file_path": "docs/data/material/components/drawers/MiniDrawer.js", "type": "replace", "edit_start_line_idx": 134 }
import createSvgIcon from './utils/createSvgIcon'; import { jsx as _jsx } from "react/jsx-runtime"; export default createSvgIcon( /*#__PURE__*/_jsx("path", { d: "M20 8h-3V4H3c-1.1 0-2 .9-2 2v11h2c0 1.66 1.34 3 3 3s3-1.34 3-3h6c0 1.66 1.34 3 3 3s3-1.34 3-3h2v-5l-3-4zM6 18.5c-.83 0-1.5-.67-1.5-1.5s.67-1.5 1.5-1.5 1.5.67 1.5 1.5-.67 1.5-1.5 1.5zm13.5-9 1.96 2.5H17V9.5h2.5zm-1.5 9c-.83 0-1.5-.67-1.5-1.5s.67-1.5 1.5-1.5 1.5.67 1.5 1.5-.67 1.5-1.5 1.5z" }), 'LocalShipping');
packages/mui-icons-material/lib/esm/LocalShipping.js
0
https://github.com/mui/material-ui/commit/1db2ae2530d6a5ccb26c63ad7e9bbe5926ab0ea5
[ 0.00016527995467185974, 0.00016527995467185974, 0.00016527995467185974, 0.00016527995467185974, 0 ]
{ "id": 4, "code_window": [ " {index % 2 === 0 ? <InboxIcon /> : <MailIcon />}\n", " </ListItemIcon>\n", " <ListItemText primary={text} />\n", " </ListItem>\n", " ))}\n", " </List>\n", " <Divider />\n", " <List>\n" ], "labels": [ "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " <ListItemText primary={text} sx={{ opacity: open ? 1 : 0 }} />\n", " </ListItemButton>\n" ], "file_path": "docs/data/material/components/drawers/MiniDrawer.js", "type": "replace", "edit_start_line_idx": 134 }
import createSvgIcon from './utils/createSvgIcon'; import { jsx as _jsx } from "react/jsx-runtime"; export default createSvgIcon([/*#__PURE__*/_jsx("path", { d: "M14 7h-4c-1.1 0-2 .9-2 2v6h2v7h4v-7h2V9c0-1.1-.9-2-2-2z" }, "0"), /*#__PURE__*/_jsx("circle", { cx: "12", cy: "4", r: "2" }, "1")], 'ManTwoTone');
packages/mui-icons-material/lib/esm/ManTwoTone.js
0
https://github.com/mui/material-ui/commit/1db2ae2530d6a5ccb26c63ad7e9bbe5926ab0ea5
[ 0.00016671331832185388, 0.00016671331832185388, 0.00016671331832185388, 0.00016671331832185388, 0 ]
{ "id": 4, "code_window": [ " {index % 2 === 0 ? <InboxIcon /> : <MailIcon />}\n", " </ListItemIcon>\n", " <ListItemText primary={text} />\n", " </ListItem>\n", " ))}\n", " </List>\n", " <Divider />\n", " <List>\n" ], "labels": [ "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " <ListItemText primary={text} sx={{ opacity: open ? 1 : 0 }} />\n", " </ListItemButton>\n" ], "file_path": "docs/data/material/components/drawers/MiniDrawer.js", "type": "replace", "edit_start_line_idx": 134 }
--- product: material-ui title: Ícones Material components: Icon, SvgIcon materialDesign: https://material.io/design/iconography/system-icons.html packageName: '@mui/icons-material' githubLabel: 'ícones' --- # Ícones Material <p class="description">1,900+ React Material icons ready-to-use from the official website.</p> The following npm package, [@mui/icons-material](https://www.npmjs.com/package/@mui/icons-material), includes the 1,900+ official [Material icons](https://fonts.google.com/icons) converted to [`SvgIcon`](/api/svg-icon/) components. {{"component": "modules/components/ComponentLinkHeader.js"}} {{"demo": "SearchIcons.js", "hideToolbar": true, "bg": true}} ℹ️ A pesquisa suporta sinônimos. Try searching for "hamburger" or "logout".
docs/data/material/components/material-icons/material-icons-pt.md
0
https://github.com/mui/material-ui/commit/1db2ae2530d6a5ccb26c63ad7e9bbe5926ab0ea5
[ 0.00017431547166779637, 0.00017162358562927693, 0.00016727272304706275, 0.00017328254762105644, 0.0000031052863960212562 ]
{ "id": 5, "code_window": [ " <Divider />\n", " <List>\n", " {['All mail', 'Trash', 'Spam'].map((text, index) => (\n", " <ListItem button key={text}>\n", " <ListItemIcon>\n", " {index % 2 === 0 ? <InboxIcon /> : <MailIcon />}\n", " </ListItemIcon>\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "keep", "keep" ], "after_edit": [ " <ListItemButton\n", " key={text}\n", " sx={{\n", " minHeight: 48,\n", " justifyContent: open ? 'initial' : 'center',\n", " px: 2.5,\n", " }}\n", " >\n", " <ListItemIcon\n", " sx={{\n", " minWidth: 0,\n", " mr: open ? 3 : 'auto',\n", " justifyContent: 'center',\n", " }}\n", " >\n" ], "file_path": "docs/data/material/components/drawers/MiniDrawer.js", "type": "replace", "edit_start_line_idx": 141 }
import * as React from 'react'; import { styled, useTheme, Theme, CSSObject } from '@mui/material/styles'; import Box from '@mui/material/Box'; import MuiDrawer from '@mui/material/Drawer'; import MuiAppBar, { AppBarProps as MuiAppBarProps } from '@mui/material/AppBar'; import Toolbar from '@mui/material/Toolbar'; import List from '@mui/material/List'; import CssBaseline from '@mui/material/CssBaseline'; import Typography from '@mui/material/Typography'; import Divider from '@mui/material/Divider'; import IconButton from '@mui/material/IconButton'; import MenuIcon from '@mui/icons-material/Menu'; import ChevronLeftIcon from '@mui/icons-material/ChevronLeft'; import ChevronRightIcon from '@mui/icons-material/ChevronRight'; import ListItem from '@mui/material/ListItem'; import ListItemIcon from '@mui/material/ListItemIcon'; import ListItemText from '@mui/material/ListItemText'; import InboxIcon from '@mui/icons-material/MoveToInbox'; import MailIcon from '@mui/icons-material/Mail'; const drawerWidth = 240; const openedMixin = (theme: Theme): CSSObject => ({ width: drawerWidth, transition: theme.transitions.create('width', { easing: theme.transitions.easing.sharp, duration: theme.transitions.duration.enteringScreen, }), overflowX: 'hidden', }); const closedMixin = (theme: Theme): CSSObject => ({ transition: theme.transitions.create('width', { easing: theme.transitions.easing.sharp, duration: theme.transitions.duration.leavingScreen, }), overflowX: 'hidden', width: `calc(${theme.spacing(7)} + 1px)`, [theme.breakpoints.up('sm')]: { width: `calc(${theme.spacing(9)} + 1px)`, }, }); const DrawerHeader = styled('div')(({ theme }) => ({ display: 'flex', alignItems: 'center', justifyContent: 'flex-end', padding: theme.spacing(0, 1), // necessary for content to be below app bar ...theme.mixins.toolbar, })); interface AppBarProps extends MuiAppBarProps { open?: boolean; } const AppBar = styled(MuiAppBar, { shouldForwardProp: (prop) => prop !== 'open', })<AppBarProps>(({ theme, open }) => ({ zIndex: theme.zIndex.drawer + 1, transition: theme.transitions.create(['width', 'margin'], { easing: theme.transitions.easing.sharp, duration: theme.transitions.duration.leavingScreen, }), ...(open && { marginLeft: drawerWidth, width: `calc(100% - ${drawerWidth}px)`, transition: theme.transitions.create(['width', 'margin'], { easing: theme.transitions.easing.sharp, duration: theme.transitions.duration.enteringScreen, }), }), })); const Drawer = styled(MuiDrawer, { shouldForwardProp: (prop) => prop !== 'open' })( ({ theme, open }) => ({ width: drawerWidth, flexShrink: 0, whiteSpace: 'nowrap', boxSizing: 'border-box', ...(open && { ...openedMixin(theme), '& .MuiDrawer-paper': openedMixin(theme), }), ...(!open && { ...closedMixin(theme), '& .MuiDrawer-paper': closedMixin(theme), }), }), ); export default function MiniDrawer() { const theme = useTheme(); const [open, setOpen] = React.useState(false); const handleDrawerOpen = () => { setOpen(true); }; const handleDrawerClose = () => { setOpen(false); }; return ( <Box sx={{ display: 'flex' }}> <CssBaseline /> <AppBar position="fixed" open={open}> <Toolbar> <IconButton color="inherit" aria-label="open drawer" onClick={handleDrawerOpen} edge="start" sx={{ marginRight: '36px', ...(open && { display: 'none' }), }} > <MenuIcon /> </IconButton> <Typography variant="h6" noWrap component="div"> Mini variant drawer </Typography> </Toolbar> </AppBar> <Drawer variant="permanent" open={open}> <DrawerHeader> <IconButton onClick={handleDrawerClose}> {theme.direction === 'rtl' ? <ChevronRightIcon /> : <ChevronLeftIcon />} </IconButton> </DrawerHeader> <Divider /> <List> {['Inbox', 'Starred', 'Send email', 'Drafts'].map((text, index) => ( <ListItem button key={text}> <ListItemIcon> {index % 2 === 0 ? <InboxIcon /> : <MailIcon />} </ListItemIcon> <ListItemText primary={text} /> </ListItem> ))} </List> <Divider /> <List> {['All mail', 'Trash', 'Spam'].map((text, index) => ( <ListItem button key={text}> <ListItemIcon> {index % 2 === 0 ? <InboxIcon /> : <MailIcon />} </ListItemIcon> <ListItemText primary={text} /> </ListItem> ))} </List> </Drawer> <Box component="main" sx={{ flexGrow: 1, p: 3 }}> <DrawerHeader /> <Typography paragraph> Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Rhoncus dolor purus non enim praesent elementum facilisis leo vel. Risus at ultrices mi tempus imperdiet. Semper risus in hendrerit gravida rutrum quisque non tellus. Convallis convallis tellus id interdum velit laoreet id donec ultrices. Odio morbi quis commodo odio aenean sed adipiscing. Amet nisl suscipit adipiscing bibendum est ultricies integer quis. Cursus euismod quis viverra nibh cras. Metus vulputate eu scelerisque felis imperdiet proin fermentum leo. Mauris commodo quis imperdiet massa tincidunt. Cras tincidunt lobortis feugiat vivamus at augue. At augue eget arcu dictum varius duis at consectetur lorem. Velit sed ullamcorper morbi tincidunt. Lorem donec massa sapien faucibus et molestie ac. </Typography> <Typography paragraph> Consequat mauris nunc congue nisi vitae suscipit. Fringilla est ullamcorper eget nulla facilisi etiam dignissim diam. Pulvinar elementum integer enim neque volutpat ac tincidunt. Ornare suspendisse sed nisi lacus sed viverra tellus. Purus sit amet volutpat consequat mauris. Elementum eu facilisis sed odio morbi. Euismod lacinia at quis risus sed vulputate odio. Morbi tincidunt ornare massa eget egestas purus viverra accumsan in. In hendrerit gravida rutrum quisque non tellus orci ac. Pellentesque nec nam aliquam sem et tortor. Habitant morbi tristique senectus et. Adipiscing elit duis tristique sollicitudin nibh sit. Ornare aenean euismod elementum nisi quis eleifend. Commodo viverra maecenas accumsan lacus vel facilisis. Nulla posuere sollicitudin aliquam ultrices sagittis orci a. </Typography> </Box> </Box> ); }
docs/data/material/components/drawers/MiniDrawer.tsx
1
https://github.com/mui/material-ui/commit/1db2ae2530d6a5ccb26c63ad7e9bbe5926ab0ea5
[ 0.9934438467025757, 0.057079609483480453, 0.0001650069170864299, 0.00017137500981334597, 0.22157184779644012 ]
{ "id": 5, "code_window": [ " <Divider />\n", " <List>\n", " {['All mail', 'Trash', 'Spam'].map((text, index) => (\n", " <ListItem button key={text}>\n", " <ListItemIcon>\n", " {index % 2 === 0 ? <InboxIcon /> : <MailIcon />}\n", " </ListItemIcon>\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "keep", "keep" ], "after_edit": [ " <ListItemButton\n", " key={text}\n", " sx={{\n", " minHeight: 48,\n", " justifyContent: open ? 'initial' : 'center',\n", " px: 2.5,\n", " }}\n", " >\n", " <ListItemIcon\n", " sx={{\n", " minWidth: 0,\n", " mr: open ? 3 : 'auto',\n", " justifyContent: 'center',\n", " }}\n", " >\n" ], "file_path": "docs/data/material/components/drawers/MiniDrawer.js", "type": "replace", "edit_start_line_idx": 141 }
import createSvgIcon from './utils/createSvgIcon'; import { jsx as _jsx } from "react/jsx-runtime"; export default createSvgIcon( /*#__PURE__*/_jsx("path", { d: "M13 5.08c3.06.44 5.48 2.86 5.92 5.92h3.03c-.47-4.72-4.23-8.48-8.95-8.95v3.03zM18.92 13c-.44 3.06-2.86 5.48-5.92 5.92v3.03c4.72-.47 8.48-4.23 8.95-8.95h-3.03zM11 18.92c-3.39-.49-6-3.4-6-6.92s2.61-6.43 6-6.92V2.05c-5.05.5-9 4.76-9 9.95 0 5.19 3.95 9.45 9 9.95v-3.03z" }), 'DonutLargeSharp');
packages/mui-icons-material/lib/esm/DonutLargeSharp.js
0
https://github.com/mui/material-ui/commit/1db2ae2530d6a5ccb26c63ad7e9bbe5926ab0ea5
[ 0.00017059016681741923, 0.00017059016681741923, 0.00017059016681741923, 0.00017059016681741923, 0 ]
{ "id": 5, "code_window": [ " <Divider />\n", " <List>\n", " {['All mail', 'Trash', 'Spam'].map((text, index) => (\n", " <ListItem button key={text}>\n", " <ListItemIcon>\n", " {index % 2 === 0 ? <InboxIcon /> : <MailIcon />}\n", " </ListItemIcon>\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "keep", "keep" ], "after_edit": [ " <ListItemButton\n", " key={text}\n", " sx={{\n", " minHeight: 48,\n", " justifyContent: open ? 'initial' : 'center',\n", " px: 2.5,\n", " }}\n", " >\n", " <ListItemIcon\n", " sx={{\n", " minWidth: 0,\n", " mr: open ? 3 : 'auto',\n", " justifyContent: 'center',\n", " }}\n", " >\n" ], "file_path": "docs/data/material/components/drawers/MiniDrawer.js", "type": "replace", "edit_start_line_idx": 141 }
<svg xmlns="http://www.w3.org/2000/svg" enable-background="new 0 0 24 24" height="24" viewBox="0 0 24 24" width="24"><g><rect fill="none" height="24" width="24"/></g><g><path d="M18,5V3c0-1.1-0.9-2-2-2h-4c-1.1,0-2,0.9-2,2v2H7C5.9,5,5,5.9,5,7v9c0,1.1,0.9,2,2,2h14c1.1,0,2-0.9,2-2V7c0-1.1-0.9-2-2-2 H18z M16,5h-4V3h4V5z M2,9L2,9c-0.55,0-1,0.45-1,1v10c0,1.1,0.9,2,2,2h15c0.55,0,1-0.45,1-1v0c0-0.55-0.45-1-1-1H3V10 C3,9.45,2.55,9,2,9z"/></g></svg>
packages/mui-icons-material/material-icons/cases_rounded_24px.svg
0
https://github.com/mui/material-ui/commit/1db2ae2530d6a5ccb26c63ad7e9bbe5926ab0ea5
[ 0.0001706640177872032, 0.0001706640177872032, 0.0001706640177872032, 0.0001706640177872032, 0 ]
{ "id": 5, "code_window": [ " <Divider />\n", " <List>\n", " {['All mail', 'Trash', 'Spam'].map((text, index) => (\n", " <ListItem button key={text}>\n", " <ListItemIcon>\n", " {index % 2 === 0 ? <InboxIcon /> : <MailIcon />}\n", " </ListItemIcon>\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "keep", "keep" ], "after_edit": [ " <ListItemButton\n", " key={text}\n", " sx={{\n", " minHeight: 48,\n", " justifyContent: open ? 'initial' : 'center',\n", " px: 2.5,\n", " }}\n", " >\n", " <ListItemIcon\n", " sx={{\n", " minWidth: 0,\n", " mr: open ? 3 : 'auto',\n", " justifyContent: 'center',\n", " }}\n", " >\n" ], "file_path": "docs/data/material/components/drawers/MiniDrawer.js", "type": "replace", "edit_start_line_idx": 141 }
import createSvgIcon from './utils/createSvgIcon'; import { jsx as _jsx } from "react/jsx-runtime"; export default createSvgIcon( /*#__PURE__*/_jsx("path", { d: "M17 11v2h-1.17l4.51 4.51C21.39 15.93 22 14.04 22 12c0-5.52-4.48-10-10-10-2.04 0-3.93.61-5.51 1.66L13.83 11H17zM1.39 4.22l2.27 2.27C2.61 8.07 2 9.96 2 12c0 5.52 4.48 10 10 10 2.04 0 3.93-.61 5.51-1.66l2.27 2.27 1.41-1.41L2.81 2.81 1.39 4.22zM7 11h1.17l2 2H7v-2z" }), 'DoDisturbOff');
packages/mui-icons-material/lib/esm/DoDisturbOff.js
0
https://github.com/mui/material-ui/commit/1db2ae2530d6a5ccb26c63ad7e9bbe5926ab0ea5
[ 0.00016889511607587337, 0.00016889511607587337, 0.00016889511607587337, 0.00016889511607587337, 0 ]
{ "id": 6, "code_window": [ " {index % 2 === 0 ? <InboxIcon /> : <MailIcon />}\n", " </ListItemIcon>\n", " <ListItemText primary={text} />\n", " </ListItem>\n", " ))}\n", " </List>\n", " </Drawer>\n" ], "labels": [ "keep", "keep", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ " <ListItemText primary={text} sx={{ opacity: open ? 1 : 0 }} />\n", " </ListItemButton>\n" ], "file_path": "docs/data/material/components/drawers/MiniDrawer.js", "type": "replace", "edit_start_line_idx": 145 }
import * as React from 'react'; import { styled, useTheme, Theme, CSSObject } from '@mui/material/styles'; import Box from '@mui/material/Box'; import MuiDrawer from '@mui/material/Drawer'; import MuiAppBar, { AppBarProps as MuiAppBarProps } from '@mui/material/AppBar'; import Toolbar from '@mui/material/Toolbar'; import List from '@mui/material/List'; import CssBaseline from '@mui/material/CssBaseline'; import Typography from '@mui/material/Typography'; import Divider from '@mui/material/Divider'; import IconButton from '@mui/material/IconButton'; import MenuIcon from '@mui/icons-material/Menu'; import ChevronLeftIcon from '@mui/icons-material/ChevronLeft'; import ChevronRightIcon from '@mui/icons-material/ChevronRight'; import ListItem from '@mui/material/ListItem'; import ListItemIcon from '@mui/material/ListItemIcon'; import ListItemText from '@mui/material/ListItemText'; import InboxIcon from '@mui/icons-material/MoveToInbox'; import MailIcon from '@mui/icons-material/Mail'; const drawerWidth = 240; const openedMixin = (theme: Theme): CSSObject => ({ width: drawerWidth, transition: theme.transitions.create('width', { easing: theme.transitions.easing.sharp, duration: theme.transitions.duration.enteringScreen, }), overflowX: 'hidden', }); const closedMixin = (theme: Theme): CSSObject => ({ transition: theme.transitions.create('width', { easing: theme.transitions.easing.sharp, duration: theme.transitions.duration.leavingScreen, }), overflowX: 'hidden', width: `calc(${theme.spacing(7)} + 1px)`, [theme.breakpoints.up('sm')]: { width: `calc(${theme.spacing(9)} + 1px)`, }, }); const DrawerHeader = styled('div')(({ theme }) => ({ display: 'flex', alignItems: 'center', justifyContent: 'flex-end', padding: theme.spacing(0, 1), // necessary for content to be below app bar ...theme.mixins.toolbar, })); interface AppBarProps extends MuiAppBarProps { open?: boolean; } const AppBar = styled(MuiAppBar, { shouldForwardProp: (prop) => prop !== 'open', })<AppBarProps>(({ theme, open }) => ({ zIndex: theme.zIndex.drawer + 1, transition: theme.transitions.create(['width', 'margin'], { easing: theme.transitions.easing.sharp, duration: theme.transitions.duration.leavingScreen, }), ...(open && { marginLeft: drawerWidth, width: `calc(100% - ${drawerWidth}px)`, transition: theme.transitions.create(['width', 'margin'], { easing: theme.transitions.easing.sharp, duration: theme.transitions.duration.enteringScreen, }), }), })); const Drawer = styled(MuiDrawer, { shouldForwardProp: (prop) => prop !== 'open' })( ({ theme, open }) => ({ width: drawerWidth, flexShrink: 0, whiteSpace: 'nowrap', boxSizing: 'border-box', ...(open && { ...openedMixin(theme), '& .MuiDrawer-paper': openedMixin(theme), }), ...(!open && { ...closedMixin(theme), '& .MuiDrawer-paper': closedMixin(theme), }), }), ); export default function MiniDrawer() { const theme = useTheme(); const [open, setOpen] = React.useState(false); const handleDrawerOpen = () => { setOpen(true); }; const handleDrawerClose = () => { setOpen(false); }; return ( <Box sx={{ display: 'flex' }}> <CssBaseline /> <AppBar position="fixed" open={open}> <Toolbar> <IconButton color="inherit" aria-label="open drawer" onClick={handleDrawerOpen} edge="start" sx={{ marginRight: '36px', ...(open && { display: 'none' }), }} > <MenuIcon /> </IconButton> <Typography variant="h6" noWrap component="div"> Mini variant drawer </Typography> </Toolbar> </AppBar> <Drawer variant="permanent" open={open}> <DrawerHeader> <IconButton onClick={handleDrawerClose}> {theme.direction === 'rtl' ? <ChevronRightIcon /> : <ChevronLeftIcon />} </IconButton> </DrawerHeader> <Divider /> <List> {['Inbox', 'Starred', 'Send email', 'Drafts'].map((text, index) => ( <ListItem button key={text}> <ListItemIcon> {index % 2 === 0 ? <InboxIcon /> : <MailIcon />} </ListItemIcon> <ListItemText primary={text} /> </ListItem> ))} </List> <Divider /> <List> {['All mail', 'Trash', 'Spam'].map((text, index) => ( <ListItem button key={text}> <ListItemIcon> {index % 2 === 0 ? <InboxIcon /> : <MailIcon />} </ListItemIcon> <ListItemText primary={text} /> </ListItem> ))} </List> </Drawer> <Box component="main" sx={{ flexGrow: 1, p: 3 }}> <DrawerHeader /> <Typography paragraph> Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Rhoncus dolor purus non enim praesent elementum facilisis leo vel. Risus at ultrices mi tempus imperdiet. Semper risus in hendrerit gravida rutrum quisque non tellus. Convallis convallis tellus id interdum velit laoreet id donec ultrices. Odio morbi quis commodo odio aenean sed adipiscing. Amet nisl suscipit adipiscing bibendum est ultricies integer quis. Cursus euismod quis viverra nibh cras. Metus vulputate eu scelerisque felis imperdiet proin fermentum leo. Mauris commodo quis imperdiet massa tincidunt. Cras tincidunt lobortis feugiat vivamus at augue. At augue eget arcu dictum varius duis at consectetur lorem. Velit sed ullamcorper morbi tincidunt. Lorem donec massa sapien faucibus et molestie ac. </Typography> <Typography paragraph> Consequat mauris nunc congue nisi vitae suscipit. Fringilla est ullamcorper eget nulla facilisi etiam dignissim diam. Pulvinar elementum integer enim neque volutpat ac tincidunt. Ornare suspendisse sed nisi lacus sed viverra tellus. Purus sit amet volutpat consequat mauris. Elementum eu facilisis sed odio morbi. Euismod lacinia at quis risus sed vulputate odio. Morbi tincidunt ornare massa eget egestas purus viverra accumsan in. In hendrerit gravida rutrum quisque non tellus orci ac. Pellentesque nec nam aliquam sem et tortor. Habitant morbi tristique senectus et. Adipiscing elit duis tristique sollicitudin nibh sit. Ornare aenean euismod elementum nisi quis eleifend. Commodo viverra maecenas accumsan lacus vel facilisis. Nulla posuere sollicitudin aliquam ultrices sagittis orci a. </Typography> </Box> </Box> ); }
docs/data/material/components/drawers/MiniDrawer.tsx
1
https://github.com/mui/material-ui/commit/1db2ae2530d6a5ccb26c63ad7e9bbe5926ab0ea5
[ 0.9943570494651794, 0.10511403530836105, 0.00016367010539397597, 0.00029575766529887915, 0.30449822545051575 ]
{ "id": 6, "code_window": [ " {index % 2 === 0 ? <InboxIcon /> : <MailIcon />}\n", " </ListItemIcon>\n", " <ListItemText primary={text} />\n", " </ListItem>\n", " ))}\n", " </List>\n", " </Drawer>\n" ], "labels": [ "keep", "keep", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ " <ListItemText primary={text} sx={{ opacity: open ? 1 : 0 }} />\n", " </ListItemButton>\n" ], "file_path": "docs/data/material/components/drawers/MiniDrawer.js", "type": "replace", "edit_start_line_idx": 145 }
import createSvgIcon from './utils/createSvgIcon'; import { jsx as _jsx } from "react/jsx-runtime"; export default createSvgIcon( /*#__PURE__*/_jsx("path", { d: "M10.85 12.65h2.3L12 9l-1.15 3.65zM20 8.69V4h-4.69L12 .69 8.69 4H4v4.69L.69 12 4 15.31V20h4.69L12 23.31 15.31 20H20v-4.69L23.31 12 20 8.69zM14.3 16l-.7-2h-3.2l-.7 2H7.8L11 7h2l3.2 9h-1.9z" }), 'BrightnessAuto');
packages/mui-icons-material/lib/esm/BrightnessAuto.js
0
https://github.com/mui/material-ui/commit/1db2ae2530d6a5ccb26c63ad7e9bbe5926ab0ea5
[ 0.0001668039767537266, 0.0001668039767537266, 0.0001668039767537266, 0.0001668039767537266, 0 ]
{ "id": 6, "code_window": [ " {index % 2 === 0 ? <InboxIcon /> : <MailIcon />}\n", " </ListItemIcon>\n", " <ListItemText primary={text} />\n", " </ListItem>\n", " ))}\n", " </List>\n", " </Drawer>\n" ], "labels": [ "keep", "keep", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ " <ListItemText primary={text} sx={{ opacity: open ? 1 : 0 }} />\n", " </ListItemButton>\n" ], "file_path": "docs/data/material/components/drawers/MiniDrawer.js", "type": "replace", "edit_start_line_idx": 145 }
"use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; var _createSvgIcon = _interopRequireDefault(require("./utils/createSvgIcon")); var _jsxRuntime = require("react/jsx-runtime"); var _default = (0, _createSvgIcon.default)([/*#__PURE__*/(0, _jsxRuntime.jsx)("path", { d: "M10 21H4c-.55 0-1-.45-1-1v-6c0-.39.23-.64.36-.75L7 9.87V12h3v9z", opacity: ".3" }, "0"), /*#__PURE__*/(0, _jsxRuntime.jsx)("path", { d: "M20.75 16c.69 0 1.25-.56 1.25-1.25s-.56-1.25-1.25-1.25H12v-1h6.75c.69 0 1.25-.56 1.25-1.25 0-.67-.53-1.2-1.18-1.24L8.87 10l1.48-2.6c.09-.17.14-.34.14-.54 0-.26-.09-.5-.26-.7L9.12 5l-7.18 6.8c-.6.56-.94 1.35-.94 2.17V20c0 1.66 1.34 3 3 3h13.75c.69 0 1.25-.56 1.25-1.25s-.56-1.25-1.25-1.25H12v-1h7.75c.69 0 1.25-.56 1.25-1.25S20.44 17 19.75 17H12v-1h8.75zM10 21H4c-.55 0-1-.45-1-1v-6c0-.39.23-.64.36-.75L7 9.87V12h3v9zm5.65-16.14-.07-.07c-.57-.62-.82-1.41-.67-2.2L15 2h-1.89l-.06.43c-.2 1.36.27 2.71 1.3 3.72l.07.06c.57.62.82 1.41.67 2.2l-.11.59h1.91l.06-.43c.21-1.36-.27-2.71-1.3-3.71zm4 0-.07-.07c-.57-.62-.82-1.41-.67-2.2L19 2h-1.89l-.06.43c-.2 1.36.27 2.71 1.3 3.72l.07.06c.57.62.82 1.41.67 2.2l-.11.59h1.91l.06-.43c.21-1.36-.27-2.71-1.3-3.71z" }, "1")], 'DryTwoTone'); exports.default = _default;
packages/mui-icons-material/lib/DryTwoTone.js
0
https://github.com/mui/material-ui/commit/1db2ae2530d6a5ccb26c63ad7e9bbe5926ab0ea5
[ 0.0033710983116179705, 0.0012378020910546184, 0.00016984890680760145, 0.00017245888011530042, 0.0015084686456248164 ]
{ "id": 6, "code_window": [ " {index % 2 === 0 ? <InboxIcon /> : <MailIcon />}\n", " </ListItemIcon>\n", " <ListItemText primary={text} />\n", " </ListItem>\n", " ))}\n", " </List>\n", " </Drawer>\n" ], "labels": [ "keep", "keep", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ " <ListItemText primary={text} sx={{ opacity: open ? 1 : 0 }} />\n", " </ListItemButton>\n" ], "file_path": "docs/data/material/components/drawers/MiniDrawer.js", "type": "replace", "edit_start_line_idx": 145 }
"use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; var _createSvgIcon = _interopRequireDefault(require("./utils/createSvgIcon")); var _jsxRuntime = require("react/jsx-runtime"); var _default = (0, _createSvgIcon.default)( /*#__PURE__*/(0, _jsxRuntime.jsx)("path", { d: "M13.9 11c-.46-2.28-2.48-4-4.9-4-2.76 0-5 2.24-5 5s2.24 5 5 5c2.42 0 4.44-1.72 4.9-4h4.27l-1.59 1.59L18 16l4-4-4-4-1.41 1.41L18.17 11H13.9z" }), 'SwipeRightAltSharp'); exports.default = _default;
packages/mui-icons-material/lib/SwipeRightAltSharp.js
0
https://github.com/mui/material-ui/commit/1db2ae2530d6a5ccb26c63ad7e9bbe5926ab0ea5
[ 0.00017245905473828316, 0.0001684835006017238, 0.00016450796101707965, 0.0001684835006017238, 0.000003975546860601753 ]
{ "id": 7, "code_window": [ "import Divider from '@mui/material/Divider';\n", "import IconButton from '@mui/material/IconButton';\n", "import MenuIcon from '@mui/icons-material/Menu';\n", "import ChevronLeftIcon from '@mui/icons-material/ChevronLeft';\n", "import ChevronRightIcon from '@mui/icons-material/ChevronRight';\n", "import ListItem from '@mui/material/ListItem';\n", "import ListItemIcon from '@mui/material/ListItemIcon';\n", "import ListItemText from '@mui/material/ListItemText';\n", "import InboxIcon from '@mui/icons-material/MoveToInbox';\n", "import MailIcon from '@mui/icons-material/Mail';\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "import ListItemButton from '@mui/material/ListItemButton';\n" ], "file_path": "docs/data/material/components/drawers/MiniDrawer.tsx", "type": "replace", "edit_start_line_idx": 14 }
import * as React from 'react'; import { styled, useTheme } from '@mui/material/styles'; import Box from '@mui/material/Box'; import MuiDrawer from '@mui/material/Drawer'; import MuiAppBar from '@mui/material/AppBar'; import Toolbar from '@mui/material/Toolbar'; import List from '@mui/material/List'; import CssBaseline from '@mui/material/CssBaseline'; import Typography from '@mui/material/Typography'; import Divider from '@mui/material/Divider'; import IconButton from '@mui/material/IconButton'; import MenuIcon from '@mui/icons-material/Menu'; import ChevronLeftIcon from '@mui/icons-material/ChevronLeft'; import ChevronRightIcon from '@mui/icons-material/ChevronRight'; import ListItem from '@mui/material/ListItem'; import ListItemIcon from '@mui/material/ListItemIcon'; import ListItemText from '@mui/material/ListItemText'; import InboxIcon from '@mui/icons-material/MoveToInbox'; import MailIcon from '@mui/icons-material/Mail'; const drawerWidth = 240; const openedMixin = (theme) => ({ width: drawerWidth, transition: theme.transitions.create('width', { easing: theme.transitions.easing.sharp, duration: theme.transitions.duration.enteringScreen, }), overflowX: 'hidden', }); const closedMixin = (theme) => ({ transition: theme.transitions.create('width', { easing: theme.transitions.easing.sharp, duration: theme.transitions.duration.leavingScreen, }), overflowX: 'hidden', width: `calc(${theme.spacing(7)} + 1px)`, [theme.breakpoints.up('sm')]: { width: `calc(${theme.spacing(9)} + 1px)`, }, }); const DrawerHeader = styled('div')(({ theme }) => ({ display: 'flex', alignItems: 'center', justifyContent: 'flex-end', padding: theme.spacing(0, 1), // necessary for content to be below app bar ...theme.mixins.toolbar, })); const AppBar = styled(MuiAppBar, { shouldForwardProp: (prop) => prop !== 'open', })(({ theme, open }) => ({ zIndex: theme.zIndex.drawer + 1, transition: theme.transitions.create(['width', 'margin'], { easing: theme.transitions.easing.sharp, duration: theme.transitions.duration.leavingScreen, }), ...(open && { marginLeft: drawerWidth, width: `calc(100% - ${drawerWidth}px)`, transition: theme.transitions.create(['width', 'margin'], { easing: theme.transitions.easing.sharp, duration: theme.transitions.duration.enteringScreen, }), }), })); const Drawer = styled(MuiDrawer, { shouldForwardProp: (prop) => prop !== 'open' })( ({ theme, open }) => ({ width: drawerWidth, flexShrink: 0, whiteSpace: 'nowrap', boxSizing: 'border-box', ...(open && { ...openedMixin(theme), '& .MuiDrawer-paper': openedMixin(theme), }), ...(!open && { ...closedMixin(theme), '& .MuiDrawer-paper': closedMixin(theme), }), }), ); export default function MiniDrawer() { const theme = useTheme(); const [open, setOpen] = React.useState(false); const handleDrawerOpen = () => { setOpen(true); }; const handleDrawerClose = () => { setOpen(false); }; return ( <Box sx={{ display: 'flex' }}> <CssBaseline /> <AppBar position="fixed" open={open}> <Toolbar> <IconButton color="inherit" aria-label="open drawer" onClick={handleDrawerOpen} edge="start" sx={{ marginRight: '36px', ...(open && { display: 'none' }), }} > <MenuIcon /> </IconButton> <Typography variant="h6" noWrap component="div"> Mini variant drawer </Typography> </Toolbar> </AppBar> <Drawer variant="permanent" open={open}> <DrawerHeader> <IconButton onClick={handleDrawerClose}> {theme.direction === 'rtl' ? <ChevronRightIcon /> : <ChevronLeftIcon />} </IconButton> </DrawerHeader> <Divider /> <List> {['Inbox', 'Starred', 'Send email', 'Drafts'].map((text, index) => ( <ListItem button key={text}> <ListItemIcon> {index % 2 === 0 ? <InboxIcon /> : <MailIcon />} </ListItemIcon> <ListItemText primary={text} /> </ListItem> ))} </List> <Divider /> <List> {['All mail', 'Trash', 'Spam'].map((text, index) => ( <ListItem button key={text}> <ListItemIcon> {index % 2 === 0 ? <InboxIcon /> : <MailIcon />} </ListItemIcon> <ListItemText primary={text} /> </ListItem> ))} </List> </Drawer> <Box component="main" sx={{ flexGrow: 1, p: 3 }}> <DrawerHeader /> <Typography paragraph> Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Rhoncus dolor purus non enim praesent elementum facilisis leo vel. Risus at ultrices mi tempus imperdiet. Semper risus in hendrerit gravida rutrum quisque non tellus. Convallis convallis tellus id interdum velit laoreet id donec ultrices. Odio morbi quis commodo odio aenean sed adipiscing. Amet nisl suscipit adipiscing bibendum est ultricies integer quis. Cursus euismod quis viverra nibh cras. Metus vulputate eu scelerisque felis imperdiet proin fermentum leo. Mauris commodo quis imperdiet massa tincidunt. Cras tincidunt lobortis feugiat vivamus at augue. At augue eget arcu dictum varius duis at consectetur lorem. Velit sed ullamcorper morbi tincidunt. Lorem donec massa sapien faucibus et molestie ac. </Typography> <Typography paragraph> Consequat mauris nunc congue nisi vitae suscipit. Fringilla est ullamcorper eget nulla facilisi etiam dignissim diam. Pulvinar elementum integer enim neque volutpat ac tincidunt. Ornare suspendisse sed nisi lacus sed viverra tellus. Purus sit amet volutpat consequat mauris. Elementum eu facilisis sed odio morbi. Euismod lacinia at quis risus sed vulputate odio. Morbi tincidunt ornare massa eget egestas purus viverra accumsan in. In hendrerit gravida rutrum quisque non tellus orci ac. Pellentesque nec nam aliquam sem et tortor. Habitant morbi tristique senectus et. Adipiscing elit duis tristique sollicitudin nibh sit. Ornare aenean euismod elementum nisi quis eleifend. Commodo viverra maecenas accumsan lacus vel facilisis. Nulla posuere sollicitudin aliquam ultrices sagittis orci a. </Typography> </Box> </Box> ); }
docs/data/material/components/drawers/MiniDrawer.js
1
https://github.com/mui/material-ui/commit/1db2ae2530d6a5ccb26c63ad7e9bbe5926ab0ea5
[ 0.9743437767028809, 0.0515330471098423, 0.00016179152589756995, 0.00017496940563432872, 0.21750879287719727 ]
{ "id": 7, "code_window": [ "import Divider from '@mui/material/Divider';\n", "import IconButton from '@mui/material/IconButton';\n", "import MenuIcon from '@mui/icons-material/Menu';\n", "import ChevronLeftIcon from '@mui/icons-material/ChevronLeft';\n", "import ChevronRightIcon from '@mui/icons-material/ChevronRight';\n", "import ListItem from '@mui/material/ListItem';\n", "import ListItemIcon from '@mui/material/ListItemIcon';\n", "import ListItemText from '@mui/material/ListItemText';\n", "import InboxIcon from '@mui/icons-material/MoveToInbox';\n", "import MailIcon from '@mui/icons-material/Mail';\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "import ListItemButton from '@mui/material/ListItemButton';\n" ], "file_path": "docs/data/material/components/drawers/MiniDrawer.tsx", "type": "replace", "edit_start_line_idx": 14 }
import createSvgIcon from './utils/createSvgIcon'; import { jsx as _jsx } from "react/jsx-runtime"; export default createSvgIcon( /*#__PURE__*/_jsx("path", { d: "M21 12V6c0-1.1-.9-2-2-2h-1V3c0-.55-.45-1-1-1s-1 .45-1 1v1H8V3c0-.55-.45-1-1-1s-1 .45-1 1v1H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h7v-2H5V10h14v2h2zm-5.87 8c-.55 0-.91.56-.68 1.06C15.23 22.79 16.97 24 19 24c2.76 0 5-2.24 5-5s-2.24-5-5-5c-1.36 0-2.6.55-3.5 1.43v-.68c0-.41-.34-.75-.75-.75s-.75.34-.75.75V17c0 .55.45 1 1 1h2.25c.41 0 .75-.34.75-.75s-.34-.75-.75-.75h-.7c.63-.62 1.5-1 2.45-1 1.93 0 3.5 1.57 3.5 3.5s-1.57 3.5-3.5 3.5c-1.42 0-2.64-.85-3.19-2.06-.12-.27-.39-.44-.68-.44z" }), 'EventRepeatRounded');
packages/mui-icons-material/lib/esm/EventRepeatRounded.js
0
https://github.com/mui/material-ui/commit/1db2ae2530d6a5ccb26c63ad7e9bbe5926ab0ea5
[ 0.0002610802766866982, 0.0002610802766866982, 0.0002610802766866982, 0.0002610802766866982, 0 ]
{ "id": 7, "code_window": [ "import Divider from '@mui/material/Divider';\n", "import IconButton from '@mui/material/IconButton';\n", "import MenuIcon from '@mui/icons-material/Menu';\n", "import ChevronLeftIcon from '@mui/icons-material/ChevronLeft';\n", "import ChevronRightIcon from '@mui/icons-material/ChevronRight';\n", "import ListItem from '@mui/material/ListItem';\n", "import ListItemIcon from '@mui/material/ListItemIcon';\n", "import ListItemText from '@mui/material/ListItemText';\n", "import InboxIcon from '@mui/icons-material/MoveToInbox';\n", "import MailIcon from '@mui/icons-material/Mail';\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "import ListItemButton from '@mui/material/ListItemButton';\n" ], "file_path": "docs/data/material/components/drawers/MiniDrawer.tsx", "type": "replace", "edit_start_line_idx": 14 }
<svg xmlns="http://www.w3.org/2000/svg" height="24" viewBox="0 0 24 24" width="24"><path d="M0 0h24v24H0V0z" fill="none"/><path d="M19 6H5v12h14V6zm-8 5H9.5v-.5h-2v3h2V13H11v1c0 .55-.45 1-1 1H7c-.55 0-1-.45-1-1v-4c0-.55.45-1 1-1h3c.55 0 1 .45 1 1v1zm7 0h-1.5v-.5h-2v3h2V13H18v1c0 .55-.45 1-1 1h-3c-.55 0-1-.45-1-1v-4c0-.55.45-1 1-1h3c.55 0 1 .45 1 1v1z" opacity=".3"/><path d="M5 20h14c1.1 0 2-.9 2-2V6c0-1.1-.9-2-2-2H5c-1.11 0-2 .9-2 2v12c0 1.1.89 2 2 2zM5 6h14v12H5V6zm5 3H7c-.55 0-1 .45-1 1v4c0 .55.45 1 1 1h3c.55 0 1-.45 1-1v-1H9.5v.5h-2v-3h2v.5H11v-1c0-.55-.45-1-1-1zm7 0h-3c-.55 0-1 .45-1 1v4c0 .55.45 1 1 1h3c.55 0 1-.45 1-1v-1h-1.5v.5h-2v-3h2v.5H18v-1c0-.55-.45-1-1-1z"/></svg>
packages/mui-icons-material/material-icons/closed_caption_two_tone_24px.svg
0
https://github.com/mui/material-ui/commit/1db2ae2530d6a5ccb26c63ad7e9bbe5926ab0ea5
[ 0.0004033444565720856, 0.0004033444565720856, 0.0004033444565720856, 0.0004033444565720856, 0 ]
{ "id": 7, "code_window": [ "import Divider from '@mui/material/Divider';\n", "import IconButton from '@mui/material/IconButton';\n", "import MenuIcon from '@mui/icons-material/Menu';\n", "import ChevronLeftIcon from '@mui/icons-material/ChevronLeft';\n", "import ChevronRightIcon from '@mui/icons-material/ChevronRight';\n", "import ListItem from '@mui/material/ListItem';\n", "import ListItemIcon from '@mui/material/ListItemIcon';\n", "import ListItemText from '@mui/material/ListItemText';\n", "import InboxIcon from '@mui/icons-material/MoveToInbox';\n", "import MailIcon from '@mui/icons-material/Mail';\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "import ListItemButton from '@mui/material/ListItemButton';\n" ], "file_path": "docs/data/material/components/drawers/MiniDrawer.tsx", "type": "replace", "edit_start_line_idx": 14 }
import createSvgIcon from './utils/createSvgIcon'; import { jsx as _jsx } from "react/jsx-runtime"; export default createSvgIcon( /*#__PURE__*/_jsx("path", { d: "M6 5h4v14H6zm8 0h4v14h-4z" }), 'PauseTwoTone');
packages/mui-icons-material/lib/esm/PauseTwoTone.js
0
https://github.com/mui/material-ui/commit/1db2ae2530d6a5ccb26c63ad7e9bbe5926ab0ea5
[ 0.0001711010409053415, 0.0001711010409053415, 0.0001711010409053415, 0.0001711010409053415, 0 ]
{ "id": 8, "code_window": [ " duration: theme.transitions.duration.leavingScreen,\n", " }),\n", " overflowX: 'hidden',\n", " width: `calc(${theme.spacing(7)} + 1px)`,\n", " [theme.breakpoints.up('sm')]: {\n", " width: `calc(${theme.spacing(9)} + 1px)`,\n", " },\n", "});\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " width: `calc(${theme.spacing(8)} + 1px)`,\n" ], "file_path": "docs/data/material/components/drawers/MiniDrawer.tsx", "type": "replace", "edit_start_line_idx": 39 }
import * as React from 'react'; import { styled, useTheme, Theme, CSSObject } from '@mui/material/styles'; import Box from '@mui/material/Box'; import MuiDrawer from '@mui/material/Drawer'; import MuiAppBar, { AppBarProps as MuiAppBarProps } from '@mui/material/AppBar'; import Toolbar from '@mui/material/Toolbar'; import List from '@mui/material/List'; import CssBaseline from '@mui/material/CssBaseline'; import Typography from '@mui/material/Typography'; import Divider from '@mui/material/Divider'; import IconButton from '@mui/material/IconButton'; import MenuIcon from '@mui/icons-material/Menu'; import ChevronLeftIcon from '@mui/icons-material/ChevronLeft'; import ChevronRightIcon from '@mui/icons-material/ChevronRight'; import ListItem from '@mui/material/ListItem'; import ListItemIcon from '@mui/material/ListItemIcon'; import ListItemText from '@mui/material/ListItemText'; import InboxIcon from '@mui/icons-material/MoveToInbox'; import MailIcon from '@mui/icons-material/Mail'; const drawerWidth = 240; const openedMixin = (theme: Theme): CSSObject => ({ width: drawerWidth, transition: theme.transitions.create('width', { easing: theme.transitions.easing.sharp, duration: theme.transitions.duration.enteringScreen, }), overflowX: 'hidden', }); const closedMixin = (theme: Theme): CSSObject => ({ transition: theme.transitions.create('width', { easing: theme.transitions.easing.sharp, duration: theme.transitions.duration.leavingScreen, }), overflowX: 'hidden', width: `calc(${theme.spacing(7)} + 1px)`, [theme.breakpoints.up('sm')]: { width: `calc(${theme.spacing(9)} + 1px)`, }, }); const DrawerHeader = styled('div')(({ theme }) => ({ display: 'flex', alignItems: 'center', justifyContent: 'flex-end', padding: theme.spacing(0, 1), // necessary for content to be below app bar ...theme.mixins.toolbar, })); interface AppBarProps extends MuiAppBarProps { open?: boolean; } const AppBar = styled(MuiAppBar, { shouldForwardProp: (prop) => prop !== 'open', })<AppBarProps>(({ theme, open }) => ({ zIndex: theme.zIndex.drawer + 1, transition: theme.transitions.create(['width', 'margin'], { easing: theme.transitions.easing.sharp, duration: theme.transitions.duration.leavingScreen, }), ...(open && { marginLeft: drawerWidth, width: `calc(100% - ${drawerWidth}px)`, transition: theme.transitions.create(['width', 'margin'], { easing: theme.transitions.easing.sharp, duration: theme.transitions.duration.enteringScreen, }), }), })); const Drawer = styled(MuiDrawer, { shouldForwardProp: (prop) => prop !== 'open' })( ({ theme, open }) => ({ width: drawerWidth, flexShrink: 0, whiteSpace: 'nowrap', boxSizing: 'border-box', ...(open && { ...openedMixin(theme), '& .MuiDrawer-paper': openedMixin(theme), }), ...(!open && { ...closedMixin(theme), '& .MuiDrawer-paper': closedMixin(theme), }), }), ); export default function MiniDrawer() { const theme = useTheme(); const [open, setOpen] = React.useState(false); const handleDrawerOpen = () => { setOpen(true); }; const handleDrawerClose = () => { setOpen(false); }; return ( <Box sx={{ display: 'flex' }}> <CssBaseline /> <AppBar position="fixed" open={open}> <Toolbar> <IconButton color="inherit" aria-label="open drawer" onClick={handleDrawerOpen} edge="start" sx={{ marginRight: '36px', ...(open && { display: 'none' }), }} > <MenuIcon /> </IconButton> <Typography variant="h6" noWrap component="div"> Mini variant drawer </Typography> </Toolbar> </AppBar> <Drawer variant="permanent" open={open}> <DrawerHeader> <IconButton onClick={handleDrawerClose}> {theme.direction === 'rtl' ? <ChevronRightIcon /> : <ChevronLeftIcon />} </IconButton> </DrawerHeader> <Divider /> <List> {['Inbox', 'Starred', 'Send email', 'Drafts'].map((text, index) => ( <ListItem button key={text}> <ListItemIcon> {index % 2 === 0 ? <InboxIcon /> : <MailIcon />} </ListItemIcon> <ListItemText primary={text} /> </ListItem> ))} </List> <Divider /> <List> {['All mail', 'Trash', 'Spam'].map((text, index) => ( <ListItem button key={text}> <ListItemIcon> {index % 2 === 0 ? <InboxIcon /> : <MailIcon />} </ListItemIcon> <ListItemText primary={text} /> </ListItem> ))} </List> </Drawer> <Box component="main" sx={{ flexGrow: 1, p: 3 }}> <DrawerHeader /> <Typography paragraph> Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Rhoncus dolor purus non enim praesent elementum facilisis leo vel. Risus at ultrices mi tempus imperdiet. Semper risus in hendrerit gravida rutrum quisque non tellus. Convallis convallis tellus id interdum velit laoreet id donec ultrices. Odio morbi quis commodo odio aenean sed adipiscing. Amet nisl suscipit adipiscing bibendum est ultricies integer quis. Cursus euismod quis viverra nibh cras. Metus vulputate eu scelerisque felis imperdiet proin fermentum leo. Mauris commodo quis imperdiet massa tincidunt. Cras tincidunt lobortis feugiat vivamus at augue. At augue eget arcu dictum varius duis at consectetur lorem. Velit sed ullamcorper morbi tincidunt. Lorem donec massa sapien faucibus et molestie ac. </Typography> <Typography paragraph> Consequat mauris nunc congue nisi vitae suscipit. Fringilla est ullamcorper eget nulla facilisi etiam dignissim diam. Pulvinar elementum integer enim neque volutpat ac tincidunt. Ornare suspendisse sed nisi lacus sed viverra tellus. Purus sit amet volutpat consequat mauris. Elementum eu facilisis sed odio morbi. Euismod lacinia at quis risus sed vulputate odio. Morbi tincidunt ornare massa eget egestas purus viverra accumsan in. In hendrerit gravida rutrum quisque non tellus orci ac. Pellentesque nec nam aliquam sem et tortor. Habitant morbi tristique senectus et. Adipiscing elit duis tristique sollicitudin nibh sit. Ornare aenean euismod elementum nisi quis eleifend. Commodo viverra maecenas accumsan lacus vel facilisis. Nulla posuere sollicitudin aliquam ultrices sagittis orci a. </Typography> </Box> </Box> ); }
docs/data/material/components/drawers/MiniDrawer.tsx
1
https://github.com/mui/material-ui/commit/1db2ae2530d6a5ccb26c63ad7e9bbe5926ab0ea5
[ 0.9642894864082336, 0.05425148084759712, 0.00016775204858276993, 0.00017610270879231393, 0.2145826816558838 ]
{ "id": 8, "code_window": [ " duration: theme.transitions.duration.leavingScreen,\n", " }),\n", " overflowX: 'hidden',\n", " width: `calc(${theme.spacing(7)} + 1px)`,\n", " [theme.breakpoints.up('sm')]: {\n", " width: `calc(${theme.spacing(9)} + 1px)`,\n", " },\n", "});\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " width: `calc(${theme.spacing(8)} + 1px)`,\n" ], "file_path": "docs/data/material/components/drawers/MiniDrawer.tsx", "type": "replace", "edit_start_line_idx": 39 }
import * as React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <path d="M10 15l5.19-3L10 9v6m11.56-7.83c.13.47.22 1.1.28 1.9.07.8.1 1.49.1 2.09L22 12c0 2.19-.16 3.8-.44 4.83-.25.9-.83 1.48-1.73 1.73-.47.13-1.33.22-2.65.28-1.3.07-2.49.1-3.59.1L12 19c-4.19 0-6.8-.16-7.83-.44-.9-.25-1.48-.83-1.73-1.73-.13-.47-.22-1.1-.28-1.9-.07-.8-.1-1.49-.1-2.09L2 12c0-2.19.16-3.8.44-4.83.25-.9.83-1.48 1.73-1.73.47-.13 1.33-.22 2.65-.28 1.3-.07 2.49-.1 3.59-.1L12 5c4.19 0 6.8.16 7.83.44.9.25 1.48.83 1.73 1.73z" />, 'YouTube', );
packages/mui-icons-material/custom/YouTube.js
0
https://github.com/mui/material-ui/commit/1db2ae2530d6a5ccb26c63ad7e9bbe5926ab0ea5
[ 0.00016860129835549742, 0.00016860129835549742, 0.00016860129835549742, 0.00016860129835549742, 0 ]
{ "id": 8, "code_window": [ " duration: theme.transitions.duration.leavingScreen,\n", " }),\n", " overflowX: 'hidden',\n", " width: `calc(${theme.spacing(7)} + 1px)`,\n", " [theme.breakpoints.up('sm')]: {\n", " width: `calc(${theme.spacing(9)} + 1px)`,\n", " },\n", "});\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " width: `calc(${theme.spacing(8)} + 1px)`,\n" ], "file_path": "docs/data/material/components/drawers/MiniDrawer.tsx", "type": "replace", "edit_start_line_idx": 39 }
import createSvgIcon from './utils/createSvgIcon'; import { jsx as _jsx } from "react/jsx-runtime"; export default createSvgIcon( /*#__PURE__*/_jsx("path", { d: "M19 19h2v2h-2v-2zm0-2h2v-2h-2v2zM3 13h2v-2H3v2zm0 4h2v-2H3v2zm0-8h2V7H3v2zm0-4h2V3H3v2zm4 0h2V3H7v2zm8 16h2v-2h-2v2zm-4 0h2v-2h-2v2zm4 0h2v-2h-2v2zm-8 0h2v-2H7v2zm-4 0h2v-2H3v2zM21 8c0-2.76-2.24-5-5-5h-5v2h5c1.65 0 3 1.35 3 3v5h2V8z" }), 'RoundedCornerOutlined');
packages/mui-icons-material/lib/esm/RoundedCornerOutlined.js
0
https://github.com/mui/material-ui/commit/1db2ae2530d6a5ccb26c63ad7e9bbe5926ab0ea5
[ 0.00017465971177443862, 0.00017465971177443862, 0.00017465971177443862, 0.00017465971177443862, 0 ]
{ "id": 8, "code_window": [ " duration: theme.transitions.duration.leavingScreen,\n", " }),\n", " overflowX: 'hidden',\n", " width: `calc(${theme.spacing(7)} + 1px)`,\n", " [theme.breakpoints.up('sm')]: {\n", " width: `calc(${theme.spacing(9)} + 1px)`,\n", " },\n", "});\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " width: `calc(${theme.spacing(8)} + 1px)`,\n" ], "file_path": "docs/data/material/components/drawers/MiniDrawer.tsx", "type": "replace", "edit_start_line_idx": 39 }
"use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; var _createSvgIcon = _interopRequireDefault(require("./utils/createSvgIcon")); var _jsxRuntime = require("react/jsx-runtime"); var _default = (0, _createSvgIcon.default)( /*#__PURE__*/(0, _jsxRuntime.jsx)("path", { d: "M11 6c1.38 0 2.63.56 3.54 1.46L12 10h6V4l-2.05 2.05C14.68 4.78 12.93 4 11 4c-3.53 0-6.43 2.61-6.92 6H6.1c.46-2.28 2.48-4 4.9-4zm5.64 9.14c.66-.9 1.12-1.97 1.28-3.14H15.9c-.46 2.28-2.48 4-4.9 4-1.38 0-2.63-.56-3.54-1.46L10 12H4v6l2.05-2.05C7.32 17.22 9.07 18 11 18c1.55 0 2.98-.51 4.14-1.36L20 21.49 21.49 20l-4.85-4.86z" }), 'FindReplace'); exports.default = _default;
packages/mui-icons-material/lib/FindReplace.js
0
https://github.com/mui/material-ui/commit/1db2ae2530d6a5ccb26c63ad7e9bbe5926ab0ea5
[ 0.00017317369929514825, 0.00017050054157152772, 0.00016782739839982241, 0.00017050054157152772, 0.0000026731504476629198 ]
{ "id": 9, "code_window": [ " color=\"inherit\"\n", " aria-label=\"open drawer\"\n", " onClick={handleDrawerOpen}\n", " edge=\"start\"\n", " sx={{\n", " marginRight: '36px',\n", " ...(open && { display: 'none' }),\n", " }}\n", " >\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " marginRight: 5,\n" ], "file_path": "docs/data/material/components/drawers/MiniDrawer.tsx", "type": "replace", "edit_start_line_idx": 114 }
import * as React from 'react'; import { styled, useTheme } from '@mui/material/styles'; import Box from '@mui/material/Box'; import MuiDrawer from '@mui/material/Drawer'; import MuiAppBar from '@mui/material/AppBar'; import Toolbar from '@mui/material/Toolbar'; import List from '@mui/material/List'; import CssBaseline from '@mui/material/CssBaseline'; import Typography from '@mui/material/Typography'; import Divider from '@mui/material/Divider'; import IconButton from '@mui/material/IconButton'; import MenuIcon from '@mui/icons-material/Menu'; import ChevronLeftIcon from '@mui/icons-material/ChevronLeft'; import ChevronRightIcon from '@mui/icons-material/ChevronRight'; import ListItem from '@mui/material/ListItem'; import ListItemIcon from '@mui/material/ListItemIcon'; import ListItemText from '@mui/material/ListItemText'; import InboxIcon from '@mui/icons-material/MoveToInbox'; import MailIcon from '@mui/icons-material/Mail'; const drawerWidth = 240; const openedMixin = (theme) => ({ width: drawerWidth, transition: theme.transitions.create('width', { easing: theme.transitions.easing.sharp, duration: theme.transitions.duration.enteringScreen, }), overflowX: 'hidden', }); const closedMixin = (theme) => ({ transition: theme.transitions.create('width', { easing: theme.transitions.easing.sharp, duration: theme.transitions.duration.leavingScreen, }), overflowX: 'hidden', width: `calc(${theme.spacing(7)} + 1px)`, [theme.breakpoints.up('sm')]: { width: `calc(${theme.spacing(9)} + 1px)`, }, }); const DrawerHeader = styled('div')(({ theme }) => ({ display: 'flex', alignItems: 'center', justifyContent: 'flex-end', padding: theme.spacing(0, 1), // necessary for content to be below app bar ...theme.mixins.toolbar, })); const AppBar = styled(MuiAppBar, { shouldForwardProp: (prop) => prop !== 'open', })(({ theme, open }) => ({ zIndex: theme.zIndex.drawer + 1, transition: theme.transitions.create(['width', 'margin'], { easing: theme.transitions.easing.sharp, duration: theme.transitions.duration.leavingScreen, }), ...(open && { marginLeft: drawerWidth, width: `calc(100% - ${drawerWidth}px)`, transition: theme.transitions.create(['width', 'margin'], { easing: theme.transitions.easing.sharp, duration: theme.transitions.duration.enteringScreen, }), }), })); const Drawer = styled(MuiDrawer, { shouldForwardProp: (prop) => prop !== 'open' })( ({ theme, open }) => ({ width: drawerWidth, flexShrink: 0, whiteSpace: 'nowrap', boxSizing: 'border-box', ...(open && { ...openedMixin(theme), '& .MuiDrawer-paper': openedMixin(theme), }), ...(!open && { ...closedMixin(theme), '& .MuiDrawer-paper': closedMixin(theme), }), }), ); export default function MiniDrawer() { const theme = useTheme(); const [open, setOpen] = React.useState(false); const handleDrawerOpen = () => { setOpen(true); }; const handleDrawerClose = () => { setOpen(false); }; return ( <Box sx={{ display: 'flex' }}> <CssBaseline /> <AppBar position="fixed" open={open}> <Toolbar> <IconButton color="inherit" aria-label="open drawer" onClick={handleDrawerOpen} edge="start" sx={{ marginRight: '36px', ...(open && { display: 'none' }), }} > <MenuIcon /> </IconButton> <Typography variant="h6" noWrap component="div"> Mini variant drawer </Typography> </Toolbar> </AppBar> <Drawer variant="permanent" open={open}> <DrawerHeader> <IconButton onClick={handleDrawerClose}> {theme.direction === 'rtl' ? <ChevronRightIcon /> : <ChevronLeftIcon />} </IconButton> </DrawerHeader> <Divider /> <List> {['Inbox', 'Starred', 'Send email', 'Drafts'].map((text, index) => ( <ListItem button key={text}> <ListItemIcon> {index % 2 === 0 ? <InboxIcon /> : <MailIcon />} </ListItemIcon> <ListItemText primary={text} /> </ListItem> ))} </List> <Divider /> <List> {['All mail', 'Trash', 'Spam'].map((text, index) => ( <ListItem button key={text}> <ListItemIcon> {index % 2 === 0 ? <InboxIcon /> : <MailIcon />} </ListItemIcon> <ListItemText primary={text} /> </ListItem> ))} </List> </Drawer> <Box component="main" sx={{ flexGrow: 1, p: 3 }}> <DrawerHeader /> <Typography paragraph> Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Rhoncus dolor purus non enim praesent elementum facilisis leo vel. Risus at ultrices mi tempus imperdiet. Semper risus in hendrerit gravida rutrum quisque non tellus. Convallis convallis tellus id interdum velit laoreet id donec ultrices. Odio morbi quis commodo odio aenean sed adipiscing. Amet nisl suscipit adipiscing bibendum est ultricies integer quis. Cursus euismod quis viverra nibh cras. Metus vulputate eu scelerisque felis imperdiet proin fermentum leo. Mauris commodo quis imperdiet massa tincidunt. Cras tincidunt lobortis feugiat vivamus at augue. At augue eget arcu dictum varius duis at consectetur lorem. Velit sed ullamcorper morbi tincidunt. Lorem donec massa sapien faucibus et molestie ac. </Typography> <Typography paragraph> Consequat mauris nunc congue nisi vitae suscipit. Fringilla est ullamcorper eget nulla facilisi etiam dignissim diam. Pulvinar elementum integer enim neque volutpat ac tincidunt. Ornare suspendisse sed nisi lacus sed viverra tellus. Purus sit amet volutpat consequat mauris. Elementum eu facilisis sed odio morbi. Euismod lacinia at quis risus sed vulputate odio. Morbi tincidunt ornare massa eget egestas purus viverra accumsan in. In hendrerit gravida rutrum quisque non tellus orci ac. Pellentesque nec nam aliquam sem et tortor. Habitant morbi tristique senectus et. Adipiscing elit duis tristique sollicitudin nibh sit. Ornare aenean euismod elementum nisi quis eleifend. Commodo viverra maecenas accumsan lacus vel facilisis. Nulla posuere sollicitudin aliquam ultrices sagittis orci a. </Typography> </Box> </Box> ); }
docs/data/material/components/drawers/MiniDrawer.js
1
https://github.com/mui/material-ui/commit/1db2ae2530d6a5ccb26c63ad7e9bbe5926ab0ea5
[ 0.6436526775360107, 0.03556670993566513, 0.0001640829286770895, 0.00017462839605286717, 0.1433677226305008 ]
{ "id": 9, "code_window": [ " color=\"inherit\"\n", " aria-label=\"open drawer\"\n", " onClick={handleDrawerOpen}\n", " edge=\"start\"\n", " sx={{\n", " marginRight: '36px',\n", " ...(open && { display: 'none' }),\n", " }}\n", " >\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " marginRight: 5,\n" ], "file_path": "docs/data/material/components/drawers/MiniDrawer.tsx", "type": "replace", "edit_start_line_idx": 114 }
<svg xmlns="http://www.w3.org/2000/svg" height="24" viewBox="0 0 24 24" width="24"><path d="M0 0h24v24H0V0z" fill="none"/><path d="M14 5c0-1.1-.9-2-2-2h-1V2c0-.55-.45-1-1-1H6c-.55 0-1 .45-1 1v1H4c-1.1 0-2 .9-2 2v15c0 1.1.9 2 2 2h8c1.1 0 2-.9 2-2h8V5h-8zm6 13h-8v2H4V5h3V3h2v2h3v2h8v11zM9 15h2v2H9zm0-7h2v2H9zm4 7h2v2h-2zm0-7h2v2h-2zm4 7h2v2h-2zm0-7h2v2h-2z"/></svg>
packages/mui-icons-material/material-icons/camera_roll_outlined_24px.svg
0
https://github.com/mui/material-ui/commit/1db2ae2530d6a5ccb26c63ad7e9bbe5926ab0ea5
[ 0.00016797901480458677, 0.00016797901480458677, 0.00016797901480458677, 0.00016797901480458677, 0 ]
{ "id": 9, "code_window": [ " color=\"inherit\"\n", " aria-label=\"open drawer\"\n", " onClick={handleDrawerOpen}\n", " edge=\"start\"\n", " sx={{\n", " marginRight: '36px',\n", " ...(open && { display: 'none' }),\n", " }}\n", " >\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " marginRight: 5,\n" ], "file_path": "docs/data/material/components/drawers/MiniDrawer.tsx", "type": "replace", "edit_start_line_idx": 114 }
<svg xmlns="http://www.w3.org/2000/svg" height="24" viewBox="0 0 24 24" width="24"><path d="M0 0h24v24H0z" fill="none"/><path d="M0 0h24v24H0z" fill="none" opacity=".1"/><path d="M21 3H3c-1.1 0-2 .9-2 2v3h2V5h18v14h-7v2h7c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zM1 18v3h3c0-1.66-1.34-3-3-3zm0-4v2c2.76 0 5 2.24 5 5h2c0-3.87-3.13-7-7-7zm0-4v2c4.97 0 9 4.03 9 9h2c0-6.08-4.93-11-11-11z"/></svg>
packages/mui-icons-material/material-icons/cast_24px.svg
0
https://github.com/mui/material-ui/commit/1db2ae2530d6a5ccb26c63ad7e9bbe5926ab0ea5
[ 0.0001690646167844534, 0.0001690646167844534, 0.0001690646167844534, 0.0001690646167844534, 0 ]
{ "id": 9, "code_window": [ " color=\"inherit\"\n", " aria-label=\"open drawer\"\n", " onClick={handleDrawerOpen}\n", " edge=\"start\"\n", " sx={{\n", " marginRight: '36px',\n", " ...(open && { display: 'none' }),\n", " }}\n", " >\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " marginRight: 5,\n" ], "file_path": "docs/data/material/components/drawers/MiniDrawer.tsx", "type": "replace", "edit_start_line_idx": 114 }
import * as React from 'react'; import Box from '@mui/material/Box'; export default function Visibility() { return ( <div style={{ width: '100%' }}> <Box component="span" sx={{ visibility: 'visible', my: 2, p: 1, bgcolor: (theme) => theme.palette.mode === 'dark' ? '#101010' : 'grey.100', color: (theme) => theme.palette.mode === 'dark' ? 'grey.300' : 'grey.800', border: '1px solid', borderColor: (theme) => theme.palette.mode === 'dark' ? 'grey.800' : 'grey.300', borderRadius: 2, fontSize: '0.875rem', fontWeight: '700', }} > Visible container </Box> <Box component="span" sx={{ visibility: 'hidden', p: 1, m: 1, bgcolor: 'background.paper', }} > Invisible container </Box> </div> ); }
docs/data/system/display/Visibility.tsx
0
https://github.com/mui/material-ui/commit/1db2ae2530d6a5ccb26c63ad7e9bbe5926ab0ea5
[ 0.00016931256686802953, 0.00016853591660037637, 0.0001678861299296841, 0.00016833111294545233, 5.19746606642002e-7 ]
{ "id": 10, "code_window": [ " </DrawerHeader>\n", " <Divider />\n", " <List>\n", " {['Inbox', 'Starred', 'Send email', 'Drafts'].map((text, index) => (\n", " <ListItem button key={text}>\n", " <ListItemIcon>\n", " {index % 2 === 0 ? <InboxIcon /> : <MailIcon />}\n", " </ListItemIcon>\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep" ], "after_edit": [ " <ListItemButton\n", " key={text}\n", " sx={{\n", " minHeight: 48,\n", " justifyContent: open ? 'initial' : 'center',\n", " px: 2.5,\n", " }}\n", " >\n", " <ListItemIcon\n", " sx={{\n", " minWidth: 0,\n", " mr: open ? 3 : 'auto',\n", " justifyContent: 'center',\n", " }}\n", " >\n" ], "file_path": "docs/data/material/components/drawers/MiniDrawer.tsx", "type": "replace", "edit_start_line_idx": 134 }
import * as React from 'react'; import { styled, useTheme, Theme, CSSObject } from '@mui/material/styles'; import Box from '@mui/material/Box'; import MuiDrawer from '@mui/material/Drawer'; import MuiAppBar, { AppBarProps as MuiAppBarProps } from '@mui/material/AppBar'; import Toolbar from '@mui/material/Toolbar'; import List from '@mui/material/List'; import CssBaseline from '@mui/material/CssBaseline'; import Typography from '@mui/material/Typography'; import Divider from '@mui/material/Divider'; import IconButton from '@mui/material/IconButton'; import MenuIcon from '@mui/icons-material/Menu'; import ChevronLeftIcon from '@mui/icons-material/ChevronLeft'; import ChevronRightIcon from '@mui/icons-material/ChevronRight'; import ListItem from '@mui/material/ListItem'; import ListItemIcon from '@mui/material/ListItemIcon'; import ListItemText from '@mui/material/ListItemText'; import InboxIcon from '@mui/icons-material/MoveToInbox'; import MailIcon from '@mui/icons-material/Mail'; const drawerWidth = 240; const openedMixin = (theme: Theme): CSSObject => ({ width: drawerWidth, transition: theme.transitions.create('width', { easing: theme.transitions.easing.sharp, duration: theme.transitions.duration.enteringScreen, }), overflowX: 'hidden', }); const closedMixin = (theme: Theme): CSSObject => ({ transition: theme.transitions.create('width', { easing: theme.transitions.easing.sharp, duration: theme.transitions.duration.leavingScreen, }), overflowX: 'hidden', width: `calc(${theme.spacing(7)} + 1px)`, [theme.breakpoints.up('sm')]: { width: `calc(${theme.spacing(9)} + 1px)`, }, }); const DrawerHeader = styled('div')(({ theme }) => ({ display: 'flex', alignItems: 'center', justifyContent: 'flex-end', padding: theme.spacing(0, 1), // necessary for content to be below app bar ...theme.mixins.toolbar, })); interface AppBarProps extends MuiAppBarProps { open?: boolean; } const AppBar = styled(MuiAppBar, { shouldForwardProp: (prop) => prop !== 'open', })<AppBarProps>(({ theme, open }) => ({ zIndex: theme.zIndex.drawer + 1, transition: theme.transitions.create(['width', 'margin'], { easing: theme.transitions.easing.sharp, duration: theme.transitions.duration.leavingScreen, }), ...(open && { marginLeft: drawerWidth, width: `calc(100% - ${drawerWidth}px)`, transition: theme.transitions.create(['width', 'margin'], { easing: theme.transitions.easing.sharp, duration: theme.transitions.duration.enteringScreen, }), }), })); const Drawer = styled(MuiDrawer, { shouldForwardProp: (prop) => prop !== 'open' })( ({ theme, open }) => ({ width: drawerWidth, flexShrink: 0, whiteSpace: 'nowrap', boxSizing: 'border-box', ...(open && { ...openedMixin(theme), '& .MuiDrawer-paper': openedMixin(theme), }), ...(!open && { ...closedMixin(theme), '& .MuiDrawer-paper': closedMixin(theme), }), }), ); export default function MiniDrawer() { const theme = useTheme(); const [open, setOpen] = React.useState(false); const handleDrawerOpen = () => { setOpen(true); }; const handleDrawerClose = () => { setOpen(false); }; return ( <Box sx={{ display: 'flex' }}> <CssBaseline /> <AppBar position="fixed" open={open}> <Toolbar> <IconButton color="inherit" aria-label="open drawer" onClick={handleDrawerOpen} edge="start" sx={{ marginRight: '36px', ...(open && { display: 'none' }), }} > <MenuIcon /> </IconButton> <Typography variant="h6" noWrap component="div"> Mini variant drawer </Typography> </Toolbar> </AppBar> <Drawer variant="permanent" open={open}> <DrawerHeader> <IconButton onClick={handleDrawerClose}> {theme.direction === 'rtl' ? <ChevronRightIcon /> : <ChevronLeftIcon />} </IconButton> </DrawerHeader> <Divider /> <List> {['Inbox', 'Starred', 'Send email', 'Drafts'].map((text, index) => ( <ListItem button key={text}> <ListItemIcon> {index % 2 === 0 ? <InboxIcon /> : <MailIcon />} </ListItemIcon> <ListItemText primary={text} /> </ListItem> ))} </List> <Divider /> <List> {['All mail', 'Trash', 'Spam'].map((text, index) => ( <ListItem button key={text}> <ListItemIcon> {index % 2 === 0 ? <InboxIcon /> : <MailIcon />} </ListItemIcon> <ListItemText primary={text} /> </ListItem> ))} </List> </Drawer> <Box component="main" sx={{ flexGrow: 1, p: 3 }}> <DrawerHeader /> <Typography paragraph> Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Rhoncus dolor purus non enim praesent elementum facilisis leo vel. Risus at ultrices mi tempus imperdiet. Semper risus in hendrerit gravida rutrum quisque non tellus. Convallis convallis tellus id interdum velit laoreet id donec ultrices. Odio morbi quis commodo odio aenean sed adipiscing. Amet nisl suscipit adipiscing bibendum est ultricies integer quis. Cursus euismod quis viverra nibh cras. Metus vulputate eu scelerisque felis imperdiet proin fermentum leo. Mauris commodo quis imperdiet massa tincidunt. Cras tincidunt lobortis feugiat vivamus at augue. At augue eget arcu dictum varius duis at consectetur lorem. Velit sed ullamcorper morbi tincidunt. Lorem donec massa sapien faucibus et molestie ac. </Typography> <Typography paragraph> Consequat mauris nunc congue nisi vitae suscipit. Fringilla est ullamcorper eget nulla facilisi etiam dignissim diam. Pulvinar elementum integer enim neque volutpat ac tincidunt. Ornare suspendisse sed nisi lacus sed viverra tellus. Purus sit amet volutpat consequat mauris. Elementum eu facilisis sed odio morbi. Euismod lacinia at quis risus sed vulputate odio. Morbi tincidunt ornare massa eget egestas purus viverra accumsan in. In hendrerit gravida rutrum quisque non tellus orci ac. Pellentesque nec nam aliquam sem et tortor. Habitant morbi tristique senectus et. Adipiscing elit duis tristique sollicitudin nibh sit. Ornare aenean euismod elementum nisi quis eleifend. Commodo viverra maecenas accumsan lacus vel facilisis. Nulla posuere sollicitudin aliquam ultrices sagittis orci a. </Typography> </Box> </Box> ); }
docs/data/material/components/drawers/MiniDrawer.tsx
1
https://github.com/mui/material-ui/commit/1db2ae2530d6a5ccb26c63ad7e9bbe5926ab0ea5
[ 0.9973767995834351, 0.05865292623639107, 0.00016419720486737788, 0.00018177373567596078, 0.2225048691034317 ]
{ "id": 10, "code_window": [ " </DrawerHeader>\n", " <Divider />\n", " <List>\n", " {['Inbox', 'Starred', 'Send email', 'Drafts'].map((text, index) => (\n", " <ListItem button key={text}>\n", " <ListItemIcon>\n", " {index % 2 === 0 ? <InboxIcon /> : <MailIcon />}\n", " </ListItemIcon>\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep" ], "after_edit": [ " <ListItemButton\n", " key={text}\n", " sx={{\n", " minHeight: 48,\n", " justifyContent: open ? 'initial' : 'center',\n", " px: 2.5,\n", " }}\n", " >\n", " <ListItemIcon\n", " sx={{\n", " minWidth: 0,\n", " mr: open ? 3 : 'auto',\n", " justifyContent: 'center',\n", " }}\n", " >\n" ], "file_path": "docs/data/material/components/drawers/MiniDrawer.tsx", "type": "replace", "edit_start_line_idx": 134 }
import createSvgIcon from './utils/createSvgIcon'; import { jsx as _jsx } from "react/jsx-runtime"; export default createSvgIcon( /*#__PURE__*/_jsx("path", { d: "m21.22 18.02 2 2H24v-2h-2.78zm.77-2 .01-10c0-1.11-.9-2-2-2H7.22l5.23 5.23c.18-.04.36-.07.55-.1V7.02l4 3.73-1.58 1.47 5.54 5.54c.61-.33 1.03-.99 1.03-1.74zM2.39 1.73 1.11 3l1.54 1.54c-.4.36-.65.89-.65 1.48v10c0 1.1.89 2 2 2H0v2h18.13l2.71 2.71 1.27-1.27L2.39 1.73zM7 15.02c.31-1.48.92-2.95 2.07-4.06l1.59 1.59c-1.54.38-2.7 1.18-3.66 2.47z" }), 'StopScreenShare');
packages/mui-icons-material/lib/esm/StopScreenShare.js
0
https://github.com/mui/material-ui/commit/1db2ae2530d6a5ccb26c63ad7e9bbe5926ab0ea5
[ 0.00016690260963514447, 0.00016690260963514447, 0.00016690260963514447, 0.00016690260963514447, 0 ]
{ "id": 10, "code_window": [ " </DrawerHeader>\n", " <Divider />\n", " <List>\n", " {['Inbox', 'Starred', 'Send email', 'Drafts'].map((text, index) => (\n", " <ListItem button key={text}>\n", " <ListItemIcon>\n", " {index % 2 === 0 ? <InboxIcon /> : <MailIcon />}\n", " </ListItemIcon>\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep" ], "after_edit": [ " <ListItemButton\n", " key={text}\n", " sx={{\n", " minHeight: 48,\n", " justifyContent: open ? 'initial' : 'center',\n", " px: 2.5,\n", " }}\n", " >\n", " <ListItemIcon\n", " sx={{\n", " minWidth: 0,\n", " mr: open ? 3 : 'auto',\n", " justifyContent: 'center',\n", " }}\n", " >\n" ], "file_path": "docs/data/material/components/drawers/MiniDrawer.tsx", "type": "replace", "edit_start_line_idx": 134 }
import * as React from 'react'; import PropTypes from 'prop-types'; import Tabs from '@mui/material/Tabs'; import Tab from '@mui/material/Tab'; import Typography from '@mui/material/Typography'; import Box from '@mui/material/Box'; function TabPanel(props) { const { children, value, index, ...other } = props; return ( <div role="tabpanel" hidden={value !== index} id={`simple-tabpanel-${index}`} aria-labelledby={`simple-tab-${index}`} {...other} > {value === index && ( <Box sx={{ p: 3 }}> <Typography>{children}</Typography> </Box> )} </div> ); } TabPanel.propTypes = { children: PropTypes.node, index: PropTypes.number.isRequired, value: PropTypes.number.isRequired, }; function a11yProps(index) { return { id: `simple-tab-${index}`, 'aria-controls': `simple-tabpanel-${index}`, }; } export default function BasicTabs() { const [value, setValue] = React.useState(0); const handleChange = (event, newValue) => { setValue(newValue); }; return ( <Box sx={{ width: '100%' }}> <Box sx={{ borderBottom: 1, borderColor: 'divider' }}> <Tabs value={value} onChange={handleChange} aria-label="basic tabs example"> <Tab label="Item One" {...a11yProps(0)} /> <Tab label="Item Two" {...a11yProps(1)} /> <Tab label="Item Three" {...a11yProps(2)} /> </Tabs> </Box> <TabPanel value={value} index={0}> Item One </TabPanel> <TabPanel value={value} index={1}> Item Two </TabPanel> <TabPanel value={value} index={2}> Item Three </TabPanel> </Box> ); }
docs/data/material/components/tabs/BasicTabs.js
0
https://github.com/mui/material-ui/commit/1db2ae2530d6a5ccb26c63ad7e9bbe5926ab0ea5
[ 0.00017838810163084418, 0.00017082170234061778, 0.00016500736819580197, 0.000170409373822622, 0.0000042042406676046085 ]
{ "id": 10, "code_window": [ " </DrawerHeader>\n", " <Divider />\n", " <List>\n", " {['Inbox', 'Starred', 'Send email', 'Drafts'].map((text, index) => (\n", " <ListItem button key={text}>\n", " <ListItemIcon>\n", " {index % 2 === 0 ? <InboxIcon /> : <MailIcon />}\n", " </ListItemIcon>\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep" ], "after_edit": [ " <ListItemButton\n", " key={text}\n", " sx={{\n", " minHeight: 48,\n", " justifyContent: open ? 'initial' : 'center',\n", " px: 2.5,\n", " }}\n", " >\n", " <ListItemIcon\n", " sx={{\n", " minWidth: 0,\n", " mr: open ? 3 : 'auto',\n", " justifyContent: 'center',\n", " }}\n", " >\n" ], "file_path": "docs/data/material/components/drawers/MiniDrawer.tsx", "type": "replace", "edit_start_line_idx": 134 }
{ "componentDescription": "Utility component that locks focus inside the component.", "propDescriptions": { "children": "A single child content element.<br>⚠️ <a href=\"/guides/composition/#caveat-with-refs\">Needs to be able to hold a ref</a>.", "disableAutoFocus": "If <code>true</code>, the trap focus will not automatically shift focus to itself when it opens, and replace it to the last focused element when it closes. This also works correctly with any trap focus children that have the <code>disableAutoFocus</code> prop.<br>Generally this should never be set to <code>true</code> as it makes the trap focus less accessible to assistive technologies, like screen readers.", "disableEnforceFocus": "If <code>true</code>, the trap focus will not prevent focus from leaving the trap focus while open.<br>Generally this should never be set to <code>true</code> as it makes the trap focus less accessible to assistive technologies, like screen readers.", "disableRestoreFocus": "If <code>true</code>, the trap focus will not restore focus to previously focused element once trap focus is hidden or unmounted.", "getTabbable": "Returns an array of ordered tabbable nodes (i.e. in tab order) within the root. For instance, you can provide the &quot;tabbable&quot; npm dependency.<br><br><strong>Signature:</strong><br><code>function(root: HTMLElement) =&gt; void</code><br>", "isEnabled": "This prop extends the <code>open</code> prop. It allows to toggle the open state without having to wait for a rerender when changing the <code>open</code> prop. This prop should be memoized. It can be used to support multiple trap focus mounted at the same time.", "open": "If <code>true</code>, focus is locked." }, "classDescriptions": {} }
docs/translations/api-docs/unstable-trap-focus/unstable-trap-focus-pt.json
0
https://github.com/mui/material-ui/commit/1db2ae2530d6a5ccb26c63ad7e9bbe5926ab0ea5
[ 0.0001700540742604062, 0.0001675622770562768, 0.0001650704798521474, 0.0001675622770562768, 0.000002491797204129398 ]
{ "id": 11, "code_window": [ " {index % 2 === 0 ? <InboxIcon /> : <MailIcon />}\n", " </ListItemIcon>\n", " <ListItemText primary={text} />\n", " </ListItem>\n", " ))}\n", " </List>\n", " <Divider />\n", " <List>\n" ], "labels": [ "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " <ListItemText primary={text} sx={{ opacity: open ? 1 : 0 }} />\n", " </ListItemButton>\n" ], "file_path": "docs/data/material/components/drawers/MiniDrawer.tsx", "type": "replace", "edit_start_line_idx": 138 }
import * as React from 'react'; import { styled, useTheme } from '@mui/material/styles'; import Box from '@mui/material/Box'; import MuiDrawer from '@mui/material/Drawer'; import MuiAppBar from '@mui/material/AppBar'; import Toolbar from '@mui/material/Toolbar'; import List from '@mui/material/List'; import CssBaseline from '@mui/material/CssBaseline'; import Typography from '@mui/material/Typography'; import Divider from '@mui/material/Divider'; import IconButton from '@mui/material/IconButton'; import MenuIcon from '@mui/icons-material/Menu'; import ChevronLeftIcon from '@mui/icons-material/ChevronLeft'; import ChevronRightIcon from '@mui/icons-material/ChevronRight'; import ListItem from '@mui/material/ListItem'; import ListItemIcon from '@mui/material/ListItemIcon'; import ListItemText from '@mui/material/ListItemText'; import InboxIcon from '@mui/icons-material/MoveToInbox'; import MailIcon from '@mui/icons-material/Mail'; const drawerWidth = 240; const openedMixin = (theme) => ({ width: drawerWidth, transition: theme.transitions.create('width', { easing: theme.transitions.easing.sharp, duration: theme.transitions.duration.enteringScreen, }), overflowX: 'hidden', }); const closedMixin = (theme) => ({ transition: theme.transitions.create('width', { easing: theme.transitions.easing.sharp, duration: theme.transitions.duration.leavingScreen, }), overflowX: 'hidden', width: `calc(${theme.spacing(7)} + 1px)`, [theme.breakpoints.up('sm')]: { width: `calc(${theme.spacing(9)} + 1px)`, }, }); const DrawerHeader = styled('div')(({ theme }) => ({ display: 'flex', alignItems: 'center', justifyContent: 'flex-end', padding: theme.spacing(0, 1), // necessary for content to be below app bar ...theme.mixins.toolbar, })); const AppBar = styled(MuiAppBar, { shouldForwardProp: (prop) => prop !== 'open', })(({ theme, open }) => ({ zIndex: theme.zIndex.drawer + 1, transition: theme.transitions.create(['width', 'margin'], { easing: theme.transitions.easing.sharp, duration: theme.transitions.duration.leavingScreen, }), ...(open && { marginLeft: drawerWidth, width: `calc(100% - ${drawerWidth}px)`, transition: theme.transitions.create(['width', 'margin'], { easing: theme.transitions.easing.sharp, duration: theme.transitions.duration.enteringScreen, }), }), })); const Drawer = styled(MuiDrawer, { shouldForwardProp: (prop) => prop !== 'open' })( ({ theme, open }) => ({ width: drawerWidth, flexShrink: 0, whiteSpace: 'nowrap', boxSizing: 'border-box', ...(open && { ...openedMixin(theme), '& .MuiDrawer-paper': openedMixin(theme), }), ...(!open && { ...closedMixin(theme), '& .MuiDrawer-paper': closedMixin(theme), }), }), ); export default function MiniDrawer() { const theme = useTheme(); const [open, setOpen] = React.useState(false); const handleDrawerOpen = () => { setOpen(true); }; const handleDrawerClose = () => { setOpen(false); }; return ( <Box sx={{ display: 'flex' }}> <CssBaseline /> <AppBar position="fixed" open={open}> <Toolbar> <IconButton color="inherit" aria-label="open drawer" onClick={handleDrawerOpen} edge="start" sx={{ marginRight: '36px', ...(open && { display: 'none' }), }} > <MenuIcon /> </IconButton> <Typography variant="h6" noWrap component="div"> Mini variant drawer </Typography> </Toolbar> </AppBar> <Drawer variant="permanent" open={open}> <DrawerHeader> <IconButton onClick={handleDrawerClose}> {theme.direction === 'rtl' ? <ChevronRightIcon /> : <ChevronLeftIcon />} </IconButton> </DrawerHeader> <Divider /> <List> {['Inbox', 'Starred', 'Send email', 'Drafts'].map((text, index) => ( <ListItem button key={text}> <ListItemIcon> {index % 2 === 0 ? <InboxIcon /> : <MailIcon />} </ListItemIcon> <ListItemText primary={text} /> </ListItem> ))} </List> <Divider /> <List> {['All mail', 'Trash', 'Spam'].map((text, index) => ( <ListItem button key={text}> <ListItemIcon> {index % 2 === 0 ? <InboxIcon /> : <MailIcon />} </ListItemIcon> <ListItemText primary={text} /> </ListItem> ))} </List> </Drawer> <Box component="main" sx={{ flexGrow: 1, p: 3 }}> <DrawerHeader /> <Typography paragraph> Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Rhoncus dolor purus non enim praesent elementum facilisis leo vel. Risus at ultrices mi tempus imperdiet. Semper risus in hendrerit gravida rutrum quisque non tellus. Convallis convallis tellus id interdum velit laoreet id donec ultrices. Odio morbi quis commodo odio aenean sed adipiscing. Amet nisl suscipit adipiscing bibendum est ultricies integer quis. Cursus euismod quis viverra nibh cras. Metus vulputate eu scelerisque felis imperdiet proin fermentum leo. Mauris commodo quis imperdiet massa tincidunt. Cras tincidunt lobortis feugiat vivamus at augue. At augue eget arcu dictum varius duis at consectetur lorem. Velit sed ullamcorper morbi tincidunt. Lorem donec massa sapien faucibus et molestie ac. </Typography> <Typography paragraph> Consequat mauris nunc congue nisi vitae suscipit. Fringilla est ullamcorper eget nulla facilisi etiam dignissim diam. Pulvinar elementum integer enim neque volutpat ac tincidunt. Ornare suspendisse sed nisi lacus sed viverra tellus. Purus sit amet volutpat consequat mauris. Elementum eu facilisis sed odio morbi. Euismod lacinia at quis risus sed vulputate odio. Morbi tincidunt ornare massa eget egestas purus viverra accumsan in. In hendrerit gravida rutrum quisque non tellus orci ac. Pellentesque nec nam aliquam sem et tortor. Habitant morbi tristique senectus et. Adipiscing elit duis tristique sollicitudin nibh sit. Ornare aenean euismod elementum nisi quis eleifend. Commodo viverra maecenas accumsan lacus vel facilisis. Nulla posuere sollicitudin aliquam ultrices sagittis orci a. </Typography> </Box> </Box> ); }
docs/data/material/components/drawers/MiniDrawer.js
1
https://github.com/mui/material-ui/commit/1db2ae2530d6a5ccb26c63ad7e9bbe5926ab0ea5
[ 0.9937121868133545, 0.10314185172319412, 0.00016363624308723956, 0.00017116563685704023, 0.299533873796463 ]
{ "id": 11, "code_window": [ " {index % 2 === 0 ? <InboxIcon /> : <MailIcon />}\n", " </ListItemIcon>\n", " <ListItemText primary={text} />\n", " </ListItem>\n", " ))}\n", " </List>\n", " <Divider />\n", " <List>\n" ], "labels": [ "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " <ListItemText primary={text} sx={{ opacity: open ? 1 : 0 }} />\n", " </ListItemButton>\n" ], "file_path": "docs/data/material/components/drawers/MiniDrawer.tsx", "type": "replace", "edit_start_line_idx": 138 }
import * as React from 'react'; import { SxProps } from '@mui/system'; import { Theme } from '../styles'; import ButtonBase from '../ButtonBase'; import { TabScrollButtonProps } from '../TabScrollButton'; import { OverridableComponent, OverrideProps } from '../OverridableComponent'; import { TabsClasses } from './tabsClasses'; export interface TabsTypeMap<P = {}, D extends React.ElementType = typeof ButtonBase> { props: P & { /** * Callback fired when the component mounts. * This is useful when you want to trigger an action programmatically. * It supports two actions: `updateIndicator()` and `updateScrollButtons()` * * @param {object} actions This object contains all possible actions * that can be triggered programmatically. */ action?: React.Ref<TabsActions>; /** * If `true`, the scroll buttons aren't forced hidden on mobile. * By default the scroll buttons are hidden on mobile and takes precedence over `scrollButtons`. * @default false */ allowScrollButtonsMobile?: boolean; /** * The label for the Tabs as a string. */ 'aria-label'?: string; /** * An id or list of ids separated by a space that label the Tabs. */ 'aria-labelledby'?: string; /** * If `true`, the tabs are centered. * This prop is intended for large views. * @default false */ centered?: boolean; /** * The content of the component. */ children?: React.ReactNode; /** * Override or extend the styles applied to the component. */ classes?: Partial<TabsClasses>; /** * Determines the color of the indicator. * @default 'primary' */ indicatorColor?: 'secondary' | 'primary'; /** * Callback fired when the value changes. * * @param {React.SyntheticEvent} event The event source of the callback. **Warning**: This is a generic event not a change event. * @param {any} value We default to the index of the child (number) */ onChange?: (event: React.SyntheticEvent, value: any) => void; /** * The component orientation (layout flow direction). * @default 'horizontal' */ orientation?: 'horizontal' | 'vertical'; /** * The component used to render the scroll buttons. * @default TabScrollButton */ ScrollButtonComponent?: React.ElementType; /** * Determine behavior of scroll buttons when tabs are set to scroll: * * - `auto` will only present them when not all the items are visible. * - `true` will always present them. * - `false` will never present them. * * By default the scroll buttons are hidden on mobile. * This behavior can be disabled with `allowScrollButtonsMobile`. * @default 'auto' */ scrollButtons?: 'auto' | true | false; /** * If `true` the selected tab changes on focus. Otherwise it only * changes on activation. */ selectionFollowsFocus?: boolean; /** * Props applied to the tab indicator element. * @default {} */ TabIndicatorProps?: React.HTMLAttributes<HTMLDivElement>; /** * Props applied to the [`TabScrollButton`](/api/tab-scroll-button/) element. * @default {} */ TabScrollButtonProps?: Partial<TabScrollButtonProps>; /** * Determines the color of the `Tab`. * @default 'primary' */ textColor?: 'secondary' | 'primary' | 'inherit'; /** * The value of the currently selected `Tab`. * If you don't want any selected `Tab`, you can set this prop to `false`. */ value?: any; /** * Determines additional display behavior of the tabs: * * - `scrollable` will invoke scrolling properties and allow for horizontally * scrolling (or swiping) of the tab bar. * -`fullWidth` will make the tabs grow to use all the available space, * which should be used for small views, like on mobile. * - `standard` will render the default state. * @default 'standard' */ variant?: 'standard' | 'scrollable' | 'fullWidth'; /** * If `true`, the scrollbar is visible. It can be useful when displaying * a long vertical list of tabs. * @default false */ visibleScrollbar?: boolean; /** * The system prop that allows defining system overrides as well as additional CSS styles. */ sx?: SxProps<Theme>; }; defaultComponent: D; } /** * * Demos: * * - [Tabs](https://mui.com/components/tabs/) * * API: * * - [Tabs API](https://mui.com/api/tabs/) */ declare const Tabs: OverridableComponent<TabsTypeMap>; export interface TabsActions { updateIndicator(): void; updateScrollButtons(): void; } export type TabsProps< D extends React.ElementType = TabsTypeMap['defaultComponent'], P = {}, > = OverrideProps<TabsTypeMap<P, D>, D>; export default Tabs;
packages/mui-material/src/Tabs/Tabs.d.ts
0
https://github.com/mui/material-ui/commit/1db2ae2530d6a5ccb26c63ad7e9bbe5926ab0ea5
[ 0.00018651862046681345, 0.0001708068448351696, 0.00016181173850782216, 0.00016923413204494864, 0.000006600866072403733 ]
{ "id": 11, "code_window": [ " {index % 2 === 0 ? <InboxIcon /> : <MailIcon />}\n", " </ListItemIcon>\n", " <ListItemText primary={text} />\n", " </ListItem>\n", " ))}\n", " </List>\n", " <Divider />\n", " <List>\n" ], "labels": [ "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " <ListItemText primary={text} sx={{ opacity: open ? 1 : 0 }} />\n", " </ListItemButton>\n" ], "file_path": "docs/data/material/components/drawers/MiniDrawer.tsx", "type": "replace", "edit_start_line_idx": 138 }
"use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; var _createSvgIcon = _interopRequireDefault(require("./utils/createSvgIcon")); var _jsxRuntime = require("react/jsx-runtime"); var _default = (0, _createSvgIcon.default)( /*#__PURE__*/(0, _jsxRuntime.jsx)("path", { d: "M18 4h3v16h-3V4zM3 13h3v7H3v-7zm11-9h3v3h-3V4zm-4 1h3v4h-3V5zm-3 5h3v4H7v-4z" }), 'WaterfallChartTwoTone'); exports.default = _default;
packages/mui-icons-material/lib/WaterfallChartTwoTone.js
0
https://github.com/mui/material-ui/commit/1db2ae2530d6a5ccb26c63ad7e9bbe5926ab0ea5
[ 0.00016624187992420048, 0.0001653236395213753, 0.00016440539911855012, 0.0001653236395213753, 9.182404028251767e-7 ]
{ "id": 11, "code_window": [ " {index % 2 === 0 ? <InboxIcon /> : <MailIcon />}\n", " </ListItemIcon>\n", " <ListItemText primary={text} />\n", " </ListItem>\n", " ))}\n", " </List>\n", " <Divider />\n", " <List>\n" ], "labels": [ "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " <ListItemText primary={text} sx={{ opacity: open ? 1 : 0 }} />\n", " </ListItemButton>\n" ], "file_path": "docs/data/material/components/drawers/MiniDrawer.tsx", "type": "replace", "edit_start_line_idx": 138 }
import createSvgIcon from './utils/createSvgIcon'; import { jsx as _jsx } from "react/jsx-runtime"; export default createSvgIcon( /*#__PURE__*/_jsx("path", { d: "M12 5.9c1.16 0 2.1.94 2.1 2.1s-.94 2.1-2.1 2.1S9.9 9.16 9.9 8s.94-2.1 2.1-2.1m0 9c2.97 0 6.1 1.46 6.1 2.1v1.1H5.9V17c0-.64 3.13-2.1 6.1-2.1M12 4C9.79 4 8 5.79 8 8s1.79 4 4 4 4-1.79 4-4-1.79-4-4-4zm0 9c-2.67 0-8 1.34-8 4v3h16v-3c0-2.66-5.33-4-8-4z" }), 'PersonOutline');
packages/mui-icons-material/lib/esm/PersonOutline.js
0
https://github.com/mui/material-ui/commit/1db2ae2530d6a5ccb26c63ad7e9bbe5926ab0ea5
[ 0.000166426005307585, 0.000166426005307585, 0.000166426005307585, 0.000166426005307585, 0 ]
{ "id": 12, "code_window": [ " <Divider />\n", " <List>\n", " {['All mail', 'Trash', 'Spam'].map((text, index) => (\n", " <ListItem button key={text}>\n", " <ListItemIcon>\n", " {index % 2 === 0 ? <InboxIcon /> : <MailIcon />}\n", " </ListItemIcon>\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "keep", "keep" ], "after_edit": [ " <ListItemButton\n", " key={text}\n", " sx={{\n", " minHeight: 48,\n", " justifyContent: open ? 'initial' : 'center',\n", " px: 2.5,\n", " }}\n", " >\n", " <ListItemIcon\n", " sx={{\n", " minWidth: 0,\n", " mr: open ? 3 : 'auto',\n", " justifyContent: 'center',\n", " }}\n", " >\n" ], "file_path": "docs/data/material/components/drawers/MiniDrawer.tsx", "type": "replace", "edit_start_line_idx": 145 }
import * as React from 'react'; import { styled, useTheme, Theme, CSSObject } from '@mui/material/styles'; import Box from '@mui/material/Box'; import MuiDrawer from '@mui/material/Drawer'; import MuiAppBar, { AppBarProps as MuiAppBarProps } from '@mui/material/AppBar'; import Toolbar from '@mui/material/Toolbar'; import List from '@mui/material/List'; import CssBaseline from '@mui/material/CssBaseline'; import Typography from '@mui/material/Typography'; import Divider from '@mui/material/Divider'; import IconButton from '@mui/material/IconButton'; import MenuIcon from '@mui/icons-material/Menu'; import ChevronLeftIcon from '@mui/icons-material/ChevronLeft'; import ChevronRightIcon from '@mui/icons-material/ChevronRight'; import ListItem from '@mui/material/ListItem'; import ListItemIcon from '@mui/material/ListItemIcon'; import ListItemText from '@mui/material/ListItemText'; import InboxIcon from '@mui/icons-material/MoveToInbox'; import MailIcon from '@mui/icons-material/Mail'; const drawerWidth = 240; const openedMixin = (theme: Theme): CSSObject => ({ width: drawerWidth, transition: theme.transitions.create('width', { easing: theme.transitions.easing.sharp, duration: theme.transitions.duration.enteringScreen, }), overflowX: 'hidden', }); const closedMixin = (theme: Theme): CSSObject => ({ transition: theme.transitions.create('width', { easing: theme.transitions.easing.sharp, duration: theme.transitions.duration.leavingScreen, }), overflowX: 'hidden', width: `calc(${theme.spacing(7)} + 1px)`, [theme.breakpoints.up('sm')]: { width: `calc(${theme.spacing(9)} + 1px)`, }, }); const DrawerHeader = styled('div')(({ theme }) => ({ display: 'flex', alignItems: 'center', justifyContent: 'flex-end', padding: theme.spacing(0, 1), // necessary for content to be below app bar ...theme.mixins.toolbar, })); interface AppBarProps extends MuiAppBarProps { open?: boolean; } const AppBar = styled(MuiAppBar, { shouldForwardProp: (prop) => prop !== 'open', })<AppBarProps>(({ theme, open }) => ({ zIndex: theme.zIndex.drawer + 1, transition: theme.transitions.create(['width', 'margin'], { easing: theme.transitions.easing.sharp, duration: theme.transitions.duration.leavingScreen, }), ...(open && { marginLeft: drawerWidth, width: `calc(100% - ${drawerWidth}px)`, transition: theme.transitions.create(['width', 'margin'], { easing: theme.transitions.easing.sharp, duration: theme.transitions.duration.enteringScreen, }), }), })); const Drawer = styled(MuiDrawer, { shouldForwardProp: (prop) => prop !== 'open' })( ({ theme, open }) => ({ width: drawerWidth, flexShrink: 0, whiteSpace: 'nowrap', boxSizing: 'border-box', ...(open && { ...openedMixin(theme), '& .MuiDrawer-paper': openedMixin(theme), }), ...(!open && { ...closedMixin(theme), '& .MuiDrawer-paper': closedMixin(theme), }), }), ); export default function MiniDrawer() { const theme = useTheme(); const [open, setOpen] = React.useState(false); const handleDrawerOpen = () => { setOpen(true); }; const handleDrawerClose = () => { setOpen(false); }; return ( <Box sx={{ display: 'flex' }}> <CssBaseline /> <AppBar position="fixed" open={open}> <Toolbar> <IconButton color="inherit" aria-label="open drawer" onClick={handleDrawerOpen} edge="start" sx={{ marginRight: '36px', ...(open && { display: 'none' }), }} > <MenuIcon /> </IconButton> <Typography variant="h6" noWrap component="div"> Mini variant drawer </Typography> </Toolbar> </AppBar> <Drawer variant="permanent" open={open}> <DrawerHeader> <IconButton onClick={handleDrawerClose}> {theme.direction === 'rtl' ? <ChevronRightIcon /> : <ChevronLeftIcon />} </IconButton> </DrawerHeader> <Divider /> <List> {['Inbox', 'Starred', 'Send email', 'Drafts'].map((text, index) => ( <ListItem button key={text}> <ListItemIcon> {index % 2 === 0 ? <InboxIcon /> : <MailIcon />} </ListItemIcon> <ListItemText primary={text} /> </ListItem> ))} </List> <Divider /> <List> {['All mail', 'Trash', 'Spam'].map((text, index) => ( <ListItem button key={text}> <ListItemIcon> {index % 2 === 0 ? <InboxIcon /> : <MailIcon />} </ListItemIcon> <ListItemText primary={text} /> </ListItem> ))} </List> </Drawer> <Box component="main" sx={{ flexGrow: 1, p: 3 }}> <DrawerHeader /> <Typography paragraph> Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Rhoncus dolor purus non enim praesent elementum facilisis leo vel. Risus at ultrices mi tempus imperdiet. Semper risus in hendrerit gravida rutrum quisque non tellus. Convallis convallis tellus id interdum velit laoreet id donec ultrices. Odio morbi quis commodo odio aenean sed adipiscing. Amet nisl suscipit adipiscing bibendum est ultricies integer quis. Cursus euismod quis viverra nibh cras. Metus vulputate eu scelerisque felis imperdiet proin fermentum leo. Mauris commodo quis imperdiet massa tincidunt. Cras tincidunt lobortis feugiat vivamus at augue. At augue eget arcu dictum varius duis at consectetur lorem. Velit sed ullamcorper morbi tincidunt. Lorem donec massa sapien faucibus et molestie ac. </Typography> <Typography paragraph> Consequat mauris nunc congue nisi vitae suscipit. Fringilla est ullamcorper eget nulla facilisi etiam dignissim diam. Pulvinar elementum integer enim neque volutpat ac tincidunt. Ornare suspendisse sed nisi lacus sed viverra tellus. Purus sit amet volutpat consequat mauris. Elementum eu facilisis sed odio morbi. Euismod lacinia at quis risus sed vulputate odio. Morbi tincidunt ornare massa eget egestas purus viverra accumsan in. In hendrerit gravida rutrum quisque non tellus orci ac. Pellentesque nec nam aliquam sem et tortor. Habitant morbi tristique senectus et. Adipiscing elit duis tristique sollicitudin nibh sit. Ornare aenean euismod elementum nisi quis eleifend. Commodo viverra maecenas accumsan lacus vel facilisis. Nulla posuere sollicitudin aliquam ultrices sagittis orci a. </Typography> </Box> </Box> ); }
docs/data/material/components/drawers/MiniDrawer.tsx
1
https://github.com/mui/material-ui/commit/1db2ae2530d6a5ccb26c63ad7e9bbe5926ab0ea5
[ 0.9934438467025757, 0.057079609483480453, 0.0001650069170864299, 0.00017137500981334597, 0.22157184779644012 ]
{ "id": 12, "code_window": [ " <Divider />\n", " <List>\n", " {['All mail', 'Trash', 'Spam'].map((text, index) => (\n", " <ListItem button key={text}>\n", " <ListItemIcon>\n", " {index % 2 === 0 ? <InboxIcon /> : <MailIcon />}\n", " </ListItemIcon>\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "keep", "keep" ], "after_edit": [ " <ListItemButton\n", " key={text}\n", " sx={{\n", " minHeight: 48,\n", " justifyContent: open ? 'initial' : 'center',\n", " px: 2.5,\n", " }}\n", " >\n", " <ListItemIcon\n", " sx={{\n", " minWidth: 0,\n", " mr: open ? 3 : 'auto',\n", " justifyContent: 'center',\n", " }}\n", " >\n" ], "file_path": "docs/data/material/components/drawers/MiniDrawer.tsx", "type": "replace", "edit_start_line_idx": 145 }
import createSvgIcon from './utils/createSvgIcon'; import { jsx as _jsx } from "react/jsx-runtime"; export default createSvgIcon( /*#__PURE__*/_jsx("path", { d: "M12 3 2 12h3v8h14v-8h3L12 3zm0 13c-1.1 0-2-.9-2-2s2-4 2-4 2 2.9 2 4-.9 2-2 2z" }), 'WaterDamageSharp');
packages/mui-icons-material/lib/esm/WaterDamageSharp.js
0
https://github.com/mui/material-ui/commit/1db2ae2530d6a5ccb26c63ad7e9bbe5926ab0ea5
[ 0.00016916684398893267, 0.00016916684398893267, 0.00016916684398893267, 0.00016916684398893267, 0 ]
{ "id": 12, "code_window": [ " <Divider />\n", " <List>\n", " {['All mail', 'Trash', 'Spam'].map((text, index) => (\n", " <ListItem button key={text}>\n", " <ListItemIcon>\n", " {index % 2 === 0 ? <InboxIcon /> : <MailIcon />}\n", " </ListItemIcon>\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "keep", "keep" ], "after_edit": [ " <ListItemButton\n", " key={text}\n", " sx={{\n", " minHeight: 48,\n", " justifyContent: open ? 'initial' : 'center',\n", " px: 2.5,\n", " }}\n", " >\n", " <ListItemIcon\n", " sx={{\n", " minWidth: 0,\n", " mr: open ? 3 : 'auto',\n", " justifyContent: 'center',\n", " }}\n", " >\n" ], "file_path": "docs/data/material/components/drawers/MiniDrawer.tsx", "type": "replace", "edit_start_line_idx": 145 }
<svg xmlns="http://www.w3.org/2000/svg" enable-background="new 0 0 24 24" height="24" viewBox="0 0 24 24" width="24"><rect fill="none" height="24" width="24"/><path d="M17,11h3c1.11,0,2-0.9,2-2V5c0-1.11-0.9-2-2-2h-3c-1.11,0-2,0.9-2,2v1H9.01V5c0-1.11-0.9-2-2-2H4C2.9,3,2,3.9,2,5v4 c0,1.11,0.9,2,2,2h3c1.11,0,2-0.9,2-2V8H11v7.01c0,1.65,1.34,2.99,2.99,2.99H15v1c0,1.11,0.9,2,2,2h3c1.11,0,2-0.9,2-2v-4 c0-1.11-0.9-2-2-2h-3c-1.11,0-2,0.9-2,2v1h-1.01C13.45,16,13,15.55,13,15.01V8h2v1C15,10.1,15.9,11,17,11z"/></svg>
packages/mui-icons-material/material-icons/account_tree_rounded_24px.svg
0
https://github.com/mui/material-ui/commit/1db2ae2530d6a5ccb26c63ad7e9bbe5926ab0ea5
[ 0.0001637255190871656, 0.0001637255190871656, 0.0001637255190871656, 0.0001637255190871656, 0 ]
{ "id": 12, "code_window": [ " <Divider />\n", " <List>\n", " {['All mail', 'Trash', 'Spam'].map((text, index) => (\n", " <ListItem button key={text}>\n", " <ListItemIcon>\n", " {index % 2 === 0 ? <InboxIcon /> : <MailIcon />}\n", " </ListItemIcon>\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "keep", "keep" ], "after_edit": [ " <ListItemButton\n", " key={text}\n", " sx={{\n", " minHeight: 48,\n", " justifyContent: open ? 'initial' : 'center',\n", " px: 2.5,\n", " }}\n", " >\n", " <ListItemIcon\n", " sx={{\n", " minWidth: 0,\n", " mr: open ? 3 : 'auto',\n", " justifyContent: 'center',\n", " }}\n", " >\n" ], "file_path": "docs/data/material/components/drawers/MiniDrawer.tsx", "type": "replace", "edit_start_line_idx": 145 }
"use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; var _createSvgIcon = _interopRequireDefault(require("./utils/createSvgIcon")); var _jsxRuntime = require("react/jsx-runtime"); var _default = (0, _createSvgIcon.default)([/*#__PURE__*/(0, _jsxRuntime.jsx)("path", { d: "M20 2H4c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h14l4 4V4c0-1.1-.9-2-2-2zm0 15.17L18.83 16H4V4h16v13.17zM13 5h-2v4H7v2h4v4h2v-4h4V9h-4z" }, "0"), /*#__PURE__*/(0, _jsxRuntime.jsx)("path", { d: "M4 4v12h14.83L20 17.17V4H4zm13 7h-4v4h-2v-4H7V9h4V5h2v4h4v2z", opacity: ".3" }, "1")], 'AddCommentTwoTone'); exports.default = _default;
packages/mui-icons-material/lib/AddCommentTwoTone.js
0
https://github.com/mui/material-ui/commit/1db2ae2530d6a5ccb26c63ad7e9bbe5926ab0ea5
[ 0.00017244770424440503, 0.00017051205213647336, 0.00016837332805152982, 0.00017071512411348522, 0.0000016695435078872833 ]
{ "id": 13, "code_window": [ " {index % 2 === 0 ? <InboxIcon /> : <MailIcon />}\n", " </ListItemIcon>\n", " <ListItemText primary={text} />\n", " </ListItem>\n", " ))}\n", " </List>\n", " </Drawer>\n", " <Box component=\"main\" sx={{ flexGrow: 1, p: 3 }}>\n" ], "labels": [ "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " <ListItemText primary={text} sx={{ opacity: open ? 1 : 0 }} />\n", " </ListItemButton>\n" ], "file_path": "docs/data/material/components/drawers/MiniDrawer.tsx", "type": "replace", "edit_start_line_idx": 149 }
import * as React from 'react'; import { styled, useTheme } from '@mui/material/styles'; import Box from '@mui/material/Box'; import MuiDrawer from '@mui/material/Drawer'; import MuiAppBar from '@mui/material/AppBar'; import Toolbar from '@mui/material/Toolbar'; import List from '@mui/material/List'; import CssBaseline from '@mui/material/CssBaseline'; import Typography from '@mui/material/Typography'; import Divider from '@mui/material/Divider'; import IconButton from '@mui/material/IconButton'; import MenuIcon from '@mui/icons-material/Menu'; import ChevronLeftIcon from '@mui/icons-material/ChevronLeft'; import ChevronRightIcon from '@mui/icons-material/ChevronRight'; import ListItem from '@mui/material/ListItem'; import ListItemIcon from '@mui/material/ListItemIcon'; import ListItemText from '@mui/material/ListItemText'; import InboxIcon from '@mui/icons-material/MoveToInbox'; import MailIcon from '@mui/icons-material/Mail'; const drawerWidth = 240; const openedMixin = (theme) => ({ width: drawerWidth, transition: theme.transitions.create('width', { easing: theme.transitions.easing.sharp, duration: theme.transitions.duration.enteringScreen, }), overflowX: 'hidden', }); const closedMixin = (theme) => ({ transition: theme.transitions.create('width', { easing: theme.transitions.easing.sharp, duration: theme.transitions.duration.leavingScreen, }), overflowX: 'hidden', width: `calc(${theme.spacing(7)} + 1px)`, [theme.breakpoints.up('sm')]: { width: `calc(${theme.spacing(9)} + 1px)`, }, }); const DrawerHeader = styled('div')(({ theme }) => ({ display: 'flex', alignItems: 'center', justifyContent: 'flex-end', padding: theme.spacing(0, 1), // necessary for content to be below app bar ...theme.mixins.toolbar, })); const AppBar = styled(MuiAppBar, { shouldForwardProp: (prop) => prop !== 'open', })(({ theme, open }) => ({ zIndex: theme.zIndex.drawer + 1, transition: theme.transitions.create(['width', 'margin'], { easing: theme.transitions.easing.sharp, duration: theme.transitions.duration.leavingScreen, }), ...(open && { marginLeft: drawerWidth, width: `calc(100% - ${drawerWidth}px)`, transition: theme.transitions.create(['width', 'margin'], { easing: theme.transitions.easing.sharp, duration: theme.transitions.duration.enteringScreen, }), }), })); const Drawer = styled(MuiDrawer, { shouldForwardProp: (prop) => prop !== 'open' })( ({ theme, open }) => ({ width: drawerWidth, flexShrink: 0, whiteSpace: 'nowrap', boxSizing: 'border-box', ...(open && { ...openedMixin(theme), '& .MuiDrawer-paper': openedMixin(theme), }), ...(!open && { ...closedMixin(theme), '& .MuiDrawer-paper': closedMixin(theme), }), }), ); export default function MiniDrawer() { const theme = useTheme(); const [open, setOpen] = React.useState(false); const handleDrawerOpen = () => { setOpen(true); }; const handleDrawerClose = () => { setOpen(false); }; return ( <Box sx={{ display: 'flex' }}> <CssBaseline /> <AppBar position="fixed" open={open}> <Toolbar> <IconButton color="inherit" aria-label="open drawer" onClick={handleDrawerOpen} edge="start" sx={{ marginRight: '36px', ...(open && { display: 'none' }), }} > <MenuIcon /> </IconButton> <Typography variant="h6" noWrap component="div"> Mini variant drawer </Typography> </Toolbar> </AppBar> <Drawer variant="permanent" open={open}> <DrawerHeader> <IconButton onClick={handleDrawerClose}> {theme.direction === 'rtl' ? <ChevronRightIcon /> : <ChevronLeftIcon />} </IconButton> </DrawerHeader> <Divider /> <List> {['Inbox', 'Starred', 'Send email', 'Drafts'].map((text, index) => ( <ListItem button key={text}> <ListItemIcon> {index % 2 === 0 ? <InboxIcon /> : <MailIcon />} </ListItemIcon> <ListItemText primary={text} /> </ListItem> ))} </List> <Divider /> <List> {['All mail', 'Trash', 'Spam'].map((text, index) => ( <ListItem button key={text}> <ListItemIcon> {index % 2 === 0 ? <InboxIcon /> : <MailIcon />} </ListItemIcon> <ListItemText primary={text} /> </ListItem> ))} </List> </Drawer> <Box component="main" sx={{ flexGrow: 1, p: 3 }}> <DrawerHeader /> <Typography paragraph> Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Rhoncus dolor purus non enim praesent elementum facilisis leo vel. Risus at ultrices mi tempus imperdiet. Semper risus in hendrerit gravida rutrum quisque non tellus. Convallis convallis tellus id interdum velit laoreet id donec ultrices. Odio morbi quis commodo odio aenean sed adipiscing. Amet nisl suscipit adipiscing bibendum est ultricies integer quis. Cursus euismod quis viverra nibh cras. Metus vulputate eu scelerisque felis imperdiet proin fermentum leo. Mauris commodo quis imperdiet massa tincidunt. Cras tincidunt lobortis feugiat vivamus at augue. At augue eget arcu dictum varius duis at consectetur lorem. Velit sed ullamcorper morbi tincidunt. Lorem donec massa sapien faucibus et molestie ac. </Typography> <Typography paragraph> Consequat mauris nunc congue nisi vitae suscipit. Fringilla est ullamcorper eget nulla facilisi etiam dignissim diam. Pulvinar elementum integer enim neque volutpat ac tincidunt. Ornare suspendisse sed nisi lacus sed viverra tellus. Purus sit amet volutpat consequat mauris. Elementum eu facilisis sed odio morbi. Euismod lacinia at quis risus sed vulputate odio. Morbi tincidunt ornare massa eget egestas purus viverra accumsan in. In hendrerit gravida rutrum quisque non tellus orci ac. Pellentesque nec nam aliquam sem et tortor. Habitant morbi tristique senectus et. Adipiscing elit duis tristique sollicitudin nibh sit. Ornare aenean euismod elementum nisi quis eleifend. Commodo viverra maecenas accumsan lacus vel facilisis. Nulla posuere sollicitudin aliquam ultrices sagittis orci a. </Typography> </Box> </Box> ); }
docs/data/material/components/drawers/MiniDrawer.js
1
https://github.com/mui/material-ui/commit/1db2ae2530d6a5ccb26c63ad7e9bbe5926ab0ea5
[ 0.9942092895507812, 0.10464168339967728, 0.00016334660176653415, 0.00023099272220861167, 0.3030184507369995 ]
{ "id": 13, "code_window": [ " {index % 2 === 0 ? <InboxIcon /> : <MailIcon />}\n", " </ListItemIcon>\n", " <ListItemText primary={text} />\n", " </ListItem>\n", " ))}\n", " </List>\n", " </Drawer>\n", " <Box component=\"main\" sx={{ flexGrow: 1, p: 3 }}>\n" ], "labels": [ "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " <ListItemText primary={text} sx={{ opacity: open ? 1 : 0 }} />\n", " </ListItemButton>\n" ], "file_path": "docs/data/material/components/drawers/MiniDrawer.tsx", "type": "replace", "edit_start_line_idx": 149 }
"use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; var _createSvgIcon = _interopRequireDefault(require("./utils/createSvgIcon")); var _jsxRuntime = require("react/jsx-runtime"); var _default = (0, _createSvgIcon.default)( /*#__PURE__*/(0, _jsxRuntime.jsx)("path", { d: "M6 19c0 1.1.9 2 2 2h8c1.1 0 2-.9 2-2V7H6v12zm3.17-6.41a.9959.9959 0 0 1 0-1.41c.39-.39 1.02-.39 1.41 0L12 12.59l1.41-1.41c.39-.39 1.02-.39 1.41 0s.39 1.02 0 1.41L13.41 14l1.41 1.41c.39.39.39 1.02 0 1.41s-1.02.39-1.41 0L12 15.41l-1.41 1.41c-.39.39-1.02.39-1.41 0a.9959.9959 0 0 1 0-1.41L10.59 14l-1.42-1.41zM18 4h-2.5l-.71-.71c-.18-.18-.44-.29-.7-.29H9.91c-.26 0-.52.11-.7.29L8.5 4H6c-.55 0-1 .45-1 1s.45 1 1 1h12c.55 0 1-.45 1-1s-.45-1-1-1z" }), 'DeleteForeverRounded'); exports.default = _default;
packages/mui-icons-material/lib/DeleteForeverRounded.js
0
https://github.com/mui/material-ui/commit/1db2ae2530d6a5ccb26c63ad7e9bbe5926ab0ea5
[ 0.00016641014371998608, 0.00016555369074922055, 0.00016469723777845502, 0.00016555369074922055, 8.564529707655311e-7 ]
{ "id": 13, "code_window": [ " {index % 2 === 0 ? <InboxIcon /> : <MailIcon />}\n", " </ListItemIcon>\n", " <ListItemText primary={text} />\n", " </ListItem>\n", " ))}\n", " </List>\n", " </Drawer>\n", " <Box component=\"main\" sx={{ flexGrow: 1, p: 3 }}>\n" ], "labels": [ "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " <ListItemText primary={text} sx={{ opacity: open ? 1 : 0 }} />\n", " </ListItemButton>\n" ], "file_path": "docs/data/material/components/drawers/MiniDrawer.tsx", "type": "replace", "edit_start_line_idx": 149 }
import createSvgIcon from './utils/createSvgIcon'; import { jsx as _jsx } from "react/jsx-runtime"; export default createSvgIcon( /*#__PURE__*/_jsx("path", { d: "M6.5 10.5h-2v1h2v-1zm13.5 0h-2v1h2v-1zm-7 2h-2v1.75c0 .41-.34.75-.75.75s-.75-.34-.75-.75v-4.5c0-.41.34-.75.75-.75s.75.34.75.75V11h2V9.75c0-.41.34-.75.75-.75s.75.34.75.75v4.5c0 .41-.34.75-.75.75s-.75-.34-.75-.75V12.5zm5 1.75c0 .41-.34.75-.75.75s-.75-.34-.75-.75V10c0-.55.45-1 1-1H20c.83 0 1.5.68 1.5 1.5v1c0 .82-.67 1.5-1.5 1.5h-2v1.25zM3 10c0-.55.45-1 1-1h2.5c.83 0 1.5.68 1.5 1.5v1c0 .82-.67 1.5-1.5 1.5h-2v1.25c0 .41-.34.75-.75.75S3 14.66 3 14.25V10z" }), 'PhpRounded');
packages/mui-icons-material/lib/esm/PhpRounded.js
0
https://github.com/mui/material-ui/commit/1db2ae2530d6a5ccb26c63ad7e9bbe5926ab0ea5
[ 0.0011506540467962623, 0.0011506540467962623, 0.0011506540467962623, 0.0011506540467962623, 0 ]
{ "id": 13, "code_window": [ " {index % 2 === 0 ? <InboxIcon /> : <MailIcon />}\n", " </ListItemIcon>\n", " <ListItemText primary={text} />\n", " </ListItem>\n", " ))}\n", " </List>\n", " </Drawer>\n", " <Box component=\"main\" sx={{ flexGrow: 1, p: 3 }}>\n" ], "labels": [ "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " <ListItemText primary={text} sx={{ opacity: open ? 1 : 0 }} />\n", " </ListItemButton>\n" ], "file_path": "docs/data/material/components/drawers/MiniDrawer.tsx", "type": "replace", "edit_start_line_idx": 149 }
<svg xmlns="http://www.w3.org/2000/svg" height="24" viewBox="0 0 24 24" width="24"><path d="M0 0h24v24H0z" fill="none"/><path d="M12 2c-4.97 0-9 4.03-9 9 0 4.17 2.84 7.67 6.69 8.69L12 22l2.31-2.31C18.16 18.67 21 15.17 21 11c0-4.97-4.03-9-9-9zm0 2c1.66 0 3 1.34 3 3s-1.34 3-3 3-3-1.34-3-3 1.34-3 3-3zm0 14.3c-2.5 0-4.71-1.28-6-3.22.03-1.99 4-3.08 6-3.08 1.99 0 5.97 1.09 6 3.08-1.29 1.94-3.5 3.22-6 3.22z"/></svg>
packages/mui-icons-material/material-icons/person_pin_24px.svg
0
https://github.com/mui/material-ui/commit/1db2ae2530d6a5ccb26c63ad7e9bbe5926ab0ea5
[ 0.00016721706197131425, 0.00016721706197131425, 0.00016721706197131425, 0.00016721706197131425, 0 ]
{ "id": 0, "code_window": [ "import * as tasks from 'vs/workbench/api/common/shared/tasks';\n", "import { SaveReason } from 'vs/workbench/common/editor';\n", "import { IRevealOptions, ITreeItem, IViewBadge } from 'vs/workbench/common/views';\n", "import { CallHierarchyItem } from 'vs/workbench/contrib/callHierarchy/common/callHierarchy';\n", "import { DebugConfigurationProviderTriggerKind, IAdapterDescriptor, IConfig, IDebugSessionReplMode } from 'vs/workbench/contrib/debug/common/debug';\n", "import { IInteractiveResponseErrorDetails } from 'vs/workbench/contrib/interactiveSession/common/interactiveSessionModel';\n", "import { IInteractiveProgress, IInteractiveSessionDynamicRequest, IInteractiveSessionFollowup, IInteractiveSessionReplyFollowup, IInteractiveSessionUserActionEvent, IInteractiveSlashCommand } from 'vs/workbench/contrib/interactiveSession/common/interactiveSessionService';\n", "import * as notebookCommon from 'vs/workbench/contrib/notebook/common/notebookCommon';\n", "import { CellExecutionUpdateType } from 'vs/workbench/contrib/notebook/common/notebookExecutionService';\n", "import { ICellExecutionComplete, ICellExecutionStateUpdate } from 'vs/workbench/contrib/notebook/common/notebookExecutionStateService';\n", "import { ICellRange } from 'vs/workbench/contrib/notebook/common/notebookRange';\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { IInteractiveProgress, IInteractiveResponseErrorDetails, IInteractiveSessionDynamicRequest, IInteractiveSessionFollowup, IInteractiveSessionReplyFollowup, IInteractiveSessionUserActionEvent, IInteractiveSlashCommand } from 'vs/workbench/contrib/interactiveSession/common/interactiveSessionService';\n" ], "file_path": "src/vs/workbench/api/common/extHost.protocol.ts", "type": "replace", "edit_start_line_idx": 53 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as dom from 'vs/base/browser/dom'; import { renderIcon } from 'vs/base/browser/ui/iconLabel/iconLabels'; import { IListVirtualDelegate } from 'vs/base/browser/ui/list/list'; import { IListAccessibilityProvider } from 'vs/base/browser/ui/list/listWidget'; import { ITreeNode, ITreeRenderer } from 'vs/base/browser/ui/tree/tree'; import { IntervalTimer } from 'vs/base/common/async'; import { Codicon } from 'vs/base/common/codicons'; import { Emitter, Event } from 'vs/base/common/event'; import { FuzzyScore } from 'vs/base/common/filters'; import { IMarkdownString, MarkdownString } from 'vs/base/common/htmlContent'; import { Disposable, DisposableStore, IDisposable } from 'vs/base/common/lifecycle'; import { ResourceMap } from 'vs/base/common/map'; import { FileAccess } from 'vs/base/common/network'; import { ThemeIcon } from 'vs/base/common/themables'; import { EditorExtensionsRegistry } from 'vs/editor/browser/editorExtensions'; import { CodeEditorWidget } from 'vs/editor/browser/widget/codeEditorWidget'; import { EDITOR_FONT_DEFAULTS, IEditorOptions } from 'vs/editor/common/config/editorOptions'; import { Range } from 'vs/editor/common/core/range'; import { ILanguageService } from 'vs/editor/common/languages/language'; import { ITextModel } from 'vs/editor/common/model'; import { IModelService } from 'vs/editor/common/services/model'; import { BracketMatchingController } from 'vs/editor/contrib/bracketMatching/browser/bracketMatching'; import { ContextMenuController } from 'vs/editor/contrib/contextmenu/browser/contextmenu'; import { IMarkdownRenderResult, MarkdownRenderer } from 'vs/editor/contrib/markdownRenderer/browser/markdownRenderer'; import { ViewportSemanticTokensContribution } from 'vs/editor/contrib/semanticTokens/browser/viewportSemanticTokens'; import { SmartSelectController } from 'vs/editor/contrib/smartSelect/browser/smartSelect'; import { WordHighlighterContribution } from 'vs/editor/contrib/wordHighlighter/browser/wordHighlighter'; import { localize } from 'vs/nls'; import { MenuWorkbenchToolBar } from 'vs/platform/actions/browser/toolbar'; import { MenuId } from 'vs/platform/actions/common/actions'; import { ICommandService } from 'vs/platform/commands/common/commands'; import { IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { IContextKeyService } from 'vs/platform/contextkey/common/contextkey'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { ServiceCollection } from 'vs/platform/instantiation/common/serviceCollection'; import { ILogService } from 'vs/platform/log/common/log'; import { defaultButtonStyles } from 'vs/platform/theme/browser/defaultStyles'; import { MenuPreventer } from 'vs/workbench/contrib/codeEditor/browser/menuPreventer'; import { SelectionClipboardContributionID } from 'vs/workbench/contrib/codeEditor/browser/selectionClipboard'; import { getSimpleEditorOptions } from 'vs/workbench/contrib/codeEditor/browser/simpleEditorOptions'; import { IInteractiveSessionCodeBlockActionContext } from 'vs/workbench/contrib/interactiveSession/browser/actions/interactiveSessionCodeblockActions'; import { InteractiveSessionFollowups } from 'vs/workbench/contrib/interactiveSession/browser/interactiveSessionFollowups'; import { InteractiveSessionEditorOptions } from 'vs/workbench/contrib/interactiveSession/browser/interactiveSessionOptions'; import { CONTEXT_RESPONSE_HAS_PROVIDER_ID, CONTEXT_RESPONSE_VOTE } from 'vs/workbench/contrib/interactiveSession/common/interactiveSessionContextKeys'; import { IInteractiveSessionReplyFollowup, IInteractiveSessionService, IInteractiveSlashCommand, InteractiveSessionVoteDirection } from 'vs/workbench/contrib/interactiveSession/common/interactiveSessionService'; import { IInteractiveRequestViewModel, IInteractiveResponseViewModel, IInteractiveWelcomeMessageViewModel, isRequestVM, isResponseVM, isWelcomeVM } from 'vs/workbench/contrib/interactiveSession/common/interactiveSessionViewModel'; import { getNWords } from 'vs/workbench/contrib/interactiveSession/common/interactiveSessionWordCounter'; const $ = dom.$; export type InteractiveTreeItem = IInteractiveRequestViewModel | IInteractiveResponseViewModel | IInteractiveWelcomeMessageViewModel; interface IInteractiveListItemTemplate { rowContainer: HTMLElement; titleToolbar: MenuWorkbenchToolBar; avatar: HTMLElement; username: HTMLElement; value: HTMLElement; contextKeyService: IContextKeyService; templateDisposables: IDisposable; elementDisposables: DisposableStore; } interface IItemHeightChangeParams { element: InteractiveTreeItem; height: number; } const forceVerboseLayoutTracing = false; export interface IInteractiveSessionRendererDelegate { getListLength(): number; getSlashCommands(): IInteractiveSlashCommand[]; } export class InteractiveListItemRenderer extends Disposable implements ITreeRenderer<InteractiveTreeItem, FuzzyScore, IInteractiveListItemTemplate> { static readonly cursorCharacter = '\u258c'; static readonly ID = 'item'; private readonly renderer: MarkdownRenderer; protected readonly _onDidClickFollowup = this._register(new Emitter<IInteractiveSessionReplyFollowup>()); readonly onDidClickFollowup: Event<IInteractiveSessionReplyFollowup> = this._onDidClickFollowup.event; protected readonly _onDidChangeItemHeight = this._register(new Emitter<IItemHeightChangeParams>()); readonly onDidChangeItemHeight: Event<IItemHeightChangeParams> = this._onDidChangeItemHeight.event; private readonly _editorPool: EditorPool; private _currentLayoutWidth: number = 0; constructor( private readonly editorOptions: InteractiveSessionEditorOptions, private readonly delegate: IInteractiveSessionRendererDelegate, @IInstantiationService private readonly instantiationService: IInstantiationService, @IConfigurationService private readonly configService: IConfigurationService, @ILogService private readonly logService: ILogService, @ICommandService private readonly commandService: ICommandService, @IContextKeyService private readonly contextKeyService: IContextKeyService, @IInteractiveSessionService private readonly interactiveSessionService: IInteractiveSessionService, ) { super(); this.renderer = this.instantiationService.createInstance(MarkdownRenderer, {}); this._editorPool = this._register(this.instantiationService.createInstance(EditorPool, this.editorOptions)); } get templateId(): string { return InteractiveListItemRenderer.ID; } private traceLayout(method: string, message: string) { if (forceVerboseLayoutTracing) { this.logService.info(`InteractiveListItemRenderer#${method}: ${message}`); } else { this.logService.trace(`InteractiveListItemRenderer#${method}: ${message}`); } } private shouldRenderProgressively(element: IInteractiveResponseViewModel): boolean { return !this.configService.getValue('interactive.experimental.disableProgressiveRendering') && element.progressiveResponseRenderingEnabled; } private getProgressiveRenderRate(element: IInteractiveResponseViewModel): number { const configuredRate = this.configService.getValue('interactive.experimental.progressiveRenderingRate'); if (typeof configuredRate === 'number') { return configuredRate; } if (element.isComplete) { return 60; } if (element.contentUpdateTimings && element.contentUpdateTimings.impliedWordLoadRate) { // This doesn't account for dead time after the last update. When the previous update is the final one and the model is only waiting for followupQuestions, that's good. // When there was one quick update and then you are waiting longer for the next one, that's not good since the rate should be decreasing. // If it's an issue, we can change this to be based on the total time from now to the beginning. const rateBoost = 1.5; return element.contentUpdateTimings.impliedWordLoadRate * rateBoost; } return 8; } layout(width: number): void { this._currentLayoutWidth = width - 40; // TODO Padding this._editorPool.inUse.forEach(editor => { editor.layout(this._currentLayoutWidth); }); } renderTemplate(container: HTMLElement): IInteractiveListItemTemplate { const templateDisposables = new DisposableStore(); const rowContainer = dom.append(container, $('.interactive-item-container')); const header = dom.append(rowContainer, $('.header')); const user = dom.append(header, $('.user')); const avatar = dom.append(user, $('.avatar')); const username = dom.append(user, $('h3.username')); const value = dom.append(rowContainer, $('.value')); const elementDisposables = new DisposableStore(); const contextKeyService = templateDisposables.add(this.contextKeyService.createScoped(rowContainer)); const scopedInstantiationService = this.instantiationService.createChild(new ServiceCollection([IContextKeyService, contextKeyService])); const titleToolbar = templateDisposables.add(scopedInstantiationService.createInstance(MenuWorkbenchToolBar, header, MenuId.InteractiveSessionTitle, { menuOptions: { shouldForwardArgs: true } })); const template: IInteractiveListItemTemplate = { avatar, username, value, rowContainer, elementDisposables, titleToolbar, templateDisposables, contextKeyService }; return template; } renderElement(node: ITreeNode<InteractiveTreeItem, FuzzyScore>, index: number, templateData: IInteractiveListItemTemplate): void { const { element } = node; const kind = isRequestVM(element) ? 'request' : isResponseVM(element) ? 'response' : 'welcome'; this.traceLayout('renderElement', `${kind}, index=${index}`); CONTEXT_RESPONSE_HAS_PROVIDER_ID.bindTo(templateData.contextKeyService).set(isResponseVM(element) && !!element.providerResponseId && !element.isPlaceholder); if (isResponseVM(element)) { CONTEXT_RESPONSE_VOTE.bindTo(templateData.contextKeyService).set(element.vote === InteractiveSessionVoteDirection.Up ? 'up' : element.vote === InteractiveSessionVoteDirection.Down ? 'down' : ''); } else { CONTEXT_RESPONSE_VOTE.bindTo(templateData.contextKeyService).set(''); } templateData.titleToolbar.context = element; templateData.rowContainer.classList.toggle('interactive-request', isRequestVM(element)); templateData.rowContainer.classList.toggle('interactive-response', isResponseVM(element)); templateData.rowContainer.classList.toggle('interactive-welcome', isWelcomeVM(element)); templateData.username.textContent = element.username; if (element.avatarIconUri) { const avatarIcon = dom.$<HTMLImageElement>('img.icon'); avatarIcon.src = FileAccess.uriToBrowserUri(element.avatarIconUri).toString(true); templateData.avatar.replaceChildren(avatarIcon); } else { const defaultIcon = isRequestVM(element) ? Codicon.account : Codicon.hubot; const avatarIcon = dom.$(ThemeIcon.asCSSSelector(defaultIcon)); templateData.avatar.replaceChildren(avatarIcon); } // Do a progressive render if // - This the last response in the list // - And the response is not complete // - Or, we previously started a progressive rendering of this element (if the element is complete, we will finish progressive rendering with a very fast rate) // - And, the feature is not disabled in configuration if (isResponseVM(element) && index === this.delegate.getListLength() - 1 && (!element.isComplete || element.renderData) && this.shouldRenderProgressively(element)) { this.traceLayout('renderElement', `start progressive render ${kind}, index=${index}`); const progressiveRenderingDisposables = templateData.elementDisposables.add(new DisposableStore()); const timer = templateData.elementDisposables.add(new IntervalTimer()); const runProgressiveRender = (initial?: boolean) => { try { if (this.doNextProgressiveRender(element, index, templateData, !!initial, progressiveRenderingDisposables)) { timer.cancel(); } } catch (err) { // Kill the timer if anything went wrong, avoid getting stuck in a nasty rendering loop. timer.cancel(); throw err; } }; runProgressiveRender(true); timer.cancelAndSet(runProgressiveRender, 50); } else if (isResponseVM(element)) { this.basicRenderElement(element.response.value, element, index, templateData, element.isCanceled); } else if (isRequestVM(element)) { this.basicRenderElement(element.messageText, element, index, templateData); } else { this.renderWelcomeMessage(element, templateData); } } private basicRenderElement(markdownValue: string, element: InteractiveTreeItem, index: number, templateData: IInteractiveListItemTemplate, fillInIncompleteTokens = false) { const result = this.renderMarkdown(new MarkdownString(markdownValue), element, templateData.elementDisposables, templateData, fillInIncompleteTokens); dom.clearNode(templateData.value); templateData.value.appendChild(result.element); templateData.elementDisposables.add(result); if (isResponseVM(element) && element.errorDetails?.message) { const errorDetails = dom.append(templateData.value, $('.interactive-response-error-details', undefined, renderIcon(Codicon.error))); errorDetails.appendChild($('span', undefined, element.errorDetails.message)); } if (isResponseVM(element) && element.commandFollowups?.length) { const followupsContainer = dom.append(templateData.value, $('.interactive-response-followups')); templateData.elementDisposables.add(new InteractiveSessionFollowups( followupsContainer, element.commandFollowups, defaultButtonStyles, followup => { this.interactiveSessionService.notifyUserAction({ providerId: element.providerId, action: { kind: 'command', command: followup } }); return this.commandService.executeCommand(followup.commandId, ...(followup.args ?? [])); })); } } private renderWelcomeMessage(element: IInteractiveWelcomeMessageViewModel, templateData: IInteractiveListItemTemplate) { dom.clearNode(templateData.value); const slashCommands = this.delegate.getSlashCommands(); for (const item of element.content) { if (Array.isArray(item)) { templateData.elementDisposables.add(new InteractiveSessionFollowups( templateData.value, item, undefined, followup => this._onDidClickFollowup.fire(followup))); } else { const result = this.renderMarkdown(item as IMarkdownString, element, templateData.elementDisposables, templateData); for (const codeElement of result.element.querySelectorAll('code')) { if (codeElement.textContent && slashCommands.find(command => codeElement.textContent === `/${command.command}`)) { codeElement.classList.add('interactive-slash-command'); } } templateData.value.appendChild(result.element); templateData.elementDisposables.add(result); } } } private doNextProgressiveRender(element: IInteractiveResponseViewModel, index: number, templateData: IInteractiveListItemTemplate, isInRenderElement: boolean, disposables: DisposableStore): boolean { disposables.clear(); let isFullyRendered = false; if (element.isCanceled) { this.traceLayout('runProgressiveRender', `canceled, index=${index}`); element.renderData = undefined; this.basicRenderElement(element.response.value, element, index, templateData, true); isFullyRendered = true; } else { // TODO- this method has the side effect of updating element.renderData const toRender = this.getProgressiveMarkdownToRender(element); isFullyRendered = !!element.renderData?.isFullyRendered; if (isFullyRendered) { // We've reached the end of the available content, so do a normal render this.traceLayout('runProgressiveRender', `end progressive render, index=${index}`); if (element.isComplete) { this.traceLayout('runProgressiveRender', `and disposing renderData, response is complete, index=${index}`); element.renderData = undefined; } else { this.traceLayout('runProgressiveRender', `Rendered all available words, but model is not complete.`); } disposables.clear(); this.basicRenderElement(element.response.value, element, index, templateData, !element.isComplete); } else if (toRender) { // Doing the progressive render const plusCursor = toRender.match(/```.*$/) ? toRender + `\n${InteractiveListItemRenderer.cursorCharacter}` : toRender + ` ${InteractiveListItemRenderer.cursorCharacter}`; const result = this.renderMarkdown(new MarkdownString(plusCursor), element, disposables, templateData, true); dom.clearNode(templateData.value); templateData.value.appendChild(result.element); disposables.add(result); } else { // Nothing new to render, not done, keep waiting return false; } } // Some render happened - update the height const height = templateData.rowContainer.offsetHeight; element.currentRenderedHeight = height; if (!isInRenderElement) { this._onDidChangeItemHeight.fire({ element, height: templateData.rowContainer.offsetHeight }); } return !!isFullyRendered; } private renderMarkdown(markdown: IMarkdownString, element: InteractiveTreeItem, disposables: DisposableStore, templateData: IInteractiveListItemTemplate, fillInIncompleteTokens = false): IMarkdownRenderResult { const disposablesList: IDisposable[] = []; let codeBlockIndex = 0; // TODO if the slash commands stay completely dynamic, this isn't quite right const slashCommands = this.delegate.getSlashCommands(); const usedSlashCommand = slashCommands.find(s => markdown.value.startsWith(`/${s.command} `)); const toRender = usedSlashCommand ? markdown.value.slice(usedSlashCommand.command.length + 2) : markdown.value; markdown = new MarkdownString(toRender); const result = this.renderer.render(markdown, { fillInIncompleteTokens, codeBlockRendererSync: (languageId, text) => { const ref = this.renderCodeBlock({ languageId, text, codeBlockIndex: codeBlockIndex++, element, parentContextKeyService: templateData.contextKeyService }, disposables); // Attach this after updating text/layout of the editor, so it should only be fired when the size updates later (horizontal scrollbar, wrapping) // not during a renderElement OR a progressive render (when we will be firing this event anyway at the end of the render) disposables.add(ref.object.onDidChangeContentHeight(() => { ref.object.layout(this._currentLayoutWidth); this._onDidChangeItemHeight.fire({ element, height: templateData.rowContainer.offsetHeight }); })); disposablesList.push(ref); return ref.object.element; } }); if (usedSlashCommand) { const slashCommandElement = $('span.interactive-slash-command', { title: usedSlashCommand.detail }, `/${usedSlashCommand.command} `); if (result.element.firstChild?.nodeName.toLowerCase() === 'p') { result.element.firstChild.insertBefore(slashCommandElement, result.element.firstChild.firstChild); } else { result.element.insertBefore($('p', undefined, slashCommandElement), result.element.firstChild); } } disposablesList.reverse().forEach(d => disposables.add(d)); return result; } private renderCodeBlock(data: IInteractiveResultCodeBlockData, disposables: DisposableStore): IDisposableReference<IInteractiveResultCodeBlockPart> { const ref = this._editorPool.get(); const editorInfo = ref.object; editorInfo.render(data, this._currentLayoutWidth); return ref; } private getProgressiveMarkdownToRender(element: IInteractiveResponseViewModel): string | undefined { const renderData = element.renderData ?? { renderedWordCount: 0, lastRenderTime: 0 }; const rate = this.getProgressiveRenderRate(element); const numWordsToRender = renderData.lastRenderTime === 0 ? 1 : renderData.renderedWordCount + // Additional words to render beyond what's already rendered Math.floor((Date.now() - renderData.lastRenderTime) / 1000 * rate); if (numWordsToRender === renderData.renderedWordCount) { return undefined; } const result = getNWords(element.response.value, numWordsToRender); element.renderData = { renderedWordCount: result.actualWordCount, lastRenderTime: Date.now(), isFullyRendered: result.isFullString }; return result.value; } disposeElement(node: ITreeNode<InteractiveTreeItem, FuzzyScore>, index: number, templateData: IInteractiveListItemTemplate): void { templateData.elementDisposables.clear(); } disposeTemplate(templateData: IInteractiveListItemTemplate): void { templateData.templateDisposables.dispose(); } } export class InteractiveSessionListDelegate implements IListVirtualDelegate<InteractiveTreeItem> { constructor( @ILogService private readonly logService: ILogService ) { } private _traceLayout(method: string, message: string) { if (forceVerboseLayoutTracing) { this.logService.info(`InteractiveSessionListDelegate#${method}: ${message}`); } else { this.logService.trace(`InteractiveSessionListDelegate#${method}: ${message}`); } } getHeight(element: InteractiveTreeItem): number { const kind = isRequestVM(element) ? 'request' : 'response'; const height = ('currentRenderedHeight' in element ? element.currentRenderedHeight : undefined) ?? 200; this._traceLayout('getHeight', `${kind}, height=${height}`); return height; } getTemplateId(element: InteractiveTreeItem): string { return InteractiveListItemRenderer.ID; } hasDynamicHeight(element: InteractiveTreeItem): boolean { return true; } } export class InteractiveSessionAccessibilityProvider implements IListAccessibilityProvider<InteractiveTreeItem> { getWidgetAriaLabel(): string { return localize('interactiveSession', "Interactive Session"); } getAriaLabel(element: InteractiveTreeItem): string { if (isRequestVM(element)) { return localize('interactiveRequest', "Request: {0}", element.messageText); } if (isResponseVM(element)) { return localize('interactiveResponse', "Response: {0}", element.response.value); } return ''; } } interface IInteractiveResultCodeBlockData { text: string; languageId: string; codeBlockIndex: number; element: InteractiveTreeItem; parentContextKeyService: IContextKeyService; } interface IInteractiveResultCodeBlockPart { readonly onDidChangeContentHeight: Event<number>; readonly element: HTMLElement; readonly textModel: ITextModel; layout(width: number): void; render(data: IInteractiveResultCodeBlockData, width: number): void; dispose(): void; } export interface IInteractiveResultCodeBlockInfo { providerId: string; responseId: string; codeBlockIndex: number; } export const codeBlockInfosByModelUri = new ResourceMap<IInteractiveResultCodeBlockInfo>(); class CodeBlockPart extends Disposable implements IInteractiveResultCodeBlockPart { private readonly _onDidChangeContentHeight = this._register(new Emitter<number>()); public readonly onDidChangeContentHeight = this._onDidChangeContentHeight.event; private readonly editor: CodeEditorWidget; private readonly toolbar: MenuWorkbenchToolBar; private readonly contextKeyService: IContextKeyService; public readonly textModel: ITextModel; public readonly element: HTMLElement; constructor( private readonly options: InteractiveSessionEditorOptions, @IInstantiationService instantiationService: IInstantiationService, @IContextKeyService contextKeyService: IContextKeyService, @ILanguageService private readonly languageService: ILanguageService, @IModelService private readonly modelService: IModelService, ) { super(); this.element = $('.interactive-result-editor-wrapper'); this.contextKeyService = this._register(contextKeyService.createScoped(this.element)); const scopedInstantiationService = instantiationService.createChild(new ServiceCollection([IContextKeyService, this.contextKeyService])); this.toolbar = this._register(scopedInstantiationService.createInstance(MenuWorkbenchToolBar, this.element, MenuId.InteractiveSessionCodeBlock, { menuOptions: { shouldForwardArgs: true } })); const editorElement = dom.append(this.element, $('.interactive-result-editor')); this.editor = this._register(scopedInstantiationService.createInstance(CodeEditorWidget, editorElement, { ...getSimpleEditorOptions(), readOnly: true, lineNumbers: 'off', selectOnLineNumbers: true, scrollBeyondLastLine: false, lineDecorationsWidth: 8, dragAndDrop: false, padding: { top: 2, bottom: 2 }, mouseWheelZoom: false, scrollbar: { alwaysConsumeMouseWheel: false }, ...this.getEditorOptionsFromConfig() }, { isSimpleWidget: true, contributions: EditorExtensionsRegistry.getSomeEditorContributions([ MenuPreventer.ID, SelectionClipboardContributionID, ContextMenuController.ID, WordHighlighterContribution.ID, ViewportSemanticTokensContribution.ID, BracketMatchingController.ID, SmartSelectController.ID, ]) })); this._register(this.options.onDidChange(() => { this.editor.updateOptions(this.getEditorOptionsFromConfig()); })); this._register(this.editor.onDidContentSizeChange(e => { if (e.contentHeightChanged) { this._onDidChangeContentHeight.fire(e.contentHeight); } })); this._register(this.editor.onDidBlurEditorWidget(() => { WordHighlighterContribution.get(this.editor)?.stopHighlighting(); })); this._register(this.editor.onDidFocusEditorWidget(() => { WordHighlighterContribution.get(this.editor)?.restoreViewState(true); })); const vscodeLanguageId = this.languageService.getLanguageIdByLanguageName('javascript'); this.textModel = this._register(this.modelService.createModel('', this.languageService.createById(vscodeLanguageId), undefined)); this.editor.setModel(this.textModel); } private getEditorOptionsFromConfig(): IEditorOptions { return { wordWrap: this.options.configuration.resultEditor.wordWrap, bracketPairColorization: this.options.configuration.resultEditor.bracketPairColorization, fontFamily: this.options.configuration.resultEditor.fontFamily === 'default' ? EDITOR_FONT_DEFAULTS.fontFamily : this.options.configuration.resultEditor.fontFamily, fontSize: this.options.configuration.resultEditor.fontSize, fontWeight: this.options.configuration.resultEditor.fontWeight, lineHeight: this.options.configuration.resultEditor.lineHeight, }; } layout(width: number): void { const realContentHeight = this.editor.getContentHeight(); const editorBorder = 2; this.editor.layout({ width: width - editorBorder, height: realContentHeight }); } render(data: IInteractiveResultCodeBlockData, width: number): void { this.contextKeyService.updateParent(data.parentContextKeyService); if (this.options.configuration.resultEditor.wordWrap === 'on') { // Intialize the editor with the new proper width so that getContentHeight // will be computed correctly in the next call to layout() this.layout(width); } this.setText(data.text); this.setLanguage(data.languageId); this.layout(width); if (isResponseVM(data.element) && data.element.providerResponseId) { // For telemetry reporting codeBlockInfosByModelUri.set(this.textModel.uri, { providerId: data.element.providerId, responseId: data.element.providerResponseId, codeBlockIndex: data.codeBlockIndex }); } else { codeBlockInfosByModelUri.delete(this.textModel.uri); } this.toolbar.context = <IInteractiveSessionCodeBlockActionContext>{ code: data.text, codeBlockIndex: data.codeBlockIndex, element: data.element }; } private setText(newText: string): void { let currentText = this.textModel.getLinesContent().join('\n'); if (newText === currentText) { return; } let removedChars = 0; if (currentText.endsWith(` ${InteractiveListItemRenderer.cursorCharacter}`)) { removedChars = 2; } else if (currentText.endsWith(InteractiveListItemRenderer.cursorCharacter)) { removedChars = 1; } if (removedChars > 0) { currentText = currentText.slice(0, currentText.length - removedChars); } if (newText.startsWith(currentText)) { const text = newText.slice(currentText.length); const lastLine = this.textModel.getLineCount(); const lastCol = this.textModel.getLineMaxColumn(lastLine); const insertAtCol = lastCol - removedChars; this.textModel.applyEdits([{ range: new Range(lastLine, insertAtCol, lastLine, lastCol), text }]); } else { // console.log(`Failed to optimize setText`); this.textModel.setValue(newText); } } private setLanguage(languageId: string): void { const vscodeLanguageId = this.languageService.getLanguageIdByLanguageName(languageId); if (vscodeLanguageId) { this.textModel.setLanguage(vscodeLanguageId); } } } interface IDisposableReference<T> extends IDisposable { object: T; } class EditorPool extends Disposable { private _pool: ResourcePool<IInteractiveResultCodeBlockPart>; public get inUse(): ReadonlySet<IInteractiveResultCodeBlockPart> { return this._pool.inUse; } constructor( private readonly options: InteractiveSessionEditorOptions, @IInstantiationService private readonly instantiationService: IInstantiationService, ) { super(); this._pool = this._register(new ResourcePool(() => this.editorFactory())); // TODO listen to changes on options } private editorFactory(): IInteractiveResultCodeBlockPart { return this.instantiationService.createInstance(CodeBlockPart, this.options); } get(): IDisposableReference<IInteractiveResultCodeBlockPart> { const object = this._pool.get(); return { object, dispose: () => this._pool.release(object) }; } } // TODO does something in lifecycle.ts cover this? class ResourcePool<T extends IDisposable> extends Disposable { private readonly pool: T[] = []; private _inUse = new Set<T>; public get inUse(): ReadonlySet<T> { return this._inUse; } constructor( private readonly _itemFactory: () => T, ) { super(); } get(): T { if (this.pool.length > 0) { const item = this.pool.pop()!; this._inUse.add(item); return item; } const item = this._register(this._itemFactory()); this._inUse.add(item); return item; } release(item: T): void { this._inUse.delete(item); this.pool.push(item); } }
src/vs/workbench/contrib/interactiveSession/browser/interactiveSessionListRenderer.ts
1
https://github.com/microsoft/vscode/commit/324d1a25760c6abeb4a0492c0c5a22795b695bf4
[ 0.018477795645594597, 0.0008340140921063721, 0.000163562290254049, 0.0001714289392111823, 0.0024624718353152275 ]
{ "id": 0, "code_window": [ "import * as tasks from 'vs/workbench/api/common/shared/tasks';\n", "import { SaveReason } from 'vs/workbench/common/editor';\n", "import { IRevealOptions, ITreeItem, IViewBadge } from 'vs/workbench/common/views';\n", "import { CallHierarchyItem } from 'vs/workbench/contrib/callHierarchy/common/callHierarchy';\n", "import { DebugConfigurationProviderTriggerKind, IAdapterDescriptor, IConfig, IDebugSessionReplMode } from 'vs/workbench/contrib/debug/common/debug';\n", "import { IInteractiveResponseErrorDetails } from 'vs/workbench/contrib/interactiveSession/common/interactiveSessionModel';\n", "import { IInteractiveProgress, IInteractiveSessionDynamicRequest, IInteractiveSessionFollowup, IInteractiveSessionReplyFollowup, IInteractiveSessionUserActionEvent, IInteractiveSlashCommand } from 'vs/workbench/contrib/interactiveSession/common/interactiveSessionService';\n", "import * as notebookCommon from 'vs/workbench/contrib/notebook/common/notebookCommon';\n", "import { CellExecutionUpdateType } from 'vs/workbench/contrib/notebook/common/notebookExecutionService';\n", "import { ICellExecutionComplete, ICellExecutionStateUpdate } from 'vs/workbench/contrib/notebook/common/notebookExecutionStateService';\n", "import { ICellRange } from 'vs/workbench/contrib/notebook/common/notebookRange';\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { IInteractiveProgress, IInteractiveResponseErrorDetails, IInteractiveSessionDynamicRequest, IInteractiveSessionFollowup, IInteractiveSessionReplyFollowup, IInteractiveSessionUserActionEvent, IInteractiveSlashCommand } from 'vs/workbench/contrib/interactiveSession/common/interactiveSessionService';\n" ], "file_path": "src/vs/workbench/api/common/extHost.protocol.ts", "type": "replace", "edit_start_line_idx": 53 }
{ "name": "emmet", "displayName": "Emmet", "description": "%description%", "version": "1.0.0", "publisher": "vscode", "license": "MIT", "engines": { "vscode": "^1.13.0" }, "icon": "images/icon.png", "categories": [ "Other" ], "repository": { "type": "git", "url": "https://github.com/microsoft/vscode.git" }, "activationEvents": [ "onCommand:emmet.expandAbbreviation", "onLanguage" ], "main": "./out/node/emmetNodeMain", "browser": "./dist/browser/emmetBrowserMain", "contributes": { "configuration": { "type": "object", "title": "Emmet", "properties": { "emmet.showExpandedAbbreviation": { "type": [ "string" ], "enum": [ "never", "always", "inMarkupAndStylesheetFilesOnly" ], "default": "always", "markdownDescription": "%emmetShowExpandedAbbreviation%" }, "emmet.showAbbreviationSuggestions": { "type": "boolean", "default": true, "scope": "language-overridable", "markdownDescription": "%emmetShowAbbreviationSuggestions%" }, "emmet.includeLanguages": { "type": "object", "additionalProperties": { "type": "string" }, "default": {}, "markdownDescription": "%emmetIncludeLanguages%" }, "emmet.variables": { "type": "object", "properties": { "lang": { "type": "string", "default": "en" }, "charset": { "type": "string", "default": "UTF-8" } }, "additionalProperties": { "type": "string" }, "default": {}, "markdownDescription": "%emmetVariables%" }, "emmet.syntaxProfiles": { "type": "object", "default": {}, "markdownDescription": "%emmetSyntaxProfiles%" }, "emmet.excludeLanguages": { "type": "array", "items": { "type": "string" }, "default": [ "markdown" ], "markdownDescription": "%emmetExclude%" }, "emmet.extensionsPath": { "type": "array", "items": { "type": "string", "markdownDescription": "%emmetExtensionsPathItem%" }, "default": [], "scope": "machine-overridable", "markdownDescription": "%emmetExtensionsPath%" }, "emmet.triggerExpansionOnTab": { "type": "boolean", "default": false, "scope": "language-overridable", "markdownDescription": "%emmetTriggerExpansionOnTab%" }, "emmet.useInlineCompletions": { "type": "boolean", "default": false, "markdownDescription": "%emmetUseInlineCompletions%" }, "emmet.preferences": { "type": "object", "default": {}, "markdownDescription": "%emmetPreferences%", "properties": { "css.intUnit": { "type": "string", "default": "px", "markdownDescription": "%emmetPreferencesIntUnit%" }, "css.floatUnit": { "type": "string", "default": "em", "markdownDescription": "%emmetPreferencesFloatUnit%" }, "css.propertyEnd": { "type": "string", "default": ";", "markdownDescription": "%emmetPreferencesCssAfter%" }, "sass.propertyEnd": { "type": "string", "default": "", "markdownDescription": "%emmetPreferencesSassAfter%" }, "stylus.propertyEnd": { "type": "string", "default": "", "markdownDescription": "%emmetPreferencesStylusAfter%" }, "css.valueSeparator": { "type": "string", "default": ": ", "markdownDescription": "%emmetPreferencesCssBetween%" }, "sass.valueSeparator": { "type": "string", "default": ": ", "markdownDescription": "%emmetPreferencesSassBetween%" }, "stylus.valueSeparator": { "type": "string", "default": " ", "markdownDescription": "%emmetPreferencesStylusBetween%" }, "bem.elementSeparator": { "type": "string", "default": "__", "markdownDescription": "%emmetPreferencesBemElementSeparator%" }, "bem.modifierSeparator": { "type": "string", "default": "_", "markdownDescription": "%emmetPreferencesBemModifierSeparator%" }, "filter.commentBefore": { "type": "string", "default": "", "markdownDescription": "%emmetPreferencesFilterCommentBefore%" }, "filter.commentAfter": { "type": "string", "default": "\n<!-- /[#ID][.CLASS] -->", "markdownDescription": "%emmetPreferencesFilterCommentAfter%" }, "filter.commentTrigger": { "type": "array", "default": [ "id", "class" ], "markdownDescription": "%emmetPreferencesFilterCommentTrigger%" }, "format.noIndentTags": { "type": "array", "default": [ "html" ], "markdownDescription": "%emmetPreferencesFormatNoIndentTags%" }, "format.forceIndentationForTags": { "type": "array", "default": [ "body" ], "markdownDescription": "%emmetPreferencesFormatForceIndentTags%" }, "profile.allowCompactBoolean": { "type": "boolean", "default": false, "markdownDescription": "%emmetPreferencesAllowCompactBoolean%" }, "css.webkitProperties": { "type": "string", "default": null, "markdownDescription": "%emmetPreferencesCssWebkitProperties%" }, "css.mozProperties": { "type": "string", "default": null, "markdownDescription": "%emmetPreferencesCssMozProperties%" }, "css.oProperties": { "type": "string", "default": null, "markdownDescription": "%emmetPreferencesCssOProperties%" }, "css.msProperties": { "type": "string", "default": null, "markdownDescription": "%emmetPreferencesCssMsProperties%" }, "css.fuzzySearchMinScore": { "type": "number", "default": 0.3, "markdownDescription": "%emmetPreferencesCssFuzzySearchMinScore%" }, "output.inlineBreak": { "type": "number", "default": 0, "markdownDescription": "%emmetPreferencesOutputInlineBreak%" }, "output.reverseAttributes": { "type": "boolean", "default": false, "markdownDescription": "%emmetPreferencesOutputReverseAttributes%" }, "output.selfClosingStyle": { "type": "string", "enum": [ "html", "xhtml", "xml" ], "default": "html", "markdownDescription": "%emmetPreferencesOutputSelfClosingStyle%" }, "css.color.short": { "type": "boolean", "default": true, "markdownDescription": "%emmetPreferencesCssColorShort%" } } }, "emmet.showSuggestionsAsSnippets": { "type": "boolean", "default": false, "markdownDescription": "%emmetShowSuggestionsAsSnippets%" }, "emmet.optimizeStylesheetParsing": { "type": "boolean", "default": true, "markdownDescription": "%emmetOptimizeStylesheetParsing%" } } }, "commands": [ { "command": "editor.emmet.action.wrapWithAbbreviation", "title": "%command.wrapWithAbbreviation%", "category": "Emmet" }, { "command": "editor.emmet.action.removeTag", "title": "%command.removeTag%", "category": "Emmet" }, { "command": "editor.emmet.action.updateTag", "title": "%command.updateTag%", "category": "Emmet" }, { "command": "editor.emmet.action.matchTag", "title": "%command.matchTag%", "category": "Emmet" }, { "command": "editor.emmet.action.balanceIn", "title": "%command.balanceIn%", "category": "Emmet" }, { "command": "editor.emmet.action.balanceOut", "title": "%command.balanceOut%", "category": "Emmet" }, { "command": "editor.emmet.action.prevEditPoint", "title": "%command.prevEditPoint%", "category": "Emmet" }, { "command": "editor.emmet.action.nextEditPoint", "title": "%command.nextEditPoint%", "category": "Emmet" }, { "command": "editor.emmet.action.mergeLines", "title": "%command.mergeLines%", "category": "Emmet" }, { "command": "editor.emmet.action.selectPrevItem", "title": "%command.selectPrevItem%", "category": "Emmet" }, { "command": "editor.emmet.action.selectNextItem", "title": "%command.selectNextItem%", "category": "Emmet" }, { "command": "editor.emmet.action.splitJoinTag", "title": "%command.splitJoinTag%", "category": "Emmet" }, { "command": "editor.emmet.action.toggleComment", "title": "%command.toggleComment%", "category": "Emmet" }, { "command": "editor.emmet.action.evaluateMathExpression", "title": "%command.evaluateMathExpression%", "category": "Emmet" }, { "command": "editor.emmet.action.updateImageSize", "title": "%command.updateImageSize%", "category": "Emmet" }, { "command": "editor.emmet.action.incrementNumberByOneTenth", "title": "%command.incrementNumberByOneTenth%", "category": "Emmet" }, { "command": "editor.emmet.action.incrementNumberByOne", "title": "%command.incrementNumberByOne%", "category": "Emmet" }, { "command": "editor.emmet.action.incrementNumberByTen", "title": "%command.incrementNumberByTen%", "category": "Emmet" }, { "command": "editor.emmet.action.decrementNumberByOneTenth", "title": "%command.decrementNumberByOneTenth%", "category": "Emmet" }, { "command": "editor.emmet.action.decrementNumberByOne", "title": "%command.decrementNumberByOne%", "category": "Emmet" }, { "command": "editor.emmet.action.decrementNumberByTen", "title": "%command.decrementNumberByTen%", "category": "Emmet" }, { "command": "editor.emmet.action.reflectCSSValue", "title": "%command.reflectCSSValue%", "category": "Emmet" }, { "command": "workbench.action.showEmmetCommands", "title": "%command.showEmmetCommands%", "category": "" } ], "menus": { "commandPalette": [ { "command": "editor.emmet.action.wrapWithAbbreviation", "when": "!activeEditorIsReadonly" }, { "command": "editor.emmet.action.removeTag", "when": "!activeEditorIsReadonly" }, { "command": "editor.emmet.action.updateTag", "when": "!activeEditorIsReadonly" }, { "command": "editor.emmet.action.matchTag", "when": "!activeEditorIsReadonly" }, { "command": "editor.emmet.action.balanceIn", "when": "!activeEditorIsReadonly" }, { "command": "editor.emmet.action.balanceOut", "when": "!activeEditorIsReadonly" }, { "command": "editor.emmet.action.prevEditPoint", "when": "!activeEditorIsReadonly" }, { "command": "editor.emmet.action.nextEditPoint", "when": "!activeEditorIsReadonly" }, { "command": "editor.emmet.action.mergeLines", "when": "!activeEditorIsReadonly" }, { "command": "editor.emmet.action.selectPrevItem", "when": "!activeEditorIsReadonly" }, { "command": "editor.emmet.action.selectNextItem", "when": "!activeEditorIsReadonly" }, { "command": "editor.emmet.action.splitJoinTag", "when": "!activeEditorIsReadonly" }, { "command": "editor.emmet.action.toggleComment", "when": "!activeEditorIsReadonly" }, { "command": "editor.emmet.action.evaluateMathExpression", "when": "!activeEditorIsReadonly" }, { "command": "editor.emmet.action.updateImageSize", "when": "!activeEditorIsReadonly" }, { "command": "editor.emmet.action.incrementNumberByOneTenth", "when": "!activeEditorIsReadonly" }, { "command": "editor.emmet.action.incrementNumberByOne", "when": "!activeEditorIsReadonly" }, { "command": "editor.emmet.action.incrementNumberByTen", "when": "!activeEditorIsReadonly" }, { "command": "editor.emmet.action.decrementNumberByOneTenth", "when": "!activeEditorIsReadonly" }, { "command": "editor.emmet.action.decrementNumberByOne", "when": "!activeEditorIsReadonly" }, { "command": "editor.emmet.action.decrementNumberByTen", "when": "!activeEditorIsReadonly" }, { "command": "editor.emmet.action.reflectCSSValue", "when": "!activeEditorIsReadonly" } ] } }, "scripts": { "watch": "gulp watch-extension:emmet", "compile": "gulp compile-extension:emmet", "deps": "yarn add @vscode/emmet-helper" }, "devDependencies": { "@types/node": "16.x" }, "dependencies": { "@emmetio/abbreviation": "^2.2.0", "@emmetio/css-parser": "ramya-rao-a/css-parser#vscode", "@emmetio/html-matcher": "^0.3.3", "@emmetio/math-expression": "^1.0.4", "@vscode/emmet-helper": "^2.3.0", "image-size": "~1.0.0", "vscode-languageserver-textdocument": "^1.0.1" }, "capabilities": { "virtualWorkspaces": true, "untrustedWorkspaces": { "supported": true } } }
extensions/emmet/package.json
0
https://github.com/microsoft/vscode/commit/324d1a25760c6abeb4a0492c0c5a22795b695bf4
[ 0.0001766398490872234, 0.00017126603052020073, 0.00016573334869462997, 0.0001714198151603341, 0.0000025146855477942154 ]
{ "id": 0, "code_window": [ "import * as tasks from 'vs/workbench/api/common/shared/tasks';\n", "import { SaveReason } from 'vs/workbench/common/editor';\n", "import { IRevealOptions, ITreeItem, IViewBadge } from 'vs/workbench/common/views';\n", "import { CallHierarchyItem } from 'vs/workbench/contrib/callHierarchy/common/callHierarchy';\n", "import { DebugConfigurationProviderTriggerKind, IAdapterDescriptor, IConfig, IDebugSessionReplMode } from 'vs/workbench/contrib/debug/common/debug';\n", "import { IInteractiveResponseErrorDetails } from 'vs/workbench/contrib/interactiveSession/common/interactiveSessionModel';\n", "import { IInteractiveProgress, IInteractiveSessionDynamicRequest, IInteractiveSessionFollowup, IInteractiveSessionReplyFollowup, IInteractiveSessionUserActionEvent, IInteractiveSlashCommand } from 'vs/workbench/contrib/interactiveSession/common/interactiveSessionService';\n", "import * as notebookCommon from 'vs/workbench/contrib/notebook/common/notebookCommon';\n", "import { CellExecutionUpdateType } from 'vs/workbench/contrib/notebook/common/notebookExecutionService';\n", "import { ICellExecutionComplete, ICellExecutionStateUpdate } from 'vs/workbench/contrib/notebook/common/notebookExecutionStateService';\n", "import { ICellRange } from 'vs/workbench/contrib/notebook/common/notebookRange';\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { IInteractiveProgress, IInteractiveResponseErrorDetails, IInteractiveSessionDynamicRequest, IInteractiveSessionFollowup, IInteractiveSessionReplyFollowup, IInteractiveSessionUserActionEvent, IInteractiveSlashCommand } from 'vs/workbench/contrib/interactiveSession/common/interactiveSessionService';\n" ], "file_path": "src/vs/workbench/api/common/extHost.protocol.ts", "type": "replace", "edit_start_line_idx": 53 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { URI } from 'vs/base/common/uri'; import { InstantiationType, registerSingleton } from 'vs/platform/instantiation/common/extensions'; import { IFileService } from 'vs/platform/files/common/files'; import { IProductService } from 'vs/platform/product/common/productService'; import { asTextOrError, IRequestService } from 'vs/platform/request/common/request'; import { IStorageService } from 'vs/platform/storage/common/storage'; import { IEnvironmentService } from 'vs/platform/environment/common/environment'; import { IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { CancellationToken } from 'vs/base/common/cancellation'; import { AbstractExtensionResourceLoaderService, IExtensionResourceLoaderService } from 'vs/platform/extensionResourceLoader/common/extensionResourceLoader'; export class ExtensionResourceLoaderService extends AbstractExtensionResourceLoaderService { constructor( @IFileService fileService: IFileService, @IStorageService storageService: IStorageService, @IProductService productService: IProductService, @IEnvironmentService environmentService: IEnvironmentService, @IConfigurationService configurationService: IConfigurationService, @IRequestService private readonly _requestService: IRequestService, ) { super(fileService, storageService, productService, environmentService, configurationService); } async readExtensionResource(uri: URI): Promise<string> { if (this.isExtensionGalleryResource(uri)) { const headers = await this.getExtensionGalleryRequestHeaders(); const requestContext = await this._requestService.request({ url: uri.toString(), headers }, CancellationToken.None); return (await asTextOrError(requestContext)) || ''; } const result = await this._fileService.readFile(uri); return result.value.toString(); } } registerSingleton(IExtensionResourceLoaderService, ExtensionResourceLoaderService, InstantiationType.Delayed);
src/vs/platform/extensionResourceLoader/common/extensionResourceLoaderService.ts
0
https://github.com/microsoft/vscode/commit/324d1a25760c6abeb4a0492c0c5a22795b695bf4
[ 0.000450813997304067, 0.00022624134726356715, 0.00016825503553263843, 0.00016999781655613333, 0.00011229311348870397 ]
{ "id": 0, "code_window": [ "import * as tasks from 'vs/workbench/api/common/shared/tasks';\n", "import { SaveReason } from 'vs/workbench/common/editor';\n", "import { IRevealOptions, ITreeItem, IViewBadge } from 'vs/workbench/common/views';\n", "import { CallHierarchyItem } from 'vs/workbench/contrib/callHierarchy/common/callHierarchy';\n", "import { DebugConfigurationProviderTriggerKind, IAdapterDescriptor, IConfig, IDebugSessionReplMode } from 'vs/workbench/contrib/debug/common/debug';\n", "import { IInteractiveResponseErrorDetails } from 'vs/workbench/contrib/interactiveSession/common/interactiveSessionModel';\n", "import { IInteractiveProgress, IInteractiveSessionDynamicRequest, IInteractiveSessionFollowup, IInteractiveSessionReplyFollowup, IInteractiveSessionUserActionEvent, IInteractiveSlashCommand } from 'vs/workbench/contrib/interactiveSession/common/interactiveSessionService';\n", "import * as notebookCommon from 'vs/workbench/contrib/notebook/common/notebookCommon';\n", "import { CellExecutionUpdateType } from 'vs/workbench/contrib/notebook/common/notebookExecutionService';\n", "import { ICellExecutionComplete, ICellExecutionStateUpdate } from 'vs/workbench/contrib/notebook/common/notebookExecutionStateService';\n", "import { ICellRange } from 'vs/workbench/contrib/notebook/common/notebookRange';\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { IInteractiveProgress, IInteractiveResponseErrorDetails, IInteractiveSessionDynamicRequest, IInteractiveSessionFollowup, IInteractiveSessionReplyFollowup, IInteractiveSessionUserActionEvent, IInteractiveSlashCommand } from 'vs/workbench/contrib/interactiveSession/common/interactiveSessionService';\n" ], "file_path": "src/vs/workbench/api/common/extHost.protocol.ts", "type": "replace", "edit_start_line_idx": 53 }
test/** cgmanifest.json
extensions/handlebars/.vscodeignore
0
https://github.com/microsoft/vscode/commit/324d1a25760c6abeb4a0492c0c5a22795b695bf4
[ 0.00016427034279331565, 0.00016427034279331565, 0.00016427034279331565, 0.00016427034279331565, 0 ]
{ "id": 1, "code_window": [ "\n", "\t\ttemplateData.rowContainer.classList.toggle('interactive-request', isRequestVM(element));\n", "\t\ttemplateData.rowContainer.classList.toggle('interactive-response', isResponseVM(element));\n", "\t\ttemplateData.rowContainer.classList.toggle('interactive-welcome', isWelcomeVM(element));\n", "\t\ttemplateData.username.textContent = element.username;\n", "\n", "\t\tif (element.avatarIconUri) {\n", "\t\t\tconst avatarIcon = dom.$<HTMLImageElement>('img.icon');\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\ttemplateData.rowContainer.classList.toggle('filtered-response', !!(isResponseVM(element) && element.errorDetails?.responseIsFiltered));\n" ], "file_path": "src/vs/workbench/contrib/interactiveSession/browser/interactiveSessionListRenderer.ts", "type": "add", "edit_start_line_idx": 197 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { Emitter, Event } from 'vs/base/common/event'; import { IMarkdownString, MarkdownString } from 'vs/base/common/htmlContent'; import { Disposable } from 'vs/base/common/lifecycle'; import { URI } from 'vs/base/common/uri'; import { ILogService } from 'vs/platform/log/common/log'; import { IInteractiveProgress, IInteractiveResponse, IInteractiveSession, IInteractiveSessionFollowup, IInteractiveSessionReplyFollowup, InteractiveSessionVoteDirection } from 'vs/workbench/contrib/interactiveSession/common/interactiveSessionService'; export interface IInteractiveRequestModel { readonly id: string; readonly username: string; readonly avatarIconUri?: URI; readonly message: string | IInteractiveSessionReplyFollowup; readonly response: IInteractiveResponseModel | undefined; } export interface IInteractiveResponseErrorDetails { message: string; responseIsIncomplete?: boolean; } export interface IInteractiveResponseModel { readonly onDidChange: Event<void>; readonly id: string; readonly providerId: string; readonly providerResponseId: string | undefined; readonly username: string; readonly avatarIconUri?: URI; readonly response: IMarkdownString; readonly isComplete: boolean; readonly isCanceled: boolean; readonly vote: InteractiveSessionVoteDirection | undefined; readonly followups?: IInteractiveSessionFollowup[] | undefined; readonly errorDetails?: IInteractiveResponseErrorDetails; setVote(vote: InteractiveSessionVoteDirection): void; } export function isRequest(item: unknown): item is IInteractiveRequestModel { return !!item && typeof (item as IInteractiveRequestModel).message !== 'undefined'; } export function isResponse(item: unknown): item is IInteractiveResponseModel { return !isRequest(item); } export class InteractiveRequestModel implements IInteractiveRequestModel { private static nextId = 0; public response: InteractiveResponseModel | undefined; private _id: string; public get id(): string { return this._id; } constructor(public readonly message: string | IInteractiveSessionReplyFollowup, public readonly username: string, public readonly avatarIconUri?: URI) { this._id = 'request_' + InteractiveRequestModel.nextId++; } } export class InteractiveResponseModel extends Disposable implements IInteractiveResponseModel { private readonly _onDidChange = this._register(new Emitter<void>()); readonly onDidChange = this._onDidChange.event; private static nextId = 0; private _id: string; public get id(): string { return this._id; } private _providerResponseId: string | undefined; public get providerResponseId(): string | undefined { return this._providerResponseId; } private _isComplete: boolean; public get isComplete(): boolean { return this._isComplete; } private _isCanceled: boolean; public get isCanceled(): boolean { return this._isCanceled; } private _vote: InteractiveSessionVoteDirection | undefined; public get vote(): InteractiveSessionVoteDirection | undefined { return this._vote; } private _followups: IInteractiveSessionFollowup[] | undefined; public get followups(): IInteractiveSessionFollowup[] | undefined { return this._followups; } private _response: IMarkdownString; public get response(): IMarkdownString { return this._response; } private _errorDetails: IInteractiveResponseErrorDetails | undefined; public get errorDetails(): IInteractiveResponseErrorDetails | undefined { return this._errorDetails; } constructor(response: IMarkdownString, public readonly username: string, public readonly providerId: string, public readonly avatarIconUri?: URI, isComplete: boolean = false, isCanceled = false, vote?: InteractiveSessionVoteDirection, providerResponseId?: string, errorDetails?: IInteractiveResponseErrorDetails, followups?: IInteractiveSessionFollowup[]) { super(); this._response = response; this._isComplete = isComplete; this._followups = followups; this._providerResponseId = providerResponseId; this._errorDetails = errorDetails; this._isCanceled = isCanceled; this._vote = vote; this._id = 'response_' + InteractiveResponseModel.nextId++; } updateContent(responsePart: string) { this._response = new MarkdownString(this.response.value + responsePart); this._onDidChange.fire(); } setProviderResponseId(providerResponseId: string) { this._providerResponseId = providerResponseId; } complete(errorDetails?: IInteractiveResponseErrorDetails): void { this._isComplete = true; this._errorDetails = errorDetails; this._onDidChange.fire(); } cancel(): void { this._isComplete = true; this._isCanceled = true; this._onDidChange.fire(); } setFollowups(followups: IInteractiveSessionFollowup[] | undefined): void { this._followups = followups; this._onDidChange.fire(); // Fire so that command followups get rendered on the row } setVote(vote: InteractiveSessionVoteDirection): void { this._vote = vote; this._onDidChange.fire(); } } export interface IInteractiveSessionModel { readonly onDidDispose: Event<void>; readonly onDidChange: Event<IInteractiveSessionChangeEvent>; readonly sessionId: number; readonly providerId: string; readonly welcomeMessage: IInteractiveSessionWelcomeMessageModel | undefined; readonly inputPlaceholder?: string; getRequests(): IInteractiveRequestModel[]; } export interface ISerializableInteractiveSessionsData { [providerId: string]: ISerializableInteractiveSessionData[]; } export interface ISerializableInteractiveSessionRequestData { providerResponseId: string | undefined; message: string; response: string | undefined; responseErrorDetails: IInteractiveResponseErrorDetails | undefined; followups: IInteractiveSessionFollowup[] | undefined; isCanceled: boolean | undefined; vote: InteractiveSessionVoteDirection | undefined; } export interface ISerializableInteractiveSessionData { requests: ISerializableInteractiveSessionRequestData[]; providerId: string; providerState: any; } export type IInteractiveSessionChangeEvent = IInteractiveSessionAddRequestEvent | IInteractiveSessionAddResponseEvent | IInteractiveSessionClearEvent; export interface IInteractiveSessionAddRequestEvent { kind: 'addRequest'; request: IInteractiveRequestModel; } export interface IInteractiveSessionAddResponseEvent { kind: 'addResponse'; response: IInteractiveResponseModel; } export interface IInteractiveSessionClearEvent { kind: 'clear'; } export class InteractiveSessionModel extends Disposable implements IInteractiveSessionModel { private readonly _onDidDispose = this._register(new Emitter<void>()); readonly onDidDispose = this._onDidDispose.event; private readonly _onDidChange = this._register(new Emitter<IInteractiveSessionChangeEvent>()); readonly onDidChange = this._onDidChange.event; private _requests: InteractiveRequestModel[]; private _providerState: any; get sessionId(): number { return this.session.id; } get inputPlaceholder(): string | undefined { return this.session.inputPlaceholder; } constructor( public readonly session: IInteractiveSession, public readonly providerId: string, public readonly welcomeMessage: InteractiveWelcomeMessageModel | undefined, initialData: ISerializableInteractiveSessionData | undefined, @ILogService private readonly logService: ILogService ) { super(); this._requests = initialData ? this._deserialize(initialData) : []; this._providerState = initialData ? initialData.providerState : undefined; } private _deserialize(obj: ISerializableInteractiveSessionData): InteractiveRequestModel[] { const requests = obj.requests; if (!Array.isArray(requests)) { this.logService.error(`Ignoring malformed session data: ${obj}`); return []; } return requests.map((raw: ISerializableInteractiveSessionRequestData) => { const request = new InteractiveRequestModel(raw.message, this.session.requesterUsername, this.session.requesterAvatarIconUri); if (raw.response || raw.responseErrorDetails) { request.response = new InteractiveResponseModel(new MarkdownString(raw.response), this.session.responderUsername, this.providerId, this.session.responderAvatarIconUri, true, raw.isCanceled, raw.vote, raw.providerResponseId, raw.responseErrorDetails, raw.followups); } return request; }); } acceptNewProviderState(providerState: any): void { this._providerState = providerState; } clear(): void { this._requests.forEach(r => r.response?.dispose()); this._requests = []; this._onDidChange.fire({ kind: 'clear' }); } getRequests(): InteractiveRequestModel[] { return this._requests; } addRequest(message: string | IInteractiveSessionReplyFollowup): InteractiveRequestModel { const request = new InteractiveRequestModel(message, this.session.requesterUsername, this.session.requesterAvatarIconUri); // TODO this is suspicious, maybe the request should know that it is "in progress" instead of having a fake response model. // But the response already knows that it is "in progress" and so does a map in the session service. request.response = new InteractiveResponseModel(new MarkdownString(''), this.session.responderUsername, this.providerId, this.session.responderAvatarIconUri); this._requests.push(request); this._onDidChange.fire({ kind: 'addRequest', request }); return request; } acceptResponseProgress(request: InteractiveRequestModel, progress: IInteractiveProgress): void { if (!request.response) { request.response = new InteractiveResponseModel(new MarkdownString(''), this.session.responderUsername, this.providerId, this.session.responderAvatarIconUri); } if ('content' in progress) { request.response.updateContent(progress.content); } else { request.response.setProviderResponseId(progress.responseId); } } cancelRequest(request: InteractiveRequestModel): void { if (request.response) { request.response.cancel(); } } completeResponse(request: InteractiveRequestModel, rawResponse: IInteractiveResponse): void { if (!request.response) { request.response = new InteractiveResponseModel(new MarkdownString(''), this.session.responderUsername, this.providerId, this.session.responderAvatarIconUri); } request.response.complete(rawResponse.errorDetails); } setFollowups(request: InteractiveRequestModel, followups: IInteractiveSessionFollowup[] | undefined): void { if (!request.response) { // Maybe something went wrong? return; } request.response.setFollowups(followups); } setResponse(request: InteractiveRequestModel, response: InteractiveResponseModel): void { request.response = response; this._onDidChange.fire({ kind: 'addResponse', response }); } toJSON(): ISerializableInteractiveSessionData { return { requests: this._requests.map((r): ISerializableInteractiveSessionRequestData => { return { providerResponseId: r.response?.providerResponseId, message: typeof r.message === 'string' ? r.message : r.message.message, response: r.response ? r.response.response.value : undefined, responseErrorDetails: r.response?.errorDetails, followups: r.response?.followups, isCanceled: r.response?.isCanceled, vote: r.response?.vote }; }), providerId: this.providerId, providerState: this._providerState }; } override dispose() { this.session.dispose?.(); this._requests.forEach(r => r.response?.dispose()); this._onDidDispose.fire(); super.dispose(); } } export type IInteractiveWelcomeMessageContent = IMarkdownString | IInteractiveSessionReplyFollowup[]; export interface IInteractiveSessionWelcomeMessageModel { readonly id: string; readonly content: IInteractiveWelcomeMessageContent[]; readonly username: string; readonly avatarIconUri?: URI; } export class InteractiveWelcomeMessageModel implements IInteractiveSessionWelcomeMessageModel { private static nextId = 0; private _id: string; public get id(): string { return this._id; } constructor(public readonly content: IInteractiveWelcomeMessageContent[], public readonly username: string, public readonly avatarIconUri?: URI) { this._id = 'welcome_' + InteractiveWelcomeMessageModel.nextId++; } }
src/vs/workbench/contrib/interactiveSession/common/interactiveSessionModel.ts
1
https://github.com/microsoft/vscode/commit/324d1a25760c6abeb4a0492c0c5a22795b695bf4
[ 0.008656895719468594, 0.0008021032554097474, 0.000162622076459229, 0.00021960090089123696, 0.0015441045397892594 ]
{ "id": 1, "code_window": [ "\n", "\t\ttemplateData.rowContainer.classList.toggle('interactive-request', isRequestVM(element));\n", "\t\ttemplateData.rowContainer.classList.toggle('interactive-response', isResponseVM(element));\n", "\t\ttemplateData.rowContainer.classList.toggle('interactive-welcome', isWelcomeVM(element));\n", "\t\ttemplateData.username.textContent = element.username;\n", "\n", "\t\tif (element.avatarIconUri) {\n", "\t\t\tconst avatarIcon = dom.$<HTMLImageElement>('img.icon');\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\ttemplateData.rowContainer.classList.toggle('filtered-response', !!(isResponseVM(element) && element.errorDetails?.responseIsFiltered));\n" ], "file_path": "src/vs/workbench/contrib/interactiveSession/browser/interactiveSessionListRenderer.ts", "type": "add", "edit_start_line_idx": 197 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ .monaco-editor .test-output-peek .test-output-peek-tree { background-color: var(--vscode-peekViewResult-background); color: var(--vscode-peekViewResult-lineForeground); } .monaco-editor .test-output-peek .test-output-peek-tree .monaco-list:focus .monaco-list-rows > .monaco-list-row.selected:not(.highlighted) { background-color: var(--vscode-peekViewResult-selectionBackground); color: var(--vscode-peekViewResult-selectionForeground) !important; } .monaco-editor .test-output-peek .test-output-peek-message-container a { color: var(--vscode-textLink-foreground); } .monaco-editor .test-output-peek .test-output-peek-message-container a :hover { color: var(--vscode-textLink-activeForeground); }
src/vs/workbench/contrib/testing/browser/testingOutputPeek.css
0
https://github.com/microsoft/vscode/commit/324d1a25760c6abeb4a0492c0c5a22795b695bf4
[ 0.00017434039909858257, 0.0001718049170449376, 0.0001669880875851959, 0.00017408626445103437, 0.0000034075926578225335 ]
{ "id": 1, "code_window": [ "\n", "\t\ttemplateData.rowContainer.classList.toggle('interactive-request', isRequestVM(element));\n", "\t\ttemplateData.rowContainer.classList.toggle('interactive-response', isResponseVM(element));\n", "\t\ttemplateData.rowContainer.classList.toggle('interactive-welcome', isWelcomeVM(element));\n", "\t\ttemplateData.username.textContent = element.username;\n", "\n", "\t\tif (element.avatarIconUri) {\n", "\t\t\tconst avatarIcon = dom.$<HTMLImageElement>('img.icon');\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\ttemplateData.rowContainer.classList.toggle('filtered-response', !!(isResponseVM(element) && element.errorDetails?.responseIsFiltered));\n" ], "file_path": "src/vs/workbench/contrib/interactiveSession/browser/interactiveSessionListRenderer.ts", "type": "add", "edit_start_line_idx": 197 }
"use strict"; /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ Object.defineProperty(exports, "__esModule", { value: true }); exports.getBuiltInExtensions = exports.getExtensionStream = void 0; const fs = require("fs"); const path = require("path"); const os = require("os"); const rimraf = require("rimraf"); const es = require("event-stream"); const rename = require("gulp-rename"); const vfs = require("vinyl-fs"); const ext = require("./extensions"); const fancyLog = require("fancy-log"); const ansiColors = require("ansi-colors"); const mkdirp = require('mkdirp'); const root = path.dirname(path.dirname(__dirname)); const productjson = JSON.parse(fs.readFileSync(path.join(__dirname, '../../product.json'), 'utf8')); const builtInExtensions = productjson.builtInExtensions || []; const webBuiltInExtensions = productjson.webBuiltInExtensions || []; const controlFilePath = path.join(os.homedir(), '.vscode-oss-dev', 'extensions', 'control.json'); const ENABLE_LOGGING = !process.env['VSCODE_BUILD_BUILTIN_EXTENSIONS_SILENCE_PLEASE']; function log(...messages) { if (ENABLE_LOGGING) { fancyLog(...messages); } } function getExtensionPath(extension) { return path.join(root, '.build', 'builtInExtensions', extension.name); } function isUpToDate(extension) { const packagePath = path.join(getExtensionPath(extension), 'package.json'); if (!fs.existsSync(packagePath)) { return false; } const packageContents = fs.readFileSync(packagePath, { encoding: 'utf8' }); try { const diskVersion = JSON.parse(packageContents).version; return (diskVersion === extension.version); } catch (err) { return false; } } function getExtensionDownloadStream(extension) { const galleryServiceUrl = productjson.extensionsGallery?.serviceUrl; return (galleryServiceUrl ? ext.fromMarketplace(galleryServiceUrl, extension) : ext.fromGithub(extension)) .pipe(rename(p => p.dirname = `${extension.name}/${p.dirname}`)); } function getExtensionStream(extension) { // if the extension exists on disk, use those files instead of downloading anew if (isUpToDate(extension)) { log('[extensions]', `${extension.name}@${extension.version} up to date`, ansiColors.green('✔︎')); return vfs.src(['**'], { cwd: getExtensionPath(extension), dot: true }) .pipe(rename(p => p.dirname = `${extension.name}/${p.dirname}`)); } return getExtensionDownloadStream(extension); } exports.getExtensionStream = getExtensionStream; function syncMarketplaceExtension(extension) { const galleryServiceUrl = productjson.extensionsGallery?.serviceUrl; const source = ansiColors.blue(galleryServiceUrl ? '[marketplace]' : '[github]'); if (isUpToDate(extension)) { log(source, `${extension.name}@${extension.version}`, ansiColors.green('✔︎')); return es.readArray([]); } rimraf.sync(getExtensionPath(extension)); return getExtensionDownloadStream(extension) .pipe(vfs.dest('.build/builtInExtensions')) .on('end', () => log(source, extension.name, ansiColors.green('✔︎'))); } function syncExtension(extension, controlState) { if (extension.platforms) { const platforms = new Set(extension.platforms); if (!platforms.has(process.platform)) { log(ansiColors.gray('[skip]'), `${extension.name}@${extension.version}: Platform '${process.platform}' not supported: [${extension.platforms}]`, ansiColors.green('✔︎')); return es.readArray([]); } } switch (controlState) { case 'disabled': log(ansiColors.blue('[disabled]'), ansiColors.gray(extension.name)); return es.readArray([]); case 'marketplace': return syncMarketplaceExtension(extension); default: if (!fs.existsSync(controlState)) { log(ansiColors.red(`Error: Built-in extension '${extension.name}' is configured to run from '${controlState}' but that path does not exist.`)); return es.readArray([]); } else if (!fs.existsSync(path.join(controlState, 'package.json'))) { log(ansiColors.red(`Error: Built-in extension '${extension.name}' is configured to run from '${controlState}' but there is no 'package.json' file in that directory.`)); return es.readArray([]); } log(ansiColors.blue('[local]'), `${extension.name}: ${ansiColors.cyan(controlState)}`, ansiColors.green('✔︎')); return es.readArray([]); } } function readControlFile() { try { return JSON.parse(fs.readFileSync(controlFilePath, 'utf8')); } catch (err) { return {}; } } function writeControlFile(control) { mkdirp.sync(path.dirname(controlFilePath)); fs.writeFileSync(controlFilePath, JSON.stringify(control, null, 2)); } function getBuiltInExtensions() { log('Synchronizing built-in extensions...'); log(`You can manage built-in extensions with the ${ansiColors.cyan('--builtin')} flag`); const control = readControlFile(); const streams = []; for (const extension of [...builtInExtensions, ...webBuiltInExtensions]) { const controlState = control[extension.name] || 'marketplace'; control[extension.name] = controlState; streams.push(syncExtension(extension, controlState)); } writeControlFile(control); return new Promise((resolve, reject) => { es.merge(streams) .on('error', reject) .on('end', resolve); }); } exports.getBuiltInExtensions = getBuiltInExtensions; if (require.main === module) { getBuiltInExtensions().then(() => process.exit(0)).catch(err => { console.error(err); process.exit(1); }); } //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiYnVpbHRJbkV4dGVuc2lvbnMuanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyJidWlsdEluRXh0ZW5zaW9ucy50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiO0FBQUE7OztnR0FHZ0c7OztBQUVoRyx5QkFBeUI7QUFDekIsNkJBQTZCO0FBQzdCLHlCQUF5QjtBQUN6QixpQ0FBaUM7QUFDakMsbUNBQW1DO0FBQ25DLHNDQUFzQztBQUN0QyxnQ0FBZ0M7QUFDaEMsb0NBQW9DO0FBQ3BDLHNDQUFzQztBQUN0QywwQ0FBMEM7QUFHMUMsTUFBTSxNQUFNLEdBQUcsT0FBTyxDQUFDLFFBQVEsQ0FBQyxDQUFDO0FBbUJqQyxNQUFNLElBQUksR0FBRyxJQUFJLENBQUMsT0FBTyxDQUFDLElBQUksQ0FBQyxPQUFPLENBQUMsU0FBUyxDQUFDLENBQUMsQ0FBQztBQUNuRCxNQUFNLFdBQVcsR0FBRyxJQUFJLENBQUMsS0FBSyxDQUFDLEVBQUUsQ0FBQyxZQUFZLENBQUMsSUFBSSxDQUFDLElBQUksQ0FBQyxTQUFTLEVBQUUsb0JBQW9CLENBQUMsRUFBRSxNQUFNLENBQUMsQ0FBQyxDQUFDO0FBQ3BHLE1BQU0saUJBQWlCLEdBQTJCLFdBQVcsQ0FBQyxpQkFBaUIsSUFBSSxFQUFFLENBQUM7QUFDdEYsTUFBTSxvQkFBb0IsR0FBMkIsV0FBVyxDQUFDLG9CQUFvQixJQUFJLEVBQUUsQ0FBQztBQUM1RixNQUFNLGVBQWUsR0FBRyxJQUFJLENBQUMsSUFBSSxDQUFDLEVBQUUsQ0FBQyxPQUFPLEVBQUUsRUFBRSxpQkFBaUIsRUFBRSxZQUFZLEVBQUUsY0FBYyxDQUFDLENBQUM7QUFDakcsTUFBTSxjQUFjLEdBQUcsQ0FBQyxPQUFPLENBQUMsR0FBRyxDQUFDLGdEQUFnRCxDQUFDLENBQUM7QUFFdEYsU0FBUyxHQUFHLENBQUMsR0FBRyxRQUFrQjtJQUNqQyxJQUFJLGNBQWMsRUFBRTtRQUNuQixRQUFRLENBQUMsR0FBRyxRQUFRLENBQUMsQ0FBQztLQUN0QjtBQUNGLENBQUM7QUFFRCxTQUFTLGdCQUFnQixDQUFDLFNBQStCO0lBQ3hELE9BQU8sSUFBSSxDQUFDLElBQUksQ0FBQyxJQUFJLEVBQUUsUUFBUSxFQUFFLG1CQUFtQixFQUFFLFNBQVMsQ0FBQyxJQUFJLENBQUMsQ0FBQztBQUN2RSxDQUFDO0FBRUQsU0FBUyxVQUFVLENBQUMsU0FBK0I7SUFDbEQsTUFBTSxXQUFXLEdBQUcsSUFBSSxDQUFDLElBQUksQ0FBQyxnQkFBZ0IsQ0FBQyxTQUFTLENBQUMsRUFBRSxjQUFjLENBQUMsQ0FBQztJQUUzRSxJQUFJLENBQUMsRUFBRSxDQUFDLFVBQVUsQ0FBQyxXQUFXLENBQUMsRUFBRTtRQUNoQyxPQUFPLEtBQUssQ0FBQztLQUNiO0lBRUQsTUFBTSxlQUFlLEdBQUcsRUFBRSxDQUFDLFlBQVksQ0FBQyxXQUFXLEVBQUUsRUFBRSxRQUFRLEVBQUUsTUFBTSxFQUFFLENBQUMsQ0FBQztJQUUzRSxJQUFJO1FBQ0gsTUFBTSxXQUFXLEdBQUcsSUFBSSxDQUFDLEtBQUssQ0FBQyxlQUFlLENBQUMsQ0FBQyxPQUFPLENBQUM7UUFDeEQsT0FBTyxDQUFDLFdBQVcsS0FBSyxTQUFTLENBQUMsT0FBTyxDQUFDLENBQUM7S0FDM0M7SUFBQyxPQUFPLEdBQUcsRUFBRTtRQUNiLE9BQU8sS0FBSyxDQUFDO0tBQ2I7QUFDRixDQUFDO0FBRUQsU0FBUywwQkFBMEIsQ0FBQyxTQUErQjtJQUNsRSxNQUFNLGlCQUFpQixHQUFHLFdBQVcsQ0FBQyxpQkFBaUIsRUFBRSxVQUFVLENBQUM7SUFDcEUsT0FBTyxDQUFDLGlCQUFpQixDQUFDLENBQUMsQ0FBQyxHQUFHLENBQUMsZUFBZSxDQUFDLGlCQUFpQixFQUFFLFNBQVMsQ0FBQyxDQUFDLENBQUMsQ0FBQyxHQUFHLENBQUMsVUFBVSxDQUFDLFNBQVMsQ0FBQyxDQUFDO1NBQ3hHLElBQUksQ0FBQyxNQUFNLENBQUMsQ0FBQyxDQUFDLEVBQUUsQ0FBQyxDQUFDLENBQUMsT0FBTyxHQUFHLEdBQUcsU0FBUyxDQUFDLElBQUksSUFBSSxDQUFDLENBQUMsT0FBTyxFQUFFLENBQUMsQ0FBQyxDQUFDO0FBQ25FLENBQUM7QUFFRCxTQUFnQixrQkFBa0IsQ0FBQyxTQUErQjtJQUNqRSwrRUFBK0U7SUFDL0UsSUFBSSxVQUFVLENBQUMsU0FBUyxDQUFDLEVBQUU7UUFDMUIsR0FBRyxDQUFDLGNBQWMsRUFBRSxHQUFHLFNBQVMsQ0FBQyxJQUFJLElBQUksU0FBUyxDQUFDLE9BQU8sYUFBYSxFQUFFLFVBQVUsQ0FBQyxLQUFLLENBQUMsSUFBSSxDQUFDLENBQUMsQ0FBQztRQUNqRyxPQUFPLEdBQUcsQ0FBQyxHQUFHLENBQUMsQ0FBQyxJQUFJLENBQUMsRUFBRSxFQUFFLEdBQUcsRUFBRSxnQkFBZ0IsQ0FBQyxTQUFTLENBQUMsRUFBRSxHQUFHLEVBQUUsSUFBSSxFQUFFLENBQUM7YUFDckUsSUFBSSxDQUFDLE1BQU0sQ0FBQyxDQUFDLENBQUMsRUFBRSxDQUFDLENBQUMsQ0FBQyxPQUFPLEdBQUcsR0FBRyxTQUFTLENBQUMsSUFBSSxJQUFJLENBQUMsQ0FBQyxPQUFPLEVBQUUsQ0FBQyxDQUFDLENBQUM7S0FDbEU7SUFFRCxPQUFPLDBCQUEwQixDQUFDLFNBQVMsQ0FBQyxDQUFDO0FBQzlDLENBQUM7QUFURCxnREFTQztBQUVELFNBQVMsd0JBQXdCLENBQUMsU0FBK0I7SUFDaEUsTUFBTSxpQkFBaUIsR0FBRyxXQUFXLENBQUMsaUJBQWlCLEVBQUUsVUFBVSxDQUFDO0lBQ3BFLE1BQU0sTUFBTSxHQUFHLFVBQVUsQ0FBQyxJQUFJLENBQUMsaUJBQWlCLENBQUMsQ0FBQyxDQUFDLGVBQWUsQ0FBQyxDQUFDLENBQUMsVUFBVSxDQUFDLENBQUM7SUFDakYsSUFBSSxVQUFVLENBQUMsU0FBUyxDQUFDLEVBQUU7UUFDMUIsR0FBRyxDQUFDLE1BQU0sRUFBRSxHQUFHLFNBQVMsQ0FBQyxJQUFJLElBQUksU0FBUyxDQUFDLE9BQU8sRUFBRSxFQUFFLFVBQVUsQ0FBQyxLQUFLLENBQUMsSUFBSSxDQUFDLENBQUMsQ0FBQztRQUM5RSxPQUFPLEVBQUUsQ0FBQyxTQUFTLENBQUMsRUFBRSxDQUFDLENBQUM7S0FDeEI7SUFFRCxNQUFNLENBQUMsSUFBSSxDQUFDLGdCQUFnQixDQUFDLFNBQVMsQ0FBQyxDQUFDLENBQUM7SUFFekMsT0FBTywwQkFBMEIsQ0FBQyxTQUFTLENBQUM7U0FDMUMsSUFBSSxDQUFDLEdBQUcsQ0FBQyxJQUFJLENBQUMsMEJBQTBCLENBQUMsQ0FBQztTQUMxQyxFQUFFLENBQUMsS0FBSyxFQUFFLEdBQUcsRUFBRSxDQUFDLEdBQUcsQ0FBQyxNQUFNLEVBQUUsU0FBUyxDQUFDLElBQUksRUFBRSxVQUFVLENBQUMsS0FBSyxDQUFDLElBQUksQ0FBQyxDQUFDLENBQUMsQ0FBQztBQUN4RSxDQUFDO0FBRUQsU0FBUyxhQUFhLENBQUMsU0FBK0IsRUFBRSxZQUF3QztJQUMvRixJQUFJLFNBQVMsQ0FBQyxTQUFTLEVBQUU7UUFDeEIsTUFBTSxTQUFTLEdBQUcsSUFBSSxHQUFHLENBQUMsU0FBUyxDQUFDLFNBQVMsQ0FBQyxDQUFDO1FBRS9DLElBQUksQ0FBQyxTQUFTLENBQUMsR0FBRyxDQUFDLE9BQU8sQ0FBQyxRQUFRLENBQUMsRUFBRTtZQUNyQyxHQUFHLENBQUMsVUFBVSxDQUFDLElBQUksQ0FBQyxRQUFRLENBQUMsRUFBRSxHQUFHLFNBQVMsQ0FBQyxJQUFJLElBQUksU0FBUyxDQUFDLE9BQU8sZUFBZSxPQUFPLENBQUMsUUFBUSxxQkFBcUIsU0FBUyxDQUFDLFNBQVMsR0FBRyxFQUFFLFVBQVUsQ0FBQyxLQUFLLENBQUMsSUFBSSxDQUFDLENBQUMsQ0FBQztZQUN6SyxPQUFPLEVBQUUsQ0FBQyxTQUFTLENBQUMsRUFBRSxDQUFDLENBQUM7U0FDeEI7S0FDRDtJQUVELFFBQVEsWUFBWSxFQUFFO1FBQ3JCLEtBQUssVUFBVTtZQUNkLEdBQUcsQ0FBQyxVQUFVLENBQUMsSUFBSSxDQUFDLFlBQVksQ0FBQyxFQUFFLFVBQVUsQ0FBQyxJQUFJLENBQUMsU0FBUyxDQUFDLElBQUksQ0FBQyxDQUFDLENBQUM7WUFDcEUsT0FBTyxFQUFFLENBQUMsU0FBUyxDQUFDLEVBQUUsQ0FBQyxDQUFDO1FBRXpCLEtBQUssYUFBYTtZQUNqQixPQUFPLHdCQUF3QixDQUFDLFNBQVMsQ0FBQyxDQUFDO1FBRTVDO1lBQ0MsSUFBSSxDQUFDLEVBQUUsQ0FBQyxVQUFVLENBQUMsWUFBWSxDQUFDLEVBQUU7Z0JBQ2pDLEdBQUcsQ0FBQyxVQUFVLENBQUMsR0FBRyxDQUFDLDhCQUE4QixTQUFTLENBQUMsSUFBSSxnQ0FBZ0MsWUFBWSxpQ0FBaUMsQ0FBQyxDQUFDLENBQUM7Z0JBQy9JLE9BQU8sRUFBRSxDQUFDLFNBQVMsQ0FBQyxFQUFFLENBQUMsQ0FBQzthQUV4QjtpQkFBTSxJQUFJLENBQUMsRUFBRSxDQUFDLFVBQVUsQ0FBQyxJQUFJLENBQUMsSUFBSSxDQUFDLFlBQVksRUFBRSxjQUFjLENBQUMsQ0FBQyxFQUFFO2dCQUNuRSxHQUFHLENBQUMsVUFBVSxDQUFDLEdBQUcsQ0FBQyw4QkFBOEIsU0FBUyxDQUFDLElBQUksZ0NBQWdDLFlBQVksMERBQTBELENBQUMsQ0FBQyxDQUFDO2dCQUN4SyxPQUFPLEVBQUUsQ0FBQyxTQUFTLENBQUMsRUFBRSxDQUFDLENBQUM7YUFDeEI7WUFFRCxHQUFHLENBQUMsVUFBVSxDQUFDLElBQUksQ0FBQyxTQUFTLENBQUMsRUFBRSxHQUFHLFNBQVMsQ0FBQyxJQUFJLEtBQUssVUFBVSxDQUFDLElBQUksQ0FBQyxZQUFZLENBQUMsRUFBRSxFQUFFLFVBQVUsQ0FBQyxLQUFLLENBQUMsSUFBSSxDQUFDLENBQUMsQ0FBQztZQUMvRyxPQUFPLEVBQUUsQ0FBQyxTQUFTLENBQUMsRUFBRSxDQUFDLENBQUM7S0FDekI7QUFDRixDQUFDO0FBTUQsU0FBUyxlQUFlO0lBQ3ZCLElBQUk7UUFDSCxPQUFPLElBQUksQ0FBQyxLQUFLLENBQUMsRUFBRSxDQUFDLFlBQVksQ0FBQyxlQUFlLEVBQUUsTUFBTSxDQUFDLENBQUMsQ0FBQztLQUM1RDtJQUFDLE9BQU8sR0FBRyxFQUFFO1FBQ2IsT0FBTyxFQUFFLENBQUM7S0FDVjtBQUNGLENBQUM7QUFFRCxTQUFTLGdCQUFnQixDQUFDLE9BQXFCO0lBQzlDLE1BQU0sQ0FBQyxJQUFJLENBQUMsSUFBSSxDQUFDLE9BQU8sQ0FBQyxlQUFlLENBQUMsQ0FBQyxDQUFDO0lBQzNDLEVBQUUsQ0FBQyxhQUFhLENBQUMsZUFBZSxFQUFFLElBQUksQ0FBQyxTQUFTLENBQUMsT0FBTyxFQUFFLElBQUksRUFBRSxDQUFDLENBQUMsQ0FBQyxDQUFDO0FBQ3JFLENBQUM7QUFFRCxTQUFnQixvQkFBb0I7SUFDbkMsR0FBRyxDQUFDLHNDQUFzQyxDQUFDLENBQUM7SUFDNUMsR0FBRyxDQUFDLCtDQUErQyxVQUFVLENBQUMsSUFBSSxDQUFDLFdBQVcsQ0FBQyxPQUFPLENBQUMsQ0FBQztJQUV4RixNQUFNLE9BQU8sR0FBRyxlQUFlLEVBQUUsQ0FBQztJQUNsQyxNQUFNLE9BQU8sR0FBYSxFQUFFLENBQUM7SUFFN0IsS0FBSyxNQUFNLFNBQVMsSUFBSSxDQUFDLEdBQUcsaUJBQWlCLEVBQUUsR0FBRyxvQkFBb0IsQ0FBQyxFQUFFO1FBQ3hFLE1BQU0sWUFBWSxHQUFHLE9BQU8sQ0FBQyxTQUFTLENBQUMsSUFBSSxDQUFDLElBQUksYUFBYSxDQUFDO1FBQzlELE9BQU8sQ0FBQyxTQUFTLENBQUMsSUFBSSxDQUFDLEdBQUcsWUFBWSxDQUFDO1FBRXZDLE9BQU8sQ0FBQyxJQUFJLENBQUMsYUFBYSxDQUFDLFNBQVMsRUFBRSxZQUFZLENBQUMsQ0FBQyxDQUFDO0tBQ3JEO0lBRUQsZ0JBQWdCLENBQUMsT0FBTyxDQUFDLENBQUM7SUFFMUIsT0FBTyxJQUFJLE9BQU8sQ0FBQyxDQUFDLE9BQU8sRUFBRSxNQUFNLEVBQUUsRUFBRTtRQUN0QyxFQUFFLENBQUMsS0FBSyxDQUFDLE9BQU8sQ0FBQzthQUNmLEVBQUUsQ0FBQyxPQUFPLEVBQUUsTUFBTSxDQUFDO2FBQ25CLEVBQUUsQ0FBQyxLQUFLLEVBQUUsT0FBTyxDQUFDLENBQUM7SUFDdEIsQ0FBQyxDQUFDLENBQUM7QUFDSixDQUFDO0FBckJELG9EQXFCQztBQUVELElBQUksT0FBTyxDQUFDLElBQUksS0FBSyxNQUFNLEVBQUU7SUFDNUIsb0JBQW9CLEVBQUUsQ0FBQyxJQUFJLENBQUMsR0FBRyxFQUFFLENBQUMsT0FBTyxDQUFDLElBQUksQ0FBQyxDQUFDLENBQUMsQ0FBQyxDQUFDLEtBQUssQ0FBQyxHQUFHLENBQUMsRUFBRTtRQUM5RCxPQUFPLENBQUMsS0FBSyxDQUFDLEdBQUcsQ0FBQyxDQUFDO1FBQ25CLE9BQU8sQ0FBQyxJQUFJLENBQUMsQ0FBQyxDQUFDLENBQUM7SUFDakIsQ0FBQyxDQUFDLENBQUM7Q0FDSCJ9
build/lib/builtInExtensions.js
0
https://github.com/microsoft/vscode/commit/324d1a25760c6abeb4a0492c0c5a22795b695bf4
[ 0.0013505109818652272, 0.0002574918034952134, 0.00016709974443074316, 0.00017427600687369704, 0.0003031616797670722 ]
{ "id": 1, "code_window": [ "\n", "\t\ttemplateData.rowContainer.classList.toggle('interactive-request', isRequestVM(element));\n", "\t\ttemplateData.rowContainer.classList.toggle('interactive-response', isResponseVM(element));\n", "\t\ttemplateData.rowContainer.classList.toggle('interactive-welcome', isWelcomeVM(element));\n", "\t\ttemplateData.username.textContent = element.username;\n", "\n", "\t\tif (element.avatarIconUri) {\n", "\t\t\tconst avatarIcon = dom.$<HTMLImageElement>('img.icon');\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\ttemplateData.rowContainer.classList.toggle('filtered-response', !!(isResponseVM(element) && element.errorDetails?.responseIsFiltered));\n" ], "file_path": "src/vs/workbench/contrib/interactiveSession/browser/interactiveSessionListRenderer.ts", "type": "add", "edit_start_line_idx": 197 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as net from 'net'; /** * Given a start point and a max number of retries, will find a port that * is openable. Will return 0 in case no free port can be found. */ export function findFreePort(startPort: number, giveUpAfter: number, timeout: number, stride = 1): Promise<number> { let done = false; return new Promise(resolve => { const timeoutHandle = setTimeout(() => { if (!done) { done = true; return resolve(0); } }, timeout); doFindFreePort(startPort, giveUpAfter, stride, (port) => { if (!done) { done = true; clearTimeout(timeoutHandle); return resolve(port); } }); }); } function doFindFreePort(startPort: number, giveUpAfter: number, stride: number, clb: (port: number) => void): void { if (giveUpAfter === 0) { return clb(0); } const client = new net.Socket(); // If we can connect to the port it means the port is already taken so we continue searching client.once('connect', () => { dispose(client); return doFindFreePort(startPort + stride, giveUpAfter - 1, stride, clb); }); client.once('data', () => { // this listener is required since node.js 8.x }); client.once('error', (err: Error & { code?: string }) => { dispose(client); // If we receive any non ECONNREFUSED error, it means the port is used but we cannot connect if (err.code !== 'ECONNREFUSED') { return doFindFreePort(startPort + stride, giveUpAfter - 1, stride, clb); } // Otherwise it means the port is free to use! return clb(startPort); }); client.connect(startPort, '127.0.0.1'); } // Reference: https://chromium.googlesource.com/chromium/src.git/+/refs/heads/main/net/base/port_util.cc#56 export const BROWSER_RESTRICTED_PORTS: any = { 1: true, // tcpmux 7: true, // echo 9: true, // discard 11: true, // systat 13: true, // daytime 15: true, // netstat 17: true, // qotd 19: true, // chargen 20: true, // ftp data 21: true, // ftp access 22: true, // ssh 23: true, // telnet 25: true, // smtp 37: true, // time 42: true, // name 43: true, // nicname 53: true, // domain 69: true, // tftp 77: true, // priv-rjs 79: true, // finger 87: true, // ttylink 95: true, // supdup 101: true, // hostriame 102: true, // iso-tsap 103: true, // gppitnp 104: true, // acr-nema 109: true, // pop2 110: true, // pop3 111: true, // sunrpc 113: true, // auth 115: true, // sftp 117: true, // uucp-path 119: true, // nntp 123: true, // NTP 135: true, // loc-srv /epmap 137: true, // netbios 139: true, // netbios 143: true, // imap2 161: true, // snmp 179: true, // BGP 389: true, // ldap 427: true, // SLP (Also used by Apple Filing Protocol) 465: true, // smtp+ssl 512: true, // print / exec 513: true, // login 514: true, // shell 515: true, // printer 526: true, // tempo 530: true, // courier 531: true, // chat 532: true, // netnews 540: true, // uucp 548: true, // AFP (Apple Filing Protocol) 554: true, // rtsp 556: true, // remotefs 563: true, // nntp+ssl 587: true, // smtp (rfc6409) 601: true, // syslog-conn (rfc3195) 636: true, // ldap+ssl 989: true, // ftps-data 990: true, // ftps 993: true, // ldap+ssl 995: true, // pop3+ssl 1719: true, // h323gatestat 1720: true, // h323hostcall 1723: true, // pptp 2049: true, // nfs 3659: true, // apple-sasl / PasswordServer 4045: true, // lockd 5060: true, // sip 5061: true, // sips 6000: true, // X11 6566: true, // sane-port 6665: true, // Alternate IRC [Apple addition] 6666: true, // Alternate IRC [Apple addition] 6667: true, // Standard IRC [Apple addition] 6668: true, // Alternate IRC [Apple addition] 6669: true, // Alternate IRC [Apple addition] 6697: true, // IRC + TLS 10080: true // Amanda }; /** * Uses listen instead of connect. Is faster, but if there is another listener on 0.0.0.0 then this will take 127.0.0.1 from that listener. */ export function findFreePortFaster(startPort: number, giveUpAfter: number, timeout: number, hostname: string = '127.0.0.1'): Promise<number> { let resolved: boolean = false; let timeoutHandle: NodeJS.Timeout | undefined = undefined; let countTried: number = 1; const server = net.createServer({ pauseOnConnect: true }); function doResolve(port: number, resolve: (port: number) => void) { if (!resolved) { resolved = true; server.removeAllListeners(); server.close(); if (timeoutHandle) { clearTimeout(timeoutHandle); } resolve(port); } } return new Promise<number>(resolve => { timeoutHandle = setTimeout(() => { doResolve(0, resolve); }, timeout); server.on('listening', () => { doResolve(startPort, resolve); }); server.on('error', err => { if (err && ((<any>err).code === 'EADDRINUSE' || (<any>err).code === 'EACCES') && (countTried < giveUpAfter)) { startPort++; countTried++; server.listen(startPort, hostname); } else { doResolve(0, resolve); } }); server.on('close', () => { doResolve(0, resolve); }); server.listen(startPort, hostname); }); } function dispose(socket: net.Socket): void { try { socket.removeAllListeners('connect'); socket.removeAllListeners('error'); socket.end(); socket.destroy(); socket.unref(); } catch (error) { console.error(error); // otherwise this error would get lost in the callback chain } }
src/vs/base/node/ports.ts
0
https://github.com/microsoft/vscode/commit/324d1a25760c6abeb4a0492c0c5a22795b695bf4
[ 0.00017508506425656378, 0.00017303619824815542, 0.00016502295329701155, 0.0001736452686600387, 0.000002129371296177851 ]
{ "id": 3, "code_window": [ "\t\t}\n", "\t}\n", "\n", "\tprivate basicRenderElement(markdownValue: string, element: InteractiveTreeItem, index: number, templateData: IInteractiveListItemTemplate, fillInIncompleteTokens = false) {\n", "\t\tconst result = this.renderMarkdown(new MarkdownString(markdownValue), element, templateData.elementDisposables, templateData, fillInIncompleteTokens);\n", "\t\tdom.clearNode(templateData.value);\n", "\t\ttemplateData.value.appendChild(result.element);\n", "\t\ttemplateData.elementDisposables.add(result);\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tprivate basicRenderElement(markdownValue: string, element: InteractiveTreeItem, index: number, templateData: IInteractiveListItemTemplate) {\n", "\t\tconst fillInIncompleteTokens = isResponseVM(element) && (!element.isComplete || element.isCanceled || element.errorDetails?.responseIsFiltered);\n" ], "file_path": "src/vs/workbench/contrib/interactiveSession/browser/interactiveSessionListRenderer.ts", "type": "replace", "edit_start_line_idx": 240 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { Emitter, Event } from 'vs/base/common/event'; import { IMarkdownString, MarkdownString } from 'vs/base/common/htmlContent'; import { Disposable } from 'vs/base/common/lifecycle'; import { URI } from 'vs/base/common/uri'; import { ILogService } from 'vs/platform/log/common/log'; import { IInteractiveProgress, IInteractiveResponse, IInteractiveSession, IInteractiveSessionFollowup, IInteractiveSessionReplyFollowup, InteractiveSessionVoteDirection } from 'vs/workbench/contrib/interactiveSession/common/interactiveSessionService'; export interface IInteractiveRequestModel { readonly id: string; readonly username: string; readonly avatarIconUri?: URI; readonly message: string | IInteractiveSessionReplyFollowup; readonly response: IInteractiveResponseModel | undefined; } export interface IInteractiveResponseErrorDetails { message: string; responseIsIncomplete?: boolean; } export interface IInteractiveResponseModel { readonly onDidChange: Event<void>; readonly id: string; readonly providerId: string; readonly providerResponseId: string | undefined; readonly username: string; readonly avatarIconUri?: URI; readonly response: IMarkdownString; readonly isComplete: boolean; readonly isCanceled: boolean; readonly vote: InteractiveSessionVoteDirection | undefined; readonly followups?: IInteractiveSessionFollowup[] | undefined; readonly errorDetails?: IInteractiveResponseErrorDetails; setVote(vote: InteractiveSessionVoteDirection): void; } export function isRequest(item: unknown): item is IInteractiveRequestModel { return !!item && typeof (item as IInteractiveRequestModel).message !== 'undefined'; } export function isResponse(item: unknown): item is IInteractiveResponseModel { return !isRequest(item); } export class InteractiveRequestModel implements IInteractiveRequestModel { private static nextId = 0; public response: InteractiveResponseModel | undefined; private _id: string; public get id(): string { return this._id; } constructor(public readonly message: string | IInteractiveSessionReplyFollowup, public readonly username: string, public readonly avatarIconUri?: URI) { this._id = 'request_' + InteractiveRequestModel.nextId++; } } export class InteractiveResponseModel extends Disposable implements IInteractiveResponseModel { private readonly _onDidChange = this._register(new Emitter<void>()); readonly onDidChange = this._onDidChange.event; private static nextId = 0; private _id: string; public get id(): string { return this._id; } private _providerResponseId: string | undefined; public get providerResponseId(): string | undefined { return this._providerResponseId; } private _isComplete: boolean; public get isComplete(): boolean { return this._isComplete; } private _isCanceled: boolean; public get isCanceled(): boolean { return this._isCanceled; } private _vote: InteractiveSessionVoteDirection | undefined; public get vote(): InteractiveSessionVoteDirection | undefined { return this._vote; } private _followups: IInteractiveSessionFollowup[] | undefined; public get followups(): IInteractiveSessionFollowup[] | undefined { return this._followups; } private _response: IMarkdownString; public get response(): IMarkdownString { return this._response; } private _errorDetails: IInteractiveResponseErrorDetails | undefined; public get errorDetails(): IInteractiveResponseErrorDetails | undefined { return this._errorDetails; } constructor(response: IMarkdownString, public readonly username: string, public readonly providerId: string, public readonly avatarIconUri?: URI, isComplete: boolean = false, isCanceled = false, vote?: InteractiveSessionVoteDirection, providerResponseId?: string, errorDetails?: IInteractiveResponseErrorDetails, followups?: IInteractiveSessionFollowup[]) { super(); this._response = response; this._isComplete = isComplete; this._followups = followups; this._providerResponseId = providerResponseId; this._errorDetails = errorDetails; this._isCanceled = isCanceled; this._vote = vote; this._id = 'response_' + InteractiveResponseModel.nextId++; } updateContent(responsePart: string) { this._response = new MarkdownString(this.response.value + responsePart); this._onDidChange.fire(); } setProviderResponseId(providerResponseId: string) { this._providerResponseId = providerResponseId; } complete(errorDetails?: IInteractiveResponseErrorDetails): void { this._isComplete = true; this._errorDetails = errorDetails; this._onDidChange.fire(); } cancel(): void { this._isComplete = true; this._isCanceled = true; this._onDidChange.fire(); } setFollowups(followups: IInteractiveSessionFollowup[] | undefined): void { this._followups = followups; this._onDidChange.fire(); // Fire so that command followups get rendered on the row } setVote(vote: InteractiveSessionVoteDirection): void { this._vote = vote; this._onDidChange.fire(); } } export interface IInteractiveSessionModel { readonly onDidDispose: Event<void>; readonly onDidChange: Event<IInteractiveSessionChangeEvent>; readonly sessionId: number; readonly providerId: string; readonly welcomeMessage: IInteractiveSessionWelcomeMessageModel | undefined; readonly inputPlaceholder?: string; getRequests(): IInteractiveRequestModel[]; } export interface ISerializableInteractiveSessionsData { [providerId: string]: ISerializableInteractiveSessionData[]; } export interface ISerializableInteractiveSessionRequestData { providerResponseId: string | undefined; message: string; response: string | undefined; responseErrorDetails: IInteractiveResponseErrorDetails | undefined; followups: IInteractiveSessionFollowup[] | undefined; isCanceled: boolean | undefined; vote: InteractiveSessionVoteDirection | undefined; } export interface ISerializableInteractiveSessionData { requests: ISerializableInteractiveSessionRequestData[]; providerId: string; providerState: any; } export type IInteractiveSessionChangeEvent = IInteractiveSessionAddRequestEvent | IInteractiveSessionAddResponseEvent | IInteractiveSessionClearEvent; export interface IInteractiveSessionAddRequestEvent { kind: 'addRequest'; request: IInteractiveRequestModel; } export interface IInteractiveSessionAddResponseEvent { kind: 'addResponse'; response: IInteractiveResponseModel; } export interface IInteractiveSessionClearEvent { kind: 'clear'; } export class InteractiveSessionModel extends Disposable implements IInteractiveSessionModel { private readonly _onDidDispose = this._register(new Emitter<void>()); readonly onDidDispose = this._onDidDispose.event; private readonly _onDidChange = this._register(new Emitter<IInteractiveSessionChangeEvent>()); readonly onDidChange = this._onDidChange.event; private _requests: InteractiveRequestModel[]; private _providerState: any; get sessionId(): number { return this.session.id; } get inputPlaceholder(): string | undefined { return this.session.inputPlaceholder; } constructor( public readonly session: IInteractiveSession, public readonly providerId: string, public readonly welcomeMessage: InteractiveWelcomeMessageModel | undefined, initialData: ISerializableInteractiveSessionData | undefined, @ILogService private readonly logService: ILogService ) { super(); this._requests = initialData ? this._deserialize(initialData) : []; this._providerState = initialData ? initialData.providerState : undefined; } private _deserialize(obj: ISerializableInteractiveSessionData): InteractiveRequestModel[] { const requests = obj.requests; if (!Array.isArray(requests)) { this.logService.error(`Ignoring malformed session data: ${obj}`); return []; } return requests.map((raw: ISerializableInteractiveSessionRequestData) => { const request = new InteractiveRequestModel(raw.message, this.session.requesterUsername, this.session.requesterAvatarIconUri); if (raw.response || raw.responseErrorDetails) { request.response = new InteractiveResponseModel(new MarkdownString(raw.response), this.session.responderUsername, this.providerId, this.session.responderAvatarIconUri, true, raw.isCanceled, raw.vote, raw.providerResponseId, raw.responseErrorDetails, raw.followups); } return request; }); } acceptNewProviderState(providerState: any): void { this._providerState = providerState; } clear(): void { this._requests.forEach(r => r.response?.dispose()); this._requests = []; this._onDidChange.fire({ kind: 'clear' }); } getRequests(): InteractiveRequestModel[] { return this._requests; } addRequest(message: string | IInteractiveSessionReplyFollowup): InteractiveRequestModel { const request = new InteractiveRequestModel(message, this.session.requesterUsername, this.session.requesterAvatarIconUri); // TODO this is suspicious, maybe the request should know that it is "in progress" instead of having a fake response model. // But the response already knows that it is "in progress" and so does a map in the session service. request.response = new InteractiveResponseModel(new MarkdownString(''), this.session.responderUsername, this.providerId, this.session.responderAvatarIconUri); this._requests.push(request); this._onDidChange.fire({ kind: 'addRequest', request }); return request; } acceptResponseProgress(request: InteractiveRequestModel, progress: IInteractiveProgress): void { if (!request.response) { request.response = new InteractiveResponseModel(new MarkdownString(''), this.session.responderUsername, this.providerId, this.session.responderAvatarIconUri); } if ('content' in progress) { request.response.updateContent(progress.content); } else { request.response.setProviderResponseId(progress.responseId); } } cancelRequest(request: InteractiveRequestModel): void { if (request.response) { request.response.cancel(); } } completeResponse(request: InteractiveRequestModel, rawResponse: IInteractiveResponse): void { if (!request.response) { request.response = new InteractiveResponseModel(new MarkdownString(''), this.session.responderUsername, this.providerId, this.session.responderAvatarIconUri); } request.response.complete(rawResponse.errorDetails); } setFollowups(request: InteractiveRequestModel, followups: IInteractiveSessionFollowup[] | undefined): void { if (!request.response) { // Maybe something went wrong? return; } request.response.setFollowups(followups); } setResponse(request: InteractiveRequestModel, response: InteractiveResponseModel): void { request.response = response; this._onDidChange.fire({ kind: 'addResponse', response }); } toJSON(): ISerializableInteractiveSessionData { return { requests: this._requests.map((r): ISerializableInteractiveSessionRequestData => { return { providerResponseId: r.response?.providerResponseId, message: typeof r.message === 'string' ? r.message : r.message.message, response: r.response ? r.response.response.value : undefined, responseErrorDetails: r.response?.errorDetails, followups: r.response?.followups, isCanceled: r.response?.isCanceled, vote: r.response?.vote }; }), providerId: this.providerId, providerState: this._providerState }; } override dispose() { this.session.dispose?.(); this._requests.forEach(r => r.response?.dispose()); this._onDidDispose.fire(); super.dispose(); } } export type IInteractiveWelcomeMessageContent = IMarkdownString | IInteractiveSessionReplyFollowup[]; export interface IInteractiveSessionWelcomeMessageModel { readonly id: string; readonly content: IInteractiveWelcomeMessageContent[]; readonly username: string; readonly avatarIconUri?: URI; } export class InteractiveWelcomeMessageModel implements IInteractiveSessionWelcomeMessageModel { private static nextId = 0; private _id: string; public get id(): string { return this._id; } constructor(public readonly content: IInteractiveWelcomeMessageContent[], public readonly username: string, public readonly avatarIconUri?: URI) { this._id = 'welcome_' + InteractiveWelcomeMessageModel.nextId++; } }
src/vs/workbench/contrib/interactiveSession/common/interactiveSessionModel.ts
1
https://github.com/microsoft/vscode/commit/324d1a25760c6abeb4a0492c0c5a22795b695bf4
[ 0.002318396233022213, 0.0002966617757920176, 0.00016380577289965004, 0.0001734900288283825, 0.000389938271837309 ]
{ "id": 3, "code_window": [ "\t\t}\n", "\t}\n", "\n", "\tprivate basicRenderElement(markdownValue: string, element: InteractiveTreeItem, index: number, templateData: IInteractiveListItemTemplate, fillInIncompleteTokens = false) {\n", "\t\tconst result = this.renderMarkdown(new MarkdownString(markdownValue), element, templateData.elementDisposables, templateData, fillInIncompleteTokens);\n", "\t\tdom.clearNode(templateData.value);\n", "\t\ttemplateData.value.appendChild(result.element);\n", "\t\ttemplateData.elementDisposables.add(result);\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tprivate basicRenderElement(markdownValue: string, element: InteractiveTreeItem, index: number, templateData: IInteractiveListItemTemplate) {\n", "\t\tconst fillInIncompleteTokens = isResponseVM(element) && (!element.isComplete || element.isCanceled || element.errorDetails?.responseIsFiltered);\n" ], "file_path": "src/vs/workbench/contrib/interactiveSession/browser/interactiveSessionListRenderer.ts", "type": "replace", "edit_start_line_idx": 240 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import 'mocha'; import * as vscode from 'vscode'; import { onChangedDocument, retryUntilDocumentChanges, wait } from './testUtils'; export async function acceptFirstSuggestion(uri: vscode.Uri, _disposables: vscode.Disposable[]) { return retryUntilDocumentChanges(uri, { retries: 10, timeout: 0 }, _disposables, async () => { await vscode.commands.executeCommand('editor.action.triggerSuggest'); await wait(1000); await vscode.commands.executeCommand('acceptSelectedSuggestion'); }); } export async function typeCommitCharacter(uri: vscode.Uri, character: string, _disposables: vscode.Disposable[]) { const didChangeDocument = onChangedDocument(uri, _disposables); await vscode.commands.executeCommand('editor.action.triggerSuggest'); await wait(3000); // Give time for suggestions to show await vscode.commands.executeCommand('type', { text: character }); return await didChangeDocument; }
extensions/typescript-language-features/src/test/suggestTestHelpers.ts
0
https://github.com/microsoft/vscode/commit/324d1a25760c6abeb4a0492c0c5a22795b695bf4
[ 0.00017565912276040763, 0.00017335118900518864, 0.00017043505795300007, 0.00017395932809449732, 0.0000021756386558990926 ]
{ "id": 3, "code_window": [ "\t\t}\n", "\t}\n", "\n", "\tprivate basicRenderElement(markdownValue: string, element: InteractiveTreeItem, index: number, templateData: IInteractiveListItemTemplate, fillInIncompleteTokens = false) {\n", "\t\tconst result = this.renderMarkdown(new MarkdownString(markdownValue), element, templateData.elementDisposables, templateData, fillInIncompleteTokens);\n", "\t\tdom.clearNode(templateData.value);\n", "\t\ttemplateData.value.appendChild(result.element);\n", "\t\ttemplateData.elementDisposables.add(result);\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tprivate basicRenderElement(markdownValue: string, element: InteractiveTreeItem, index: number, templateData: IInteractiveListItemTemplate) {\n", "\t\tconst fillInIncompleteTokens = isResponseVM(element) && (!element.isComplete || element.isCanceled || element.errorDetails?.responseIsFiltered);\n" ], "file_path": "src/vs/workbench/contrib/interactiveSession/browser/interactiveSessionListRenderer.ts", "type": "replace", "edit_start_line_idx": 240 }
/*--------------------------------------------------------------------------------------------- * 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, DisposableStore } from 'vs/base/common/lifecycle'; import { Selection } from 'vs/editor/common/core/selection'; import { ICommand } from 'vs/editor/common/editorCommon'; import { EncodedTokenizationResult, IState, TokenizationRegistry } from 'vs/editor/common/languages'; import { ColorId, MetadataConsts } from 'vs/editor/common/encodedTokenAttributes'; import { CommentRule } from 'vs/editor/common/languages/languageConfiguration'; import { ILanguageConfigurationService } from 'vs/editor/common/languages/languageConfigurationRegistry'; import { NullState } from 'vs/editor/common/languages/nullTokenize'; import { ILanguageService } from 'vs/editor/common/languages/language'; import { ILinePreflightData, IPreflightData, ISimpleModel, LineCommentCommand, Type } from 'vs/editor/contrib/comment/browser/lineCommentCommand'; import { testCommand } from 'vs/editor/test/browser/testCommand'; import { IInstantiationService, ServicesAccessor } from 'vs/platform/instantiation/common/instantiation'; import { TestLanguageConfigurationService } from 'vs/editor/test/common/modes/testLanguageConfigurationService'; function createTestCommandHelper(commentsConfig: CommentRule, commandFactory: (accessor: ServicesAccessor, selection: Selection) => ICommand): (lines: string[], selection: Selection, expectedLines: string[], expectedSelection: Selection) => void { return (lines: string[], selection: Selection, expectedLines: string[], expectedSelection: Selection) => { const languageId = 'commentMode'; const prepare = (accessor: ServicesAccessor, disposables: DisposableStore) => { const languageConfigurationService = accessor.get(ILanguageConfigurationService); const languageService = accessor.get(ILanguageService); disposables.add(languageService.registerLanguage({ id: languageId })); disposables.add(languageConfigurationService.register(languageId, { comments: commentsConfig })); }; testCommand(lines, languageId, selection, commandFactory, expectedLines, expectedSelection, false, prepare); }; } suite('Editor Contrib - Line Comment Command', () => { const testLineCommentCommand = createTestCommandHelper( { lineComment: '!@#', blockComment: ['<!@#', '#@!>'] }, (accessor, sel) => new LineCommentCommand(accessor.get(ILanguageConfigurationService), sel, 4, Type.Toggle, true, true) ); const testAddLineCommentCommand = createTestCommandHelper( { lineComment: '!@#', blockComment: ['<!@#', '#@!>'] }, (accessor, sel) => new LineCommentCommand(accessor.get(ILanguageConfigurationService), sel, 4, Type.ForceAdd, true, true) ); test('comment single line', function () { testLineCommentCommand( [ 'some text', '\tsome more text' ], new Selection(1, 1, 1, 1), [ '!@# some text', '\tsome more text' ], new Selection(1, 5, 1, 5) ); }); test('case insensitive', function () { const testLineCommentCommand = createTestCommandHelper( { lineComment: 'rem' }, (accessor, sel) => new LineCommentCommand(accessor.get(ILanguageConfigurationService), sel, 4, Type.Toggle, true, true) ); testLineCommentCommand( [ 'REM some text' ], new Selection(1, 1, 1, 1), [ 'some text' ], new Selection(1, 1, 1, 1) ); }); function createSimpleModel(lines: string[]): ISimpleModel { return { getLineContent: (lineNumber: number) => { return lines[lineNumber - 1]; } }; } function createBasicLinePreflightData(commentTokens: string[]): ILinePreflightData[] { return commentTokens.map((commentString) => { const r: ILinePreflightData = { ignore: false, commentStr: commentString, commentStrOffset: 0, commentStrLength: commentString.length }; return r; }); } test('_analyzeLines', () => { let r: IPreflightData; r = LineCommentCommand._analyzeLines(Type.Toggle, true, createSimpleModel([ '\t\t', ' ', ' c', '\t\td' ]), createBasicLinePreflightData(['//', 'rem', '!@#', '!@#']), 1, true, false, new TestLanguageConfigurationService()); if (!r.supported) { throw new Error(`unexpected`); } assert.strictEqual(r.shouldRemoveComments, false); // Does not change `commentStr` assert.strictEqual(r.lines[0].commentStr, '//'); assert.strictEqual(r.lines[1].commentStr, 'rem'); assert.strictEqual(r.lines[2].commentStr, '!@#'); assert.strictEqual(r.lines[3].commentStr, '!@#'); // Fills in `isWhitespace` assert.strictEqual(r.lines[0].ignore, true); assert.strictEqual(r.lines[1].ignore, true); assert.strictEqual(r.lines[2].ignore, false); assert.strictEqual(r.lines[3].ignore, false); // Fills in `commentStrOffset` assert.strictEqual(r.lines[0].commentStrOffset, 2); assert.strictEqual(r.lines[1].commentStrOffset, 4); assert.strictEqual(r.lines[2].commentStrOffset, 4); assert.strictEqual(r.lines[3].commentStrOffset, 2); r = LineCommentCommand._analyzeLines(Type.Toggle, true, createSimpleModel([ '\t\t', ' rem ', ' !@# c', '\t\t!@#d' ]), createBasicLinePreflightData(['//', 'rem', '!@#', '!@#']), 1, true, false, new TestLanguageConfigurationService()); if (!r.supported) { throw new Error(`unexpected`); } assert.strictEqual(r.shouldRemoveComments, true); // Does not change `commentStr` assert.strictEqual(r.lines[0].commentStr, '//'); assert.strictEqual(r.lines[1].commentStr, 'rem'); assert.strictEqual(r.lines[2].commentStr, '!@#'); assert.strictEqual(r.lines[3].commentStr, '!@#'); // Fills in `isWhitespace` assert.strictEqual(r.lines[0].ignore, true); assert.strictEqual(r.lines[1].ignore, false); assert.strictEqual(r.lines[2].ignore, false); assert.strictEqual(r.lines[3].ignore, false); // Fills in `commentStrOffset` assert.strictEqual(r.lines[0].commentStrOffset, 2); assert.strictEqual(r.lines[1].commentStrOffset, 4); assert.strictEqual(r.lines[2].commentStrOffset, 4); assert.strictEqual(r.lines[3].commentStrOffset, 2); // Fills in `commentStrLength` assert.strictEqual(r.lines[0].commentStrLength, 2); assert.strictEqual(r.lines[1].commentStrLength, 4); assert.strictEqual(r.lines[2].commentStrLength, 4); assert.strictEqual(r.lines[3].commentStrLength, 3); }); test('_normalizeInsertionPoint', () => { const runTest = (mixedArr: any[], tabSize: number, expected: number[], testName: string) => { const model = createSimpleModel(mixedArr.filter((item, idx) => idx % 2 === 0)); const offsets = mixedArr.filter((item, idx) => idx % 2 === 1).map(offset => { return { commentStrOffset: offset, ignore: false }; }); LineCommentCommand._normalizeInsertionPoint(model, offsets, 1, tabSize); const actual = offsets.map(item => item.commentStrOffset); assert.deepStrictEqual(actual, expected, testName); }; // Bug 16696:[comment] comments not aligned in this case runTest([ ' XX', 2, ' YY', 4 ], 4, [0, 0], 'Bug 16696'); runTest([ '\t\t\tXX', 3, ' \tYY', 5, ' ZZ', 8, '\t\tTT', 2 ], 4, [2, 5, 8, 2], 'Test1'); runTest([ '\t\t\t XX', 6, ' \t\t\t\tYY', 8, ' ZZ', 8, '\t\t TT', 6 ], 4, [2, 5, 8, 2], 'Test2'); runTest([ '\t\t', 2, '\t\t\t', 3, '\t\t\t\t', 4, '\t\t\t', 3 ], 4, [2, 2, 2, 2], 'Test3'); runTest([ '\t\t', 2, '\t\t\t', 3, '\t\t\t\t', 4, '\t\t\t', 3, ' ', 4 ], 2, [2, 2, 2, 2, 4], 'Test4'); runTest([ '\t\t', 2, '\t\t\t', 3, '\t\t\t\t', 4, '\t\t\t', 3, ' ', 4 ], 4, [1, 1, 1, 1, 4], 'Test5'); runTest([ ' \t', 2, ' \t', 3, ' \t', 4, ' ', 4, '\t', 1 ], 4, [2, 3, 4, 4, 1], 'Test6'); runTest([ ' \t\t', 3, ' \t\t', 4, ' \t\t', 5, ' \t', 5, '\t', 1 ], 4, [2, 3, 4, 4, 1], 'Test7'); runTest([ '\t', 1, ' ', 4 ], 4, [1, 4], 'Test8:4'); runTest([ '\t', 1, ' ', 3 ], 4, [0, 0], 'Test8:3'); runTest([ '\t', 1, ' ', 2 ], 4, [0, 0], 'Test8:2'); runTest([ '\t', 1, ' ', 1 ], 4, [0, 0], 'Test8:1'); runTest([ '\t', 1, '', 0 ], 4, [0, 0], 'Test8:0'); }); test('detects indentation', function () { testLineCommentCommand( [ '\tsome text', '\tsome more text' ], new Selection(2, 2, 1, 1), [ '\t!@# some text', '\t!@# some more text' ], new Selection(2, 2, 1, 1) ); }); test('detects mixed indentation', function () { testLineCommentCommand( [ '\tsome text', ' some more text' ], new Selection(2, 2, 1, 1), [ '\t!@# some text', ' !@# some more text' ], new Selection(2, 2, 1, 1) ); }); test('ignores whitespace lines', function () { testLineCommentCommand( [ '\tsome text', '\t ', '', '\tsome more text' ], new Selection(4, 2, 1, 1), [ '\t!@# some text', '\t ', '', '\t!@# some more text' ], new Selection(4, 2, 1, 1) ); }); test('removes its own', function () { testLineCommentCommand( [ '\t!@# some text', '\t ', '\t\t!@# some more text' ], new Selection(3, 2, 1, 1), [ '\tsome text', '\t ', '\t\tsome more text' ], new Selection(3, 2, 1, 1) ); }); test('works in only whitespace', function () { testLineCommentCommand( [ '\t ', '\t', '\t\tsome more text' ], new Selection(3, 1, 1, 1), [ '\t!@# ', '\t!@# ', '\t\tsome more text' ], new Selection(3, 1, 1, 1) ); }); test('bug 9697 - whitespace before comment token', function () { testLineCommentCommand( [ '\t !@#first', '\tsecond line' ], new Selection(1, 1, 1, 1), [ '\t first', '\tsecond line' ], new Selection(1, 1, 1, 1) ); }); test('bug 10162 - line comment before caret', function () { testLineCommentCommand( [ 'first!@#', '\tsecond line' ], new Selection(1, 1, 1, 1), [ '!@# first!@#', '\tsecond line' ], new Selection(1, 5, 1, 5) ); }); test('comment single line - leading whitespace', function () { testLineCommentCommand( [ 'first!@#', '\tsecond line' ], new Selection(2, 3, 2, 1), [ 'first!@#', '\t!@# second line' ], new Selection(2, 7, 2, 1) ); }); test('ignores invisible selection', function () { testLineCommentCommand( [ 'first', '\tsecond line', 'third line', 'fourth line', 'fifth' ], new Selection(2, 1, 1, 1), [ '!@# first', '\tsecond line', 'third line', 'fourth line', 'fifth' ], new Selection(2, 1, 1, 5) ); }); test('multiple lines', function () { testLineCommentCommand( [ 'first', '\tsecond line', 'third line', 'fourth line', 'fifth' ], new Selection(2, 4, 1, 1), [ '!@# first', '!@# \tsecond line', 'third line', 'fourth line', 'fifth' ], new Selection(2, 8, 1, 5) ); }); test('multiple modes on multiple lines', function () { testLineCommentCommand( [ 'first', '\tsecond line', 'third line', 'fourth line', 'fifth' ], new Selection(4, 4, 3, 1), [ 'first', '\tsecond line', '!@# third line', '!@# fourth line', 'fifth' ], new Selection(4, 8, 3, 5) ); }); test('toggle single line', function () { testLineCommentCommand( [ 'first', '\tsecond line', 'third line', 'fourth line', 'fifth' ], new Selection(1, 1, 1, 1), [ '!@# first', '\tsecond line', 'third line', 'fourth line', 'fifth' ], new Selection(1, 5, 1, 5) ); testLineCommentCommand( [ '!@# first', '\tsecond line', 'third line', 'fourth line', 'fifth' ], new Selection(1, 4, 1, 4), [ 'first', '\tsecond line', 'third line', 'fourth line', 'fifth' ], new Selection(1, 1, 1, 1) ); }); test('toggle multiple lines', function () { testLineCommentCommand( [ 'first', '\tsecond line', 'third line', 'fourth line', 'fifth' ], new Selection(2, 4, 1, 1), [ '!@# first', '!@# \tsecond line', 'third line', 'fourth line', 'fifth' ], new Selection(2, 8, 1, 5) ); testLineCommentCommand( [ '!@# first', '!@# \tsecond line', 'third line', 'fourth line', 'fifth' ], new Selection(2, 7, 1, 4), [ 'first', '\tsecond line', 'third line', 'fourth line', 'fifth' ], new Selection(2, 3, 1, 1) ); }); test('issue #5964: Ctrl+/ to create comment when cursor is at the beginning of the line puts the cursor in a strange position', () => { testLineCommentCommand( [ 'first', '\tsecond line', 'third line', 'fourth line', 'fifth' ], new Selection(1, 1, 1, 1), [ '!@# first', '\tsecond line', 'third line', 'fourth line', 'fifth' ], new Selection(1, 5, 1, 5) ); }); test('issue #35673: Comment hotkeys throws the cursor before the comment', () => { testLineCommentCommand( [ 'first', '', '\tsecond line', 'third line', 'fourth line', 'fifth' ], new Selection(2, 1, 2, 1), [ 'first', '!@# ', '\tsecond line', 'third line', 'fourth line', 'fifth' ], new Selection(2, 5, 2, 5) ); testLineCommentCommand( [ 'first', '\t', '\tsecond line', 'third line', 'fourth line', 'fifth' ], new Selection(2, 2, 2, 2), [ 'first', '\t!@# ', '\tsecond line', 'third line', 'fourth line', 'fifth' ], new Selection(2, 6, 2, 6) ); }); test('issue #2837 "Add Line Comment" fault when blank lines involved', function () { testAddLineCommentCommand( [ ' if displayName == "":', ' displayName = groupName', ' description = getAttr(attributes, "description")', ' mailAddress = getAttr(attributes, "mail")', '', ' print "||Group name|%s|" % displayName', ' print "||Description|%s|" % description', ' print "||Email address|[mailto:%s]|" % mailAddress`', ], new Selection(1, 1, 8, 56), [ ' !@# if displayName == "":', ' !@# displayName = groupName', ' !@# description = getAttr(attributes, "description")', ' !@# mailAddress = getAttr(attributes, "mail")', '', ' !@# print "||Group name|%s|" % displayName', ' !@# print "||Description|%s|" % description', ' !@# print "||Email address|[mailto:%s]|" % mailAddress`', ], new Selection(1, 1, 8, 60) ); }); test('issue #47004: Toggle comments shouldn\'t move cursor', () => { testAddLineCommentCommand( [ ' A line', ' Another line' ], new Selection(2, 7, 1, 1), [ ' !@# A line', ' !@# Another line' ], new Selection(2, 11, 1, 1) ); }); test('insertSpace false', () => { const testLineCommentCommand = createTestCommandHelper( { lineComment: '!@#' }, (accessor, sel) => new LineCommentCommand(accessor.get(ILanguageConfigurationService), sel, 4, Type.Toggle, false, true) ); testLineCommentCommand( [ 'some text' ], new Selection(1, 1, 1, 1), [ '!@#some text' ], new Selection(1, 4, 1, 4) ); }); test('insertSpace false does not remove space', () => { const testLineCommentCommand = createTestCommandHelper( { lineComment: '!@#' }, (accessor, sel) => new LineCommentCommand(accessor.get(ILanguageConfigurationService), sel, 4, Type.Toggle, false, true) ); testLineCommentCommand( [ '!@# some text' ], new Selection(1, 1, 1, 1), [ ' some text' ], new Selection(1, 1, 1, 1) ); }); suite('ignoreEmptyLines false', () => { const testLineCommentCommand = createTestCommandHelper( { lineComment: '!@#', blockComment: ['<!@#', '#@!>'] }, (accessor, sel) => new LineCommentCommand(accessor.get(ILanguageConfigurationService), sel, 4, Type.Toggle, true, false) ); test('does not ignore whitespace lines', () => { testLineCommentCommand( [ '\tsome text', '\t ', '', '\tsome more text' ], new Selection(4, 2, 1, 1), [ '!@# \tsome text', '!@# \t ', '!@# ', '!@# \tsome more text' ], new Selection(4, 6, 1, 5) ); }); test('removes its own', function () { testLineCommentCommand( [ '\t!@# some text', '\t ', '\t\t!@# some more text' ], new Selection(3, 2, 1, 1), [ '\tsome text', '\t ', '\t\tsome more text' ], new Selection(3, 2, 1, 1) ); }); test('works in only whitespace', function () { testLineCommentCommand( [ '\t ', '\t', '\t\tsome more text' ], new Selection(3, 1, 1, 1), [ '\t!@# ', '\t!@# ', '\t\tsome more text' ], new Selection(3, 1, 1, 1) ); }); test('comments single line', function () { testLineCommentCommand( [ 'some text', '\tsome more text' ], new Selection(1, 1, 1, 1), [ '!@# some text', '\tsome more text' ], new Selection(1, 5, 1, 5) ); }); test('detects indentation', function () { testLineCommentCommand( [ '\tsome text', '\tsome more text' ], new Selection(2, 2, 1, 1), [ '\t!@# some text', '\t!@# some more text' ], new Selection(2, 2, 1, 1) ); }); }); }); suite('Editor Contrib - Line Comment As Block Comment', () => { const testLineCommentCommand = createTestCommandHelper( { lineComment: '', blockComment: ['(', ')'] }, (accessor, sel) => new LineCommentCommand(accessor.get(ILanguageConfigurationService), sel, 4, Type.Toggle, true, true) ); test('fall back to block comment command', function () { testLineCommentCommand( [ 'first', '\tsecond line', 'third line', 'fourth line', 'fifth' ], new Selection(1, 1, 1, 1), [ '( first )', '\tsecond line', 'third line', 'fourth line', 'fifth' ], new Selection(1, 3, 1, 3) ); }); test('fall back to block comment command - toggle', function () { testLineCommentCommand( [ '(first)', '\tsecond line', 'third line', 'fourth line', 'fifth' ], new Selection(1, 7, 1, 2), [ 'first', '\tsecond line', 'third line', 'fourth line', 'fifth' ], new Selection(1, 6, 1, 1) ); }); test('bug 9513 - expand single line to uncomment auto block', function () { testLineCommentCommand( [ 'first', '\tsecond line', 'third line', 'fourth line', 'fifth' ], new Selection(1, 1, 1, 1), [ '( first )', '\tsecond line', 'third line', 'fourth line', 'fifth' ], new Selection(1, 3, 1, 3) ); }); test('bug 9691 - always expand selection to line boundaries', function () { testLineCommentCommand( [ 'first', '\tsecond line', 'third line', 'fourth line', 'fifth' ], new Selection(3, 2, 1, 3), [ '( first', '\tsecond line', 'third line )', 'fourth line', 'fifth' ], new Selection(3, 2, 1, 5) ); testLineCommentCommand( [ '(first', '\tsecond line', 'third line)', 'fourth line', 'fifth' ], new Selection(3, 11, 1, 2), [ 'first', '\tsecond line', 'third line', 'fourth line', 'fifth' ], new Selection(3, 11, 1, 1) ); }); }); suite('Editor Contrib - Line Comment As Block Comment 2', () => { const testLineCommentCommand = createTestCommandHelper( { lineComment: null, blockComment: ['<!@#', '#@!>'] }, (accessor, sel) => new LineCommentCommand(accessor.get(ILanguageConfigurationService), sel, 4, Type.Toggle, true, true) ); test('no selection => uses indentation', function () { testLineCommentCommand( [ '\t\tfirst\t ', '\t\tsecond line', '\tthird line', 'fourth line', '\t\t<!@#fifth#@!>\t\t' ], new Selection(1, 1, 1, 1), [ '\t\t<!@# first\t #@!>', '\t\tsecond line', '\tthird line', 'fourth line', '\t\t<!@#fifth#@!>\t\t' ], new Selection(1, 1, 1, 1) ); testLineCommentCommand( [ '\t\t<!@#first\t #@!>', '\t\tsecond line', '\tthird line', 'fourth line', '\t\t<!@#fifth#@!>\t\t' ], new Selection(1, 1, 1, 1), [ '\t\tfirst\t ', '\t\tsecond line', '\tthird line', 'fourth line', '\t\t<!@#fifth#@!>\t\t' ], new Selection(1, 1, 1, 1) ); }); test('can remove', function () { testLineCommentCommand( [ '\t\tfirst\t ', '\t\tsecond line', '\tthird line', 'fourth line', '\t\t<!@#fifth#@!>\t\t' ], new Selection(5, 1, 5, 1), [ '\t\tfirst\t ', '\t\tsecond line', '\tthird line', 'fourth line', '\t\tfifth\t\t' ], new Selection(5, 1, 5, 1) ); testLineCommentCommand( [ '\t\tfirst\t ', '\t\tsecond line', '\tthird line', 'fourth line', '\t\t<!@#fifth#@!>\t\t' ], new Selection(5, 3, 5, 3), [ '\t\tfirst\t ', '\t\tsecond line', '\tthird line', 'fourth line', '\t\tfifth\t\t' ], new Selection(5, 3, 5, 3) ); testLineCommentCommand( [ '\t\tfirst\t ', '\t\tsecond line', '\tthird line', 'fourth line', '\t\t<!@#fifth#@!>\t\t' ], new Selection(5, 4, 5, 4), [ '\t\tfirst\t ', '\t\tsecond line', '\tthird line', 'fourth line', '\t\tfifth\t\t' ], new Selection(5, 3, 5, 3) ); testLineCommentCommand( [ '\t\tfirst\t ', '\t\tsecond line', '\tthird line', 'fourth line', '\t\t<!@#fifth#@!>\t\t' ], new Selection(5, 16, 5, 3), [ '\t\tfirst\t ', '\t\tsecond line', '\tthird line', 'fourth line', '\t\tfifth\t\t' ], new Selection(5, 8, 5, 3) ); testLineCommentCommand( [ '\t\tfirst\t ', '\t\tsecond line', '\tthird line', 'fourth line', '\t\t<!@#fifth#@!>\t\t' ], new Selection(5, 12, 5, 7), [ '\t\tfirst\t ', '\t\tsecond line', '\tthird line', 'fourth line', '\t\tfifth\t\t' ], new Selection(5, 8, 5, 3) ); testLineCommentCommand( [ '\t\tfirst\t ', '\t\tsecond line', '\tthird line', 'fourth line', '\t\t<!@#fifth#@!>\t\t' ], new Selection(5, 18, 5, 18), [ '\t\tfirst\t ', '\t\tsecond line', '\tthird line', 'fourth line', '\t\tfifth\t\t' ], new Selection(5, 10, 5, 10) ); }); test('issue #993: Remove comment does not work consistently in HTML', () => { testLineCommentCommand( [ ' asd qwe', ' asd qwe', '' ], new Selection(1, 1, 3, 1), [ ' <!@# asd qwe', ' asd qwe #@!>', '' ], new Selection(1, 1, 3, 1) ); testLineCommentCommand( [ ' <!@#asd qwe', ' asd qwe#@!>', '' ], new Selection(1, 1, 3, 1), [ ' asd qwe', ' asd qwe', '' ], new Selection(1, 1, 3, 1) ); }); }); suite('Editor Contrib - Line Comment in mixed modes', () => { const OUTER_LANGUAGE_ID = 'outerMode'; const INNER_LANGUAGE_ID = 'innerMode'; class OuterMode extends Disposable { private readonly languageId = OUTER_LANGUAGE_ID; constructor( commentsConfig: CommentRule, @ILanguageService languageService: ILanguageService, @ILanguageConfigurationService languageConfigurationService: ILanguageConfigurationService ) { super(); this._register(languageService.registerLanguage({ id: this.languageId })); this._register(languageConfigurationService.register(this.languageId, { comments: commentsConfig })); this._register(TokenizationRegistry.register(this.languageId, { getInitialState: (): IState => NullState, tokenize: () => { throw new Error('not implemented'); }, tokenizeEncoded: (line: string, hasEOL: boolean, state: IState): EncodedTokenizationResult => { const languageId = (/^ /.test(line) ? INNER_LANGUAGE_ID : OUTER_LANGUAGE_ID); const encodedLanguageId = languageService.languageIdCodec.encodeLanguageId(languageId); const tokens = new Uint32Array(1 << 1); tokens[(0 << 1)] = 0; tokens[(0 << 1) + 1] = ( (ColorId.DefaultForeground << MetadataConsts.FOREGROUND_OFFSET) | (encodedLanguageId << MetadataConsts.LANGUAGEID_OFFSET) ); return new EncodedTokenizationResult(tokens, state); } })); } } class InnerMode extends Disposable { private readonly languageId = INNER_LANGUAGE_ID; constructor( commentsConfig: CommentRule, @ILanguageService languageService: ILanguageService, @ILanguageConfigurationService languageConfigurationService: ILanguageConfigurationService ) { super(); this._register(languageService.registerLanguage({ id: this.languageId })); this._register(languageConfigurationService.register(this.languageId, { comments: commentsConfig })); } } function testLineCommentCommand(lines: string[], selection: Selection, expectedLines: string[], expectedSelection: Selection): void { const setup = (accessor: ServicesAccessor, disposables: DisposableStore) => { const instantiationService = accessor.get(IInstantiationService); disposables.add(instantiationService.createInstance(OuterMode, { lineComment: '//', blockComment: ['/*', '*/'] })); disposables.add(instantiationService.createInstance(InnerMode, { lineComment: null, blockComment: ['{/*', '*/}'] })); }; testCommand( lines, OUTER_LANGUAGE_ID, selection, (accessor, sel) => new LineCommentCommand(accessor.get(ILanguageConfigurationService), sel, 4, Type.Toggle, true, true), expectedLines, expectedSelection, true, setup ); } test('issue #24047 (part 1): Commenting code in JSX files', () => { testLineCommentCommand( [ 'import React from \'react\';', 'const Loader = () => (', ' <div>', ' Loading...', ' </div>', ');', 'export default Loader;' ], new Selection(1, 1, 7, 22), [ '// import React from \'react\';', '// const Loader = () => (', '// <div>', '// Loading...', '// </div>', '// );', '// export default Loader;' ], new Selection(1, 4, 7, 25), ); }); test('issue #24047 (part 2): Commenting code in JSX files', () => { testLineCommentCommand( [ 'import React from \'react\';', 'const Loader = () => (', ' <div>', ' Loading...', ' </div>', ');', 'export default Loader;' ], new Selection(3, 4, 3, 4), [ 'import React from \'react\';', 'const Loader = () => (', ' {/* <div> */}', ' Loading...', ' </div>', ');', 'export default Loader;' ], new Selection(3, 8, 3, 8), ); }); test('issue #36173: Commenting code in JSX tag body', () => { testLineCommentCommand( [ '<div>', ' {123}', '</div>', ], new Selection(2, 4, 2, 4), [ '<div>', ' {/* {123} */}', '</div>', ], new Selection(2, 8, 2, 8), ); }); });
src/vs/editor/contrib/comment/test/browser/lineCommentCommand.test.ts
0
https://github.com/microsoft/vscode/commit/324d1a25760c6abeb4a0492c0c5a22795b695bf4
[ 0.00017655968258623034, 0.0001716794795356691, 0.00016498126205988228, 0.00017188479250762612, 0.0000020027434857183835 ]
{ "id": 3, "code_window": [ "\t\t}\n", "\t}\n", "\n", "\tprivate basicRenderElement(markdownValue: string, element: InteractiveTreeItem, index: number, templateData: IInteractiveListItemTemplate, fillInIncompleteTokens = false) {\n", "\t\tconst result = this.renderMarkdown(new MarkdownString(markdownValue), element, templateData.elementDisposables, templateData, fillInIncompleteTokens);\n", "\t\tdom.clearNode(templateData.value);\n", "\t\ttemplateData.value.appendChild(result.element);\n", "\t\ttemplateData.elementDisposables.add(result);\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tprivate basicRenderElement(markdownValue: string, element: InteractiveTreeItem, index: number, templateData: IInteractiveListItemTemplate) {\n", "\t\tconst fillInIncompleteTokens = isResponseVM(element) && (!element.isComplete || element.isCanceled || element.errorDetails?.responseIsFiltered);\n" ], "file_path": "src/vs/workbench/contrib/interactiveSession/browser/interactiveSessionListRenderer.ts", "type": "replace", "edit_start_line_idx": 240 }
#!/usr/bin/env bash # # Copyright (c) Microsoft Corporation. All rights reserved. # case "$1" in --inspect*) INSPECT="$1"; shift;; esac realdir() { SOURCE=$1 while [ -h "$SOURCE" ]; do DIR=$(dirname "$SOURCE") SOURCE=$(readlink "$SOURCE") [[ $SOURCE != /* ]] && SOURCE=$DIR/$SOURCE done echo "$( cd -P "$(dirname "$SOURCE")" >/dev/null 2>&1 && pwd )" } ROOT="$(dirname "$(realdir "$0")")" "$ROOT/node" ${INSPECT:-} "$ROOT/out/server-main.js" "$@"
resources/server/bin/code-server-darwin.sh
0
https://github.com/microsoft/vscode/commit/324d1a25760c6abeb4a0492c0c5a22795b695bf4
[ 0.00017370058048982173, 0.00017346173990517855, 0.0001732531382003799, 0.00017343148647341877, 1.839155316929464e-7 ]
{ "id": 4, "code_window": [ "\t\tif (element.isCanceled) {\n", "\t\t\tthis.traceLayout('runProgressiveRender', `canceled, index=${index}`);\n", "\t\t\telement.renderData = undefined;\n", "\t\t\tthis.basicRenderElement(element.response.value, element, index, templateData, true);\n", "\t\t\tisFullyRendered = true;\n", "\t\t} else {\n", "\t\t\t// TODO- this method has the side effect of updating element.renderData\n", "\t\t\tconst toRender = this.getProgressiveMarkdownToRender(element);\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tthis.basicRenderElement(element.response.value, element, index, templateData);\n" ], "file_path": "src/vs/workbench/contrib/interactiveSession/browser/interactiveSessionListRenderer.ts", "type": "replace", "edit_start_line_idx": 301 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as dom from 'vs/base/browser/dom'; import { renderIcon } from 'vs/base/browser/ui/iconLabel/iconLabels'; import { IListVirtualDelegate } from 'vs/base/browser/ui/list/list'; import { IListAccessibilityProvider } from 'vs/base/browser/ui/list/listWidget'; import { ITreeNode, ITreeRenderer } from 'vs/base/browser/ui/tree/tree'; import { IntervalTimer } from 'vs/base/common/async'; import { Codicon } from 'vs/base/common/codicons'; import { Emitter, Event } from 'vs/base/common/event'; import { FuzzyScore } from 'vs/base/common/filters'; import { IMarkdownString, MarkdownString } from 'vs/base/common/htmlContent'; import { Disposable, DisposableStore, IDisposable } from 'vs/base/common/lifecycle'; import { ResourceMap } from 'vs/base/common/map'; import { FileAccess } from 'vs/base/common/network'; import { ThemeIcon } from 'vs/base/common/themables'; import { EditorExtensionsRegistry } from 'vs/editor/browser/editorExtensions'; import { CodeEditorWidget } from 'vs/editor/browser/widget/codeEditorWidget'; import { EDITOR_FONT_DEFAULTS, IEditorOptions } from 'vs/editor/common/config/editorOptions'; import { Range } from 'vs/editor/common/core/range'; import { ILanguageService } from 'vs/editor/common/languages/language'; import { ITextModel } from 'vs/editor/common/model'; import { IModelService } from 'vs/editor/common/services/model'; import { BracketMatchingController } from 'vs/editor/contrib/bracketMatching/browser/bracketMatching'; import { ContextMenuController } from 'vs/editor/contrib/contextmenu/browser/contextmenu'; import { IMarkdownRenderResult, MarkdownRenderer } from 'vs/editor/contrib/markdownRenderer/browser/markdownRenderer'; import { ViewportSemanticTokensContribution } from 'vs/editor/contrib/semanticTokens/browser/viewportSemanticTokens'; import { SmartSelectController } from 'vs/editor/contrib/smartSelect/browser/smartSelect'; import { WordHighlighterContribution } from 'vs/editor/contrib/wordHighlighter/browser/wordHighlighter'; import { localize } from 'vs/nls'; import { MenuWorkbenchToolBar } from 'vs/platform/actions/browser/toolbar'; import { MenuId } from 'vs/platform/actions/common/actions'; import { ICommandService } from 'vs/platform/commands/common/commands'; import { IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { IContextKeyService } from 'vs/platform/contextkey/common/contextkey'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { ServiceCollection } from 'vs/platform/instantiation/common/serviceCollection'; import { ILogService } from 'vs/platform/log/common/log'; import { defaultButtonStyles } from 'vs/platform/theme/browser/defaultStyles'; import { MenuPreventer } from 'vs/workbench/contrib/codeEditor/browser/menuPreventer'; import { SelectionClipboardContributionID } from 'vs/workbench/contrib/codeEditor/browser/selectionClipboard'; import { getSimpleEditorOptions } from 'vs/workbench/contrib/codeEditor/browser/simpleEditorOptions'; import { IInteractiveSessionCodeBlockActionContext } from 'vs/workbench/contrib/interactiveSession/browser/actions/interactiveSessionCodeblockActions'; import { InteractiveSessionFollowups } from 'vs/workbench/contrib/interactiveSession/browser/interactiveSessionFollowups'; import { InteractiveSessionEditorOptions } from 'vs/workbench/contrib/interactiveSession/browser/interactiveSessionOptions'; import { CONTEXT_RESPONSE_HAS_PROVIDER_ID, CONTEXT_RESPONSE_VOTE } from 'vs/workbench/contrib/interactiveSession/common/interactiveSessionContextKeys'; import { IInteractiveSessionReplyFollowup, IInteractiveSessionService, IInteractiveSlashCommand, InteractiveSessionVoteDirection } from 'vs/workbench/contrib/interactiveSession/common/interactiveSessionService'; import { IInteractiveRequestViewModel, IInteractiveResponseViewModel, IInteractiveWelcomeMessageViewModel, isRequestVM, isResponseVM, isWelcomeVM } from 'vs/workbench/contrib/interactiveSession/common/interactiveSessionViewModel'; import { getNWords } from 'vs/workbench/contrib/interactiveSession/common/interactiveSessionWordCounter'; const $ = dom.$; export type InteractiveTreeItem = IInteractiveRequestViewModel | IInteractiveResponseViewModel | IInteractiveWelcomeMessageViewModel; interface IInteractiveListItemTemplate { rowContainer: HTMLElement; titleToolbar: MenuWorkbenchToolBar; avatar: HTMLElement; username: HTMLElement; value: HTMLElement; contextKeyService: IContextKeyService; templateDisposables: IDisposable; elementDisposables: DisposableStore; } interface IItemHeightChangeParams { element: InteractiveTreeItem; height: number; } const forceVerboseLayoutTracing = false; export interface IInteractiveSessionRendererDelegate { getListLength(): number; getSlashCommands(): IInteractiveSlashCommand[]; } export class InteractiveListItemRenderer extends Disposable implements ITreeRenderer<InteractiveTreeItem, FuzzyScore, IInteractiveListItemTemplate> { static readonly cursorCharacter = '\u258c'; static readonly ID = 'item'; private readonly renderer: MarkdownRenderer; protected readonly _onDidClickFollowup = this._register(new Emitter<IInteractiveSessionReplyFollowup>()); readonly onDidClickFollowup: Event<IInteractiveSessionReplyFollowup> = this._onDidClickFollowup.event; protected readonly _onDidChangeItemHeight = this._register(new Emitter<IItemHeightChangeParams>()); readonly onDidChangeItemHeight: Event<IItemHeightChangeParams> = this._onDidChangeItemHeight.event; private readonly _editorPool: EditorPool; private _currentLayoutWidth: number = 0; constructor( private readonly editorOptions: InteractiveSessionEditorOptions, private readonly delegate: IInteractiveSessionRendererDelegate, @IInstantiationService private readonly instantiationService: IInstantiationService, @IConfigurationService private readonly configService: IConfigurationService, @ILogService private readonly logService: ILogService, @ICommandService private readonly commandService: ICommandService, @IContextKeyService private readonly contextKeyService: IContextKeyService, @IInteractiveSessionService private readonly interactiveSessionService: IInteractiveSessionService, ) { super(); this.renderer = this.instantiationService.createInstance(MarkdownRenderer, {}); this._editorPool = this._register(this.instantiationService.createInstance(EditorPool, this.editorOptions)); } get templateId(): string { return InteractiveListItemRenderer.ID; } private traceLayout(method: string, message: string) { if (forceVerboseLayoutTracing) { this.logService.info(`InteractiveListItemRenderer#${method}: ${message}`); } else { this.logService.trace(`InteractiveListItemRenderer#${method}: ${message}`); } } private shouldRenderProgressively(element: IInteractiveResponseViewModel): boolean { return !this.configService.getValue('interactive.experimental.disableProgressiveRendering') && element.progressiveResponseRenderingEnabled; } private getProgressiveRenderRate(element: IInteractiveResponseViewModel): number { const configuredRate = this.configService.getValue('interactive.experimental.progressiveRenderingRate'); if (typeof configuredRate === 'number') { return configuredRate; } if (element.isComplete) { return 60; } if (element.contentUpdateTimings && element.contentUpdateTimings.impliedWordLoadRate) { // This doesn't account for dead time after the last update. When the previous update is the final one and the model is only waiting for followupQuestions, that's good. // When there was one quick update and then you are waiting longer for the next one, that's not good since the rate should be decreasing. // If it's an issue, we can change this to be based on the total time from now to the beginning. const rateBoost = 1.5; return element.contentUpdateTimings.impliedWordLoadRate * rateBoost; } return 8; } layout(width: number): void { this._currentLayoutWidth = width - 40; // TODO Padding this._editorPool.inUse.forEach(editor => { editor.layout(this._currentLayoutWidth); }); } renderTemplate(container: HTMLElement): IInteractiveListItemTemplate { const templateDisposables = new DisposableStore(); const rowContainer = dom.append(container, $('.interactive-item-container')); const header = dom.append(rowContainer, $('.header')); const user = dom.append(header, $('.user')); const avatar = dom.append(user, $('.avatar')); const username = dom.append(user, $('h3.username')); const value = dom.append(rowContainer, $('.value')); const elementDisposables = new DisposableStore(); const contextKeyService = templateDisposables.add(this.contextKeyService.createScoped(rowContainer)); const scopedInstantiationService = this.instantiationService.createChild(new ServiceCollection([IContextKeyService, contextKeyService])); const titleToolbar = templateDisposables.add(scopedInstantiationService.createInstance(MenuWorkbenchToolBar, header, MenuId.InteractiveSessionTitle, { menuOptions: { shouldForwardArgs: true } })); const template: IInteractiveListItemTemplate = { avatar, username, value, rowContainer, elementDisposables, titleToolbar, templateDisposables, contextKeyService }; return template; } renderElement(node: ITreeNode<InteractiveTreeItem, FuzzyScore>, index: number, templateData: IInteractiveListItemTemplate): void { const { element } = node; const kind = isRequestVM(element) ? 'request' : isResponseVM(element) ? 'response' : 'welcome'; this.traceLayout('renderElement', `${kind}, index=${index}`); CONTEXT_RESPONSE_HAS_PROVIDER_ID.bindTo(templateData.contextKeyService).set(isResponseVM(element) && !!element.providerResponseId && !element.isPlaceholder); if (isResponseVM(element)) { CONTEXT_RESPONSE_VOTE.bindTo(templateData.contextKeyService).set(element.vote === InteractiveSessionVoteDirection.Up ? 'up' : element.vote === InteractiveSessionVoteDirection.Down ? 'down' : ''); } else { CONTEXT_RESPONSE_VOTE.bindTo(templateData.contextKeyService).set(''); } templateData.titleToolbar.context = element; templateData.rowContainer.classList.toggle('interactive-request', isRequestVM(element)); templateData.rowContainer.classList.toggle('interactive-response', isResponseVM(element)); templateData.rowContainer.classList.toggle('interactive-welcome', isWelcomeVM(element)); templateData.username.textContent = element.username; if (element.avatarIconUri) { const avatarIcon = dom.$<HTMLImageElement>('img.icon'); avatarIcon.src = FileAccess.uriToBrowserUri(element.avatarIconUri).toString(true); templateData.avatar.replaceChildren(avatarIcon); } else { const defaultIcon = isRequestVM(element) ? Codicon.account : Codicon.hubot; const avatarIcon = dom.$(ThemeIcon.asCSSSelector(defaultIcon)); templateData.avatar.replaceChildren(avatarIcon); } // Do a progressive render if // - This the last response in the list // - And the response is not complete // - Or, we previously started a progressive rendering of this element (if the element is complete, we will finish progressive rendering with a very fast rate) // - And, the feature is not disabled in configuration if (isResponseVM(element) && index === this.delegate.getListLength() - 1 && (!element.isComplete || element.renderData) && this.shouldRenderProgressively(element)) { this.traceLayout('renderElement', `start progressive render ${kind}, index=${index}`); const progressiveRenderingDisposables = templateData.elementDisposables.add(new DisposableStore()); const timer = templateData.elementDisposables.add(new IntervalTimer()); const runProgressiveRender = (initial?: boolean) => { try { if (this.doNextProgressiveRender(element, index, templateData, !!initial, progressiveRenderingDisposables)) { timer.cancel(); } } catch (err) { // Kill the timer if anything went wrong, avoid getting stuck in a nasty rendering loop. timer.cancel(); throw err; } }; runProgressiveRender(true); timer.cancelAndSet(runProgressiveRender, 50); } else if (isResponseVM(element)) { this.basicRenderElement(element.response.value, element, index, templateData, element.isCanceled); } else if (isRequestVM(element)) { this.basicRenderElement(element.messageText, element, index, templateData); } else { this.renderWelcomeMessage(element, templateData); } } private basicRenderElement(markdownValue: string, element: InteractiveTreeItem, index: number, templateData: IInteractiveListItemTemplate, fillInIncompleteTokens = false) { const result = this.renderMarkdown(new MarkdownString(markdownValue), element, templateData.elementDisposables, templateData, fillInIncompleteTokens); dom.clearNode(templateData.value); templateData.value.appendChild(result.element); templateData.elementDisposables.add(result); if (isResponseVM(element) && element.errorDetails?.message) { const errorDetails = dom.append(templateData.value, $('.interactive-response-error-details', undefined, renderIcon(Codicon.error))); errorDetails.appendChild($('span', undefined, element.errorDetails.message)); } if (isResponseVM(element) && element.commandFollowups?.length) { const followupsContainer = dom.append(templateData.value, $('.interactive-response-followups')); templateData.elementDisposables.add(new InteractiveSessionFollowups( followupsContainer, element.commandFollowups, defaultButtonStyles, followup => { this.interactiveSessionService.notifyUserAction({ providerId: element.providerId, action: { kind: 'command', command: followup } }); return this.commandService.executeCommand(followup.commandId, ...(followup.args ?? [])); })); } } private renderWelcomeMessage(element: IInteractiveWelcomeMessageViewModel, templateData: IInteractiveListItemTemplate) { dom.clearNode(templateData.value); const slashCommands = this.delegate.getSlashCommands(); for (const item of element.content) { if (Array.isArray(item)) { templateData.elementDisposables.add(new InteractiveSessionFollowups( templateData.value, item, undefined, followup => this._onDidClickFollowup.fire(followup))); } else { const result = this.renderMarkdown(item as IMarkdownString, element, templateData.elementDisposables, templateData); for (const codeElement of result.element.querySelectorAll('code')) { if (codeElement.textContent && slashCommands.find(command => codeElement.textContent === `/${command.command}`)) { codeElement.classList.add('interactive-slash-command'); } } templateData.value.appendChild(result.element); templateData.elementDisposables.add(result); } } } private doNextProgressiveRender(element: IInteractiveResponseViewModel, index: number, templateData: IInteractiveListItemTemplate, isInRenderElement: boolean, disposables: DisposableStore): boolean { disposables.clear(); let isFullyRendered = false; if (element.isCanceled) { this.traceLayout('runProgressiveRender', `canceled, index=${index}`); element.renderData = undefined; this.basicRenderElement(element.response.value, element, index, templateData, true); isFullyRendered = true; } else { // TODO- this method has the side effect of updating element.renderData const toRender = this.getProgressiveMarkdownToRender(element); isFullyRendered = !!element.renderData?.isFullyRendered; if (isFullyRendered) { // We've reached the end of the available content, so do a normal render this.traceLayout('runProgressiveRender', `end progressive render, index=${index}`); if (element.isComplete) { this.traceLayout('runProgressiveRender', `and disposing renderData, response is complete, index=${index}`); element.renderData = undefined; } else { this.traceLayout('runProgressiveRender', `Rendered all available words, but model is not complete.`); } disposables.clear(); this.basicRenderElement(element.response.value, element, index, templateData, !element.isComplete); } else if (toRender) { // Doing the progressive render const plusCursor = toRender.match(/```.*$/) ? toRender + `\n${InteractiveListItemRenderer.cursorCharacter}` : toRender + ` ${InteractiveListItemRenderer.cursorCharacter}`; const result = this.renderMarkdown(new MarkdownString(plusCursor), element, disposables, templateData, true); dom.clearNode(templateData.value); templateData.value.appendChild(result.element); disposables.add(result); } else { // Nothing new to render, not done, keep waiting return false; } } // Some render happened - update the height const height = templateData.rowContainer.offsetHeight; element.currentRenderedHeight = height; if (!isInRenderElement) { this._onDidChangeItemHeight.fire({ element, height: templateData.rowContainer.offsetHeight }); } return !!isFullyRendered; } private renderMarkdown(markdown: IMarkdownString, element: InteractiveTreeItem, disposables: DisposableStore, templateData: IInteractiveListItemTemplate, fillInIncompleteTokens = false): IMarkdownRenderResult { const disposablesList: IDisposable[] = []; let codeBlockIndex = 0; // TODO if the slash commands stay completely dynamic, this isn't quite right const slashCommands = this.delegate.getSlashCommands(); const usedSlashCommand = slashCommands.find(s => markdown.value.startsWith(`/${s.command} `)); const toRender = usedSlashCommand ? markdown.value.slice(usedSlashCommand.command.length + 2) : markdown.value; markdown = new MarkdownString(toRender); const result = this.renderer.render(markdown, { fillInIncompleteTokens, codeBlockRendererSync: (languageId, text) => { const ref = this.renderCodeBlock({ languageId, text, codeBlockIndex: codeBlockIndex++, element, parentContextKeyService: templateData.contextKeyService }, disposables); // Attach this after updating text/layout of the editor, so it should only be fired when the size updates later (horizontal scrollbar, wrapping) // not during a renderElement OR a progressive render (when we will be firing this event anyway at the end of the render) disposables.add(ref.object.onDidChangeContentHeight(() => { ref.object.layout(this._currentLayoutWidth); this._onDidChangeItemHeight.fire({ element, height: templateData.rowContainer.offsetHeight }); })); disposablesList.push(ref); return ref.object.element; } }); if (usedSlashCommand) { const slashCommandElement = $('span.interactive-slash-command', { title: usedSlashCommand.detail }, `/${usedSlashCommand.command} `); if (result.element.firstChild?.nodeName.toLowerCase() === 'p') { result.element.firstChild.insertBefore(slashCommandElement, result.element.firstChild.firstChild); } else { result.element.insertBefore($('p', undefined, slashCommandElement), result.element.firstChild); } } disposablesList.reverse().forEach(d => disposables.add(d)); return result; } private renderCodeBlock(data: IInteractiveResultCodeBlockData, disposables: DisposableStore): IDisposableReference<IInteractiveResultCodeBlockPart> { const ref = this._editorPool.get(); const editorInfo = ref.object; editorInfo.render(data, this._currentLayoutWidth); return ref; } private getProgressiveMarkdownToRender(element: IInteractiveResponseViewModel): string | undefined { const renderData = element.renderData ?? { renderedWordCount: 0, lastRenderTime: 0 }; const rate = this.getProgressiveRenderRate(element); const numWordsToRender = renderData.lastRenderTime === 0 ? 1 : renderData.renderedWordCount + // Additional words to render beyond what's already rendered Math.floor((Date.now() - renderData.lastRenderTime) / 1000 * rate); if (numWordsToRender === renderData.renderedWordCount) { return undefined; } const result = getNWords(element.response.value, numWordsToRender); element.renderData = { renderedWordCount: result.actualWordCount, lastRenderTime: Date.now(), isFullyRendered: result.isFullString }; return result.value; } disposeElement(node: ITreeNode<InteractiveTreeItem, FuzzyScore>, index: number, templateData: IInteractiveListItemTemplate): void { templateData.elementDisposables.clear(); } disposeTemplate(templateData: IInteractiveListItemTemplate): void { templateData.templateDisposables.dispose(); } } export class InteractiveSessionListDelegate implements IListVirtualDelegate<InteractiveTreeItem> { constructor( @ILogService private readonly logService: ILogService ) { } private _traceLayout(method: string, message: string) { if (forceVerboseLayoutTracing) { this.logService.info(`InteractiveSessionListDelegate#${method}: ${message}`); } else { this.logService.trace(`InteractiveSessionListDelegate#${method}: ${message}`); } } getHeight(element: InteractiveTreeItem): number { const kind = isRequestVM(element) ? 'request' : 'response'; const height = ('currentRenderedHeight' in element ? element.currentRenderedHeight : undefined) ?? 200; this._traceLayout('getHeight', `${kind}, height=${height}`); return height; } getTemplateId(element: InteractiveTreeItem): string { return InteractiveListItemRenderer.ID; } hasDynamicHeight(element: InteractiveTreeItem): boolean { return true; } } export class InteractiveSessionAccessibilityProvider implements IListAccessibilityProvider<InteractiveTreeItem> { getWidgetAriaLabel(): string { return localize('interactiveSession', "Interactive Session"); } getAriaLabel(element: InteractiveTreeItem): string { if (isRequestVM(element)) { return localize('interactiveRequest', "Request: {0}", element.messageText); } if (isResponseVM(element)) { return localize('interactiveResponse', "Response: {0}", element.response.value); } return ''; } } interface IInteractiveResultCodeBlockData { text: string; languageId: string; codeBlockIndex: number; element: InteractiveTreeItem; parentContextKeyService: IContextKeyService; } interface IInteractiveResultCodeBlockPart { readonly onDidChangeContentHeight: Event<number>; readonly element: HTMLElement; readonly textModel: ITextModel; layout(width: number): void; render(data: IInteractiveResultCodeBlockData, width: number): void; dispose(): void; } export interface IInteractiveResultCodeBlockInfo { providerId: string; responseId: string; codeBlockIndex: number; } export const codeBlockInfosByModelUri = new ResourceMap<IInteractiveResultCodeBlockInfo>(); class CodeBlockPart extends Disposable implements IInteractiveResultCodeBlockPart { private readonly _onDidChangeContentHeight = this._register(new Emitter<number>()); public readonly onDidChangeContentHeight = this._onDidChangeContentHeight.event; private readonly editor: CodeEditorWidget; private readonly toolbar: MenuWorkbenchToolBar; private readonly contextKeyService: IContextKeyService; public readonly textModel: ITextModel; public readonly element: HTMLElement; constructor( private readonly options: InteractiveSessionEditorOptions, @IInstantiationService instantiationService: IInstantiationService, @IContextKeyService contextKeyService: IContextKeyService, @ILanguageService private readonly languageService: ILanguageService, @IModelService private readonly modelService: IModelService, ) { super(); this.element = $('.interactive-result-editor-wrapper'); this.contextKeyService = this._register(contextKeyService.createScoped(this.element)); const scopedInstantiationService = instantiationService.createChild(new ServiceCollection([IContextKeyService, this.contextKeyService])); this.toolbar = this._register(scopedInstantiationService.createInstance(MenuWorkbenchToolBar, this.element, MenuId.InteractiveSessionCodeBlock, { menuOptions: { shouldForwardArgs: true } })); const editorElement = dom.append(this.element, $('.interactive-result-editor')); this.editor = this._register(scopedInstantiationService.createInstance(CodeEditorWidget, editorElement, { ...getSimpleEditorOptions(), readOnly: true, lineNumbers: 'off', selectOnLineNumbers: true, scrollBeyondLastLine: false, lineDecorationsWidth: 8, dragAndDrop: false, padding: { top: 2, bottom: 2 }, mouseWheelZoom: false, scrollbar: { alwaysConsumeMouseWheel: false }, ...this.getEditorOptionsFromConfig() }, { isSimpleWidget: true, contributions: EditorExtensionsRegistry.getSomeEditorContributions([ MenuPreventer.ID, SelectionClipboardContributionID, ContextMenuController.ID, WordHighlighterContribution.ID, ViewportSemanticTokensContribution.ID, BracketMatchingController.ID, SmartSelectController.ID, ]) })); this._register(this.options.onDidChange(() => { this.editor.updateOptions(this.getEditorOptionsFromConfig()); })); this._register(this.editor.onDidContentSizeChange(e => { if (e.contentHeightChanged) { this._onDidChangeContentHeight.fire(e.contentHeight); } })); this._register(this.editor.onDidBlurEditorWidget(() => { WordHighlighterContribution.get(this.editor)?.stopHighlighting(); })); this._register(this.editor.onDidFocusEditorWidget(() => { WordHighlighterContribution.get(this.editor)?.restoreViewState(true); })); const vscodeLanguageId = this.languageService.getLanguageIdByLanguageName('javascript'); this.textModel = this._register(this.modelService.createModel('', this.languageService.createById(vscodeLanguageId), undefined)); this.editor.setModel(this.textModel); } private getEditorOptionsFromConfig(): IEditorOptions { return { wordWrap: this.options.configuration.resultEditor.wordWrap, bracketPairColorization: this.options.configuration.resultEditor.bracketPairColorization, fontFamily: this.options.configuration.resultEditor.fontFamily === 'default' ? EDITOR_FONT_DEFAULTS.fontFamily : this.options.configuration.resultEditor.fontFamily, fontSize: this.options.configuration.resultEditor.fontSize, fontWeight: this.options.configuration.resultEditor.fontWeight, lineHeight: this.options.configuration.resultEditor.lineHeight, }; } layout(width: number): void { const realContentHeight = this.editor.getContentHeight(); const editorBorder = 2; this.editor.layout({ width: width - editorBorder, height: realContentHeight }); } render(data: IInteractiveResultCodeBlockData, width: number): void { this.contextKeyService.updateParent(data.parentContextKeyService); if (this.options.configuration.resultEditor.wordWrap === 'on') { // Intialize the editor with the new proper width so that getContentHeight // will be computed correctly in the next call to layout() this.layout(width); } this.setText(data.text); this.setLanguage(data.languageId); this.layout(width); if (isResponseVM(data.element) && data.element.providerResponseId) { // For telemetry reporting codeBlockInfosByModelUri.set(this.textModel.uri, { providerId: data.element.providerId, responseId: data.element.providerResponseId, codeBlockIndex: data.codeBlockIndex }); } else { codeBlockInfosByModelUri.delete(this.textModel.uri); } this.toolbar.context = <IInteractiveSessionCodeBlockActionContext>{ code: data.text, codeBlockIndex: data.codeBlockIndex, element: data.element }; } private setText(newText: string): void { let currentText = this.textModel.getLinesContent().join('\n'); if (newText === currentText) { return; } let removedChars = 0; if (currentText.endsWith(` ${InteractiveListItemRenderer.cursorCharacter}`)) { removedChars = 2; } else if (currentText.endsWith(InteractiveListItemRenderer.cursorCharacter)) { removedChars = 1; } if (removedChars > 0) { currentText = currentText.slice(0, currentText.length - removedChars); } if (newText.startsWith(currentText)) { const text = newText.slice(currentText.length); const lastLine = this.textModel.getLineCount(); const lastCol = this.textModel.getLineMaxColumn(lastLine); const insertAtCol = lastCol - removedChars; this.textModel.applyEdits([{ range: new Range(lastLine, insertAtCol, lastLine, lastCol), text }]); } else { // console.log(`Failed to optimize setText`); this.textModel.setValue(newText); } } private setLanguage(languageId: string): void { const vscodeLanguageId = this.languageService.getLanguageIdByLanguageName(languageId); if (vscodeLanguageId) { this.textModel.setLanguage(vscodeLanguageId); } } } interface IDisposableReference<T> extends IDisposable { object: T; } class EditorPool extends Disposable { private _pool: ResourcePool<IInteractiveResultCodeBlockPart>; public get inUse(): ReadonlySet<IInteractiveResultCodeBlockPart> { return this._pool.inUse; } constructor( private readonly options: InteractiveSessionEditorOptions, @IInstantiationService private readonly instantiationService: IInstantiationService, ) { super(); this._pool = this._register(new ResourcePool(() => this.editorFactory())); // TODO listen to changes on options } private editorFactory(): IInteractiveResultCodeBlockPart { return this.instantiationService.createInstance(CodeBlockPart, this.options); } get(): IDisposableReference<IInteractiveResultCodeBlockPart> { const object = this._pool.get(); return { object, dispose: () => this._pool.release(object) }; } } // TODO does something in lifecycle.ts cover this? class ResourcePool<T extends IDisposable> extends Disposable { private readonly pool: T[] = []; private _inUse = new Set<T>; public get inUse(): ReadonlySet<T> { return this._inUse; } constructor( private readonly _itemFactory: () => T, ) { super(); } get(): T { if (this.pool.length > 0) { const item = this.pool.pop()!; this._inUse.add(item); return item; } const item = this._register(this._itemFactory()); this._inUse.add(item); return item; } release(item: T): void { this._inUse.delete(item); this.pool.push(item); } }
src/vs/workbench/contrib/interactiveSession/browser/interactiveSessionListRenderer.ts
1
https://github.com/microsoft/vscode/commit/324d1a25760c6abeb4a0492c0c5a22795b695bf4
[ 0.9983428716659546, 0.05605825036764145, 0.00016166784917004406, 0.00017574758385308087, 0.22659775614738464 ]
{ "id": 4, "code_window": [ "\t\tif (element.isCanceled) {\n", "\t\t\tthis.traceLayout('runProgressiveRender', `canceled, index=${index}`);\n", "\t\t\telement.renderData = undefined;\n", "\t\t\tthis.basicRenderElement(element.response.value, element, index, templateData, true);\n", "\t\t\tisFullyRendered = true;\n", "\t\t} else {\n", "\t\t\t// TODO- this method has the side effect of updating element.renderData\n", "\t\t\tconst toRender = this.getProgressiveMarkdownToRender(element);\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tthis.basicRenderElement(element.response.value, element, index, templateData);\n" ], "file_path": "src/vs/workbench/contrib/interactiveSession/browser/interactiveSessionListRenderer.ts", "type": "replace", "edit_start_line_idx": 301 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import 'vs/css!./media/extension'; import { append, $, addDisposableListener } from 'vs/base/browser/dom'; import { IDisposable, dispose, combinedDisposable } from 'vs/base/common/lifecycle'; import { IAction } 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 { IExtension, ExtensionContainers, ExtensionState, IExtensionsWorkbenchService } from 'vs/workbench/contrib/extensions/common/extensions'; import { ManageExtensionAction, ReloadAction, ExtensionStatusLabelAction, RemoteInstallAction, ExtensionStatusAction, LocalInstallAction, ActionWithDropDownAction, InstallDropdownAction, InstallingLabelAction, ExtensionActionWithDropdownActionViewItem, ExtensionDropDownAction, WebInstallAction, SwitchToPreReleaseVersionAction, SwitchToReleasedVersionAction, MigrateDeprecatedExtensionAction, SetLanguageAction, ClearLanguageAction, UpdateAction, SkipUpdateAction } from 'vs/workbench/contrib/extensions/browser/extensionsActions'; import { areSameExtensions } from 'vs/platform/extensionManagement/common/extensionManagementUtil'; import { RatingsWidget, InstallCountWidget, RecommendationWidget, RemoteBadgeWidget, ExtensionPackCountWidget as ExtensionPackBadgeWidget, SyncIgnoredWidget, ExtensionHoverWidget, ExtensionActivationStatusWidget, PreReleaseBookmarkWidget, extensionVerifiedPublisherIconColor, VerifiedPublisherWidget } from 'vs/workbench/contrib/extensions/browser/extensionsWidgets'; import { IExtensionService, toExtension } 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'; import { registerThemingParticipant, IColorTheme, ICssStyleCollector } from 'vs/platform/theme/common/themeService'; import { ThemeIcon } from 'vs/base/common/themables'; import { WORKBENCH_BACKGROUND } from 'vs/workbench/common/theme'; import { IContextMenuService } from 'vs/platform/contextview/browser/contextView'; import { HoverPosition } from 'vs/base/browser/ui/hover/hoverWidget'; import { verifiedPublisherIcon as verifiedPublisherThemeIcon } from 'vs/workbench/contrib/extensions/browser/extensionsIcons'; const EXTENSION_LIST_ELEMENT_HEIGHT = 72; export interface IExtensionsViewState { onFocus: Event<IExtension>; onBlur: Event<IExtension>; } export interface ITemplateData { root: HTMLElement; element: HTMLElement; icon: HTMLImageElement; name: HTMLElement; publisherDisplayName: HTMLElement; description: HTMLElement; installCount: HTMLElement; ratings: HTMLElement; extension: IExtension | null; disposables: IDisposable[]; extensionDisposables: IDisposable[]; actionbar: ActionBar; } export class Delegate implements IListVirtualDelegate<IExtension> { getHeight() { return EXTENSION_LIST_ELEMENT_HEIGHT; } getTemplateId() { return 'extension'; } } export type ExtensionListRendererOptions = { hoverOptions: { position: () => HoverPosition; }; }; export class Renderer implements IPagedRenderer<IExtension, ITemplateData> { constructor( private extensionViewState: IExtensionsViewState, private readonly options: ExtensionListRendererOptions, @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, @IContextMenuService private readonly contextMenuService: IContextMenuService, ) { } get templateId() { return 'extension'; } renderTemplate(root: HTMLElement): ITemplateData { const recommendationWidget = this.instantiationService.createInstance(RecommendationWidget, append(root, $('.extension-bookmark-container'))); const preReleaseWidget = this.instantiationService.createInstance(PreReleaseBookmarkWidget, append(root, $('.extension-bookmark-container'))); const element = append(root, $('.extension-list-item')); const iconContainer = append(element, $('.icon-container')); const icon = append(iconContainer, $<HTMLImageElement>('img.icon')); const iconRemoteBadgeWidget = this.instantiationService.createInstance(RemoteBadgeWidget, iconContainer, false); const extensionPackBadgeWidget = this.instantiationService.createInstance(ExtensionPackBadgeWidget, iconContainer); const details = append(element, $('.details')); const headerContainer = append(details, $('.header-container')); const header = append(headerContainer, $('.header')); const name = append(header, $('span.name')); const installCount = append(header, $('span.install-count')); const ratings = append(header, $('span.ratings')); const syncIgnore = append(header, $('span.sync-ignored')); const activationStatus = append(header, $('span.activation-status')); const headerRemoteBadgeWidget = this.instantiationService.createInstance(RemoteBadgeWidget, header, false); const description = append(details, $('.description.ellipsis')); const footer = append(details, $('.footer')); const publisher = append(footer, $('.author.ellipsis')); const verifiedPublisherWidget = this.instantiationService.createInstance(VerifiedPublisherWidget, append(publisher, $(`.verified-publisher`)), true); const publisherDisplayName = append(publisher, $('.publisher-name.ellipsis')); const actionbar = new ActionBar(footer, { animated: false, actionViewItemProvider: (action: IAction) => { if (action instanceof ActionWithDropDownAction) { return new ExtensionActionWithDropdownActionViewItem(action, { icon: true, label: true, menuActionsOrProvider: { getActions: () => action.menuActions }, menuActionClassNames: (action.class || '').split(' ') }, this.contextMenuService); } if (action instanceof ExtensionDropDownAction) { return action.createActionViewItem(); } return undefined; }, focusOnlyEnabledItems: true }); actionbar.setFocusable(false); actionbar.onDidRun(({ error }) => error && this.notificationService.error(error)); const extensionStatusIconAction = this.instantiationService.createInstance(ExtensionStatusAction); const actions = [ this.instantiationService.createInstance(ExtensionStatusLabelAction), this.instantiationService.createInstance(MigrateDeprecatedExtensionAction, true), this.instantiationService.createInstance(ReloadAction), this.instantiationService.createInstance(ActionWithDropDownAction, 'extensions.updateActions', '', [[this.instantiationService.createInstance(UpdateAction, false)], [this.instantiationService.createInstance(SkipUpdateAction)]]), this.instantiationService.createInstance(InstallDropdownAction), this.instantiationService.createInstance(InstallingLabelAction), this.instantiationService.createInstance(SetLanguageAction), this.instantiationService.createInstance(ClearLanguageAction), this.instantiationService.createInstance(RemoteInstallAction, false), this.instantiationService.createInstance(LocalInstallAction), this.instantiationService.createInstance(WebInstallAction), extensionStatusIconAction, this.instantiationService.createInstance(SwitchToReleasedVersionAction, true), this.instantiationService.createInstance(SwitchToPreReleaseVersionAction, true), this.instantiationService.createInstance(ManageExtensionAction) ]; const extensionHoverWidget = this.instantiationService.createInstance(ExtensionHoverWidget, { target: root, position: this.options.hoverOptions.position }, extensionStatusIconAction); const widgets = [ recommendationWidget, preReleaseWidget, iconRemoteBadgeWidget, extensionPackBadgeWidget, headerRemoteBadgeWidget, verifiedPublisherWidget, extensionHoverWidget, this.instantiationService.createInstance(SyncIgnoredWidget, syncIgnore), this.instantiationService.createInstance(ExtensionActivationStatusWidget, activationStatus, true), this.instantiationService.createInstance(InstallCountWidget, installCount, true), this.instantiationService.createInstance(RatingsWidget, ratings, true), ]; const extensionContainers: ExtensionContainers = this.instantiationService.createInstance(ExtensionContainers, [...actions, ...widgets]); actionbar.push(actions, { icon: true, label: true }); const disposable = combinedDisposable(...actions, ...widgets, actionbar, extensionContainers); return { root, element, icon, name, installCount, ratings, description, publisherDisplayName, disposables: [disposable], actionbar, extensionDisposables: [], set extension(extension: IExtension) { extensionContainers.extension = extension; } }; } renderPlaceholder(index: number, data: ITemplateData): void { data.element.classList.add('loading'); data.root.removeAttribute('aria-label'); data.root.removeAttribute('data-extension-id'); data.extensionDisposables = dispose(data.extensionDisposables); data.icon.src = ''; data.name.textContent = ''; data.description.textContent = ''; data.publisherDisplayName.textContent = ''; data.installCount.style.display = 'none'; data.ratings.style.display = 'none'; data.extension = null; } renderElement(extension: IExtension, index: number, data: ITemplateData): void { data.element.classList.remove('loading'); data.root.setAttribute('data-extension-id', extension.identifier.id); 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 computeEnablement = async () => { if (extension.state === ExtensionState.Uninstalled) { if (!!extension.deprecationInfo) { return true; } if (this.extensionsWorkbenchService.canSetLanguage(extension)) { return false; } return !(await this.extensionsWorkbenchService.canInstall(extension)); } else if (extension.local && !isLanguagePackExtension(extension.local.manifest)) { const runningExtension = this.extensionService.extensions.filter(e => areSameExtensions({ id: e.identifier.value, uuid: e.uuid }, extension.identifier))[0]; return !(runningExtension && extension.server === this.extensionManagementServerService.getExtensionManagementServer(toExtension(runningExtension))); } return false; }; const updateEnablement = async () => { const disabled = await computeEnablement(); const deprecated = !!extension.deprecationInfo; data.element.classList.toggle('deprecated', deprecated); data.root.classList.toggle('disabled', disabled); }; updateEnablement(); this.extensionService.onDidChangeExtensions(() => updateEnablement(), this, data.extensionDisposables); data.extensionDisposables.push(addDisposableListener(data.icon, 'error', () => data.icon.src = extension.iconUrlFallback, { once: true })); 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.description.textContent = extension.description; const updatePublisher = () => { data.publisherDisplayName.textContent = extension.publisherDisplayName; }; updatePublisher(); Event.filter(this.extensionsWorkbenchService.onChange, e => !!e && areSameExtensions(e.identifier, extension.identifier))(() => updatePublisher(), this, data.extensionDisposables); 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.setFocusable(true); } }, this, data.extensionDisposables); this.extensionViewState.onBlur(e => { if (areSameExtensions(extension.identifier, e.identifier)) { data.actionbar.setFocusable(false); } }, this, data.extensionDisposables); } disposeElement(extension: IExtension, index: number, data: ITemplateData): void { data.extensionDisposables = dispose(data.extensionDisposables); } disposeTemplate(data: ITemplateData): void { data.extensionDisposables = dispose(data.extensionDisposables); data.disposables = dispose(data.disposables); } } registerThemingParticipant((theme: IColorTheme, collector: ICssStyleCollector) => { const verifiedPublisherIconColor = theme.getColor(extensionVerifiedPublisherIconColor); if (verifiedPublisherIconColor) { const disabledVerifiedPublisherIconColor = verifiedPublisherIconColor.transparent(.5).makeOpaque(WORKBENCH_BACKGROUND(theme)); collector.addRule(`.extensions-list .monaco-list .monaco-list-row.disabled .author .verified-publisher ${ThemeIcon.asCSSSelector(verifiedPublisherThemeIcon)} { color: ${disabledVerifiedPublisherIconColor}; }`); } });
src/vs/workbench/contrib/extensions/browser/extensionsList.ts
0
https://github.com/microsoft/vscode/commit/324d1a25760c6abeb4a0492c0c5a22795b695bf4
[ 0.0005184289766475558, 0.00018703647947404534, 0.00016273159417323768, 0.00017386089893989265, 0.00006493317778222263 ]
{ "id": 4, "code_window": [ "\t\tif (element.isCanceled) {\n", "\t\t\tthis.traceLayout('runProgressiveRender', `canceled, index=${index}`);\n", "\t\t\telement.renderData = undefined;\n", "\t\t\tthis.basicRenderElement(element.response.value, element, index, templateData, true);\n", "\t\t\tisFullyRendered = true;\n", "\t\t} else {\n", "\t\t\t// TODO- this method has the side effect of updating element.renderData\n", "\t\t\tconst toRender = this.getProgressiveMarkdownToRender(element);\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tthis.basicRenderElement(element.response.value, element, index, templateData);\n" ], "file_path": "src/vs/workbench/contrib/interactiveSession/browser/interactiveSessionListRenderer.ts", "type": "replace", "edit_start_line_idx": 301 }
/*--------------------------------------------------------------------------------------------- * 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 { URI } from 'vs/base/common/uri'; import { OpenerService } from 'vs/editor/browser/services/openerService'; import { TestCodeEditorService } from 'vs/editor/test/browser/editorTestServices'; import { CommandsRegistry, ICommandService } from 'vs/platform/commands/common/commands'; import { NullCommandService } from 'vs/platform/commands/test/common/nullCommandService'; import { ITextEditorOptions } from 'vs/platform/editor/common/editor'; import { matchesScheme, matchesSomeScheme } from 'vs/platform/opener/common/opener'; import { TestThemeService } from 'vs/platform/theme/test/common/testThemeService'; suite('OpenerService', function () { const themeService = new TestThemeService(); const editorService = new TestCodeEditorService(themeService); let lastCommand: { id: string; args: any[] } | undefined; const commandService = new (class implements ICommandService { declare readonly _serviceBrand: undefined; onWillExecuteCommand = () => Disposable.None; onDidExecuteCommand = () => Disposable.None; executeCommand(id: string, ...args: any[]): Promise<any> { lastCommand = { id, args }; return Promise.resolve(undefined); } })(); setup(function () { lastCommand = undefined; }); test('delegate to editorService, scheme:///fff', async function () { const openerService = new OpenerService(editorService, NullCommandService); await openerService.open(URI.parse('another:///somepath')); assert.strictEqual((editorService.lastInput!.options as ITextEditorOptions)!.selection, undefined); }); test('delegate to editorService, scheme:///fff#L123', async function () { const openerService = new OpenerService(editorService, NullCommandService); await openerService.open(URI.parse('file:///somepath#L23')); assert.strictEqual((editorService.lastInput!.options as ITextEditorOptions)!.selection!.startLineNumber, 23); assert.strictEqual((editorService.lastInput!.options as ITextEditorOptions)!.selection!.startColumn, 1); assert.strictEqual((editorService.lastInput!.options as ITextEditorOptions)!.selection!.endLineNumber, undefined); assert.strictEqual((editorService.lastInput!.options as ITextEditorOptions)!.selection!.endColumn, undefined); assert.strictEqual(editorService.lastInput!.resource.fragment, ''); await openerService.open(URI.parse('another:///somepath#L23')); assert.strictEqual((editorService.lastInput!.options as ITextEditorOptions)!.selection!.startLineNumber, 23); assert.strictEqual((editorService.lastInput!.options as ITextEditorOptions)!.selection!.startColumn, 1); await openerService.open(URI.parse('another:///somepath#L23,45')); assert.strictEqual((editorService.lastInput!.options as ITextEditorOptions)!.selection!.startLineNumber, 23); assert.strictEqual((editorService.lastInput!.options as ITextEditorOptions)!.selection!.startColumn, 45); assert.strictEqual((editorService.lastInput!.options as ITextEditorOptions)!.selection!.endLineNumber, undefined); assert.strictEqual((editorService.lastInput!.options as ITextEditorOptions)!.selection!.endColumn, undefined); assert.strictEqual(editorService.lastInput!.resource.fragment, ''); }); test('delegate to editorService, scheme:///fff#123,123', async function () { const openerService = new OpenerService(editorService, NullCommandService); await openerService.open(URI.parse('file:///somepath#23')); assert.strictEqual((editorService.lastInput!.options as ITextEditorOptions)!.selection!.startLineNumber, 23); assert.strictEqual((editorService.lastInput!.options as ITextEditorOptions)!.selection!.startColumn, 1); assert.strictEqual((editorService.lastInput!.options as ITextEditorOptions)!.selection!.endLineNumber, undefined); assert.strictEqual((editorService.lastInput!.options as ITextEditorOptions)!.selection!.endColumn, undefined); assert.strictEqual(editorService.lastInput!.resource.fragment, ''); await openerService.open(URI.parse('file:///somepath#23,45')); assert.strictEqual((editorService.lastInput!.options as ITextEditorOptions)!.selection!.startLineNumber, 23); assert.strictEqual((editorService.lastInput!.options as ITextEditorOptions)!.selection!.startColumn, 45); assert.strictEqual((editorService.lastInput!.options as ITextEditorOptions)!.selection!.endLineNumber, undefined); assert.strictEqual((editorService.lastInput!.options as ITextEditorOptions)!.selection!.endColumn, undefined); assert.strictEqual(editorService.lastInput!.resource.fragment, ''); }); test('delegate to commandsService, command:someid', async function () { const openerService = new OpenerService(editorService, commandService); const id = `aCommand${Math.random()}`; CommandsRegistry.registerCommand(id, function () { }); assert.strictEqual(lastCommand, undefined); await openerService.open(URI.parse('command:' + id)); assert.strictEqual(lastCommand, undefined); }); test('delegate to commandsService, command:someid', async function () { const openerService = new OpenerService(editorService, commandService); const id = `aCommand${Math.random()}`; CommandsRegistry.registerCommand(id, function () { }); await openerService.open(URI.parse('command:' + id).with({ query: '\"123\"' }), { allowCommands: true }); assert.strictEqual(lastCommand!.id, id); assert.strictEqual(lastCommand!.args.length, 1); assert.strictEqual(lastCommand!.args[0], '123'); await openerService.open(URI.parse('command:' + id), { allowCommands: true }); assert.strictEqual(lastCommand!.id, id); assert.strictEqual(lastCommand!.args.length, 0); await openerService.open(URI.parse('command:' + id).with({ query: '123' }), { allowCommands: true }); assert.strictEqual(lastCommand!.id, id); assert.strictEqual(lastCommand!.args.length, 1); assert.strictEqual(lastCommand!.args[0], 123); await openerService.open(URI.parse('command:' + id).with({ query: JSON.stringify([12, true]) }), { allowCommands: true }); assert.strictEqual(lastCommand!.id, id); assert.strictEqual(lastCommand!.args.length, 2); assert.strictEqual(lastCommand!.args[0], 12); assert.strictEqual(lastCommand!.args[1], true); }); test('links are protected by validators', async function () { const openerService = new OpenerService(editorService, commandService); openerService.registerValidator({ shouldOpen: () => Promise.resolve(false) }); const httpResult = await openerService.open(URI.parse('https://www.microsoft.com')); const httpsResult = await openerService.open(URI.parse('https://www.microsoft.com')); assert.strictEqual(httpResult, false); assert.strictEqual(httpsResult, false); }); test('links validated by validators go to openers', async function () { const openerService = new OpenerService(editorService, commandService); openerService.registerValidator({ shouldOpen: () => Promise.resolve(true) }); let openCount = 0; openerService.registerOpener({ open: (resource: URI) => { openCount++; return Promise.resolve(true); } }); await openerService.open(URI.parse('http://microsoft.com')); assert.strictEqual(openCount, 1); await openerService.open(URI.parse('https://microsoft.com')); assert.strictEqual(openCount, 2); }); test('links aren\'t manipulated before being passed to validator: PR #118226', async function () { const openerService = new OpenerService(editorService, commandService); openerService.registerValidator({ shouldOpen: (resource) => { // We don't want it to convert strings into URIs assert.strictEqual(resource instanceof URI, false); return Promise.resolve(false); } }); await openerService.open('https://wwww.microsoft.com'); await openerService.open('https://www.microsoft.com??params=CountryCode%3DUSA%26Name%3Dvscode"'); }); test('links validated by multiple validators', async function () { const openerService = new OpenerService(editorService, commandService); let v1 = 0; openerService.registerValidator({ shouldOpen: () => { v1++; return Promise.resolve(true); } }); let v2 = 0; openerService.registerValidator({ shouldOpen: () => { v2++; return Promise.resolve(true); } }); let openCount = 0; openerService.registerOpener({ open: (resource: URI) => { openCount++; return Promise.resolve(true); } }); await openerService.open(URI.parse('http://microsoft.com')); assert.strictEqual(openCount, 1); assert.strictEqual(v1, 1); assert.strictEqual(v2, 1); await openerService.open(URI.parse('https://microsoft.com')); assert.strictEqual(openCount, 2); assert.strictEqual(v1, 2); assert.strictEqual(v2, 2); }); test('links invalidated by first validator do not continue validating', async function () { const openerService = new OpenerService(editorService, commandService); let v1 = 0; openerService.registerValidator({ shouldOpen: () => { v1++; return Promise.resolve(false); } }); let v2 = 0; openerService.registerValidator({ shouldOpen: () => { v2++; return Promise.resolve(true); } }); let openCount = 0; openerService.registerOpener({ open: (resource: URI) => { openCount++; return Promise.resolve(true); } }); await openerService.open(URI.parse('http://microsoft.com')); assert.strictEqual(openCount, 0); assert.strictEqual(v1, 1); assert.strictEqual(v2, 0); await openerService.open(URI.parse('https://microsoft.com')); assert.strictEqual(openCount, 0); assert.strictEqual(v1, 2); assert.strictEqual(v2, 0); }); test('matchesScheme', function () { assert.ok(matchesScheme('https://microsoft.com', 'https')); assert.ok(matchesScheme('http://microsoft.com', 'http')); assert.ok(matchesScheme('hTTPs://microsoft.com', 'https')); assert.ok(matchesScheme('httP://microsoft.com', 'http')); assert.ok(matchesScheme(URI.parse('https://microsoft.com'), 'https')); assert.ok(matchesScheme(URI.parse('http://microsoft.com'), 'http')); assert.ok(matchesScheme(URI.parse('hTTPs://microsoft.com'), 'https')); assert.ok(matchesScheme(URI.parse('httP://microsoft.com'), 'http')); assert.ok(!matchesScheme(URI.parse('https://microsoft.com'), 'http')); assert.ok(!matchesScheme(URI.parse('htt://microsoft.com'), 'http')); assert.ok(!matchesScheme(URI.parse('z://microsoft.com'), 'http')); }); test('matchesSomeScheme', function () { assert.ok(matchesSomeScheme('https://microsoft.com', 'http', 'https')); assert.ok(matchesSomeScheme('http://microsoft.com', 'http', 'https')); assert.ok(!matchesSomeScheme('x://microsoft.com', 'http', 'https')); }); test('resolveExternalUri', async function () { const openerService = new OpenerService(editorService, NullCommandService); try { await openerService.resolveExternalUri(URI.parse('file:///Users/user/folder')); assert.fail('Should not reach here'); } catch { // OK } const disposable = openerService.registerExternalUriResolver({ async resolveExternalUri(uri) { return { resolved: uri, dispose() { } }; } }); const result = await openerService.resolveExternalUri(URI.parse('file:///Users/user/folder')); assert.deepStrictEqual(result.resolved.toString(), 'file:///Users/user/folder'); disposable.dispose(); }); test('vscode.open command can\'t open HTTP URL with hash (#) in it [extension development] #140907', async function () { const openerService = new OpenerService(editorService, NullCommandService); const actual: string[] = []; openerService.setDefaultExternalOpener({ async openExternal(href) { actual.push(href); return true; } }); const href = 'https://gitlab.com/viktomas/test-project/merge_requests/new?merge_request%5Bsource_branch%5D=test-%23-hash'; const uri = URI.parse(href); assert.ok(await openerService.open(uri)); assert.ok(await openerService.open(href)); assert.deepStrictEqual(actual, [ encodeURI(uri.toString(true)), // BAD, the encoded # (%23) is double encoded to %2523 (% is double encoded) href // good ]); }); });
src/vs/editor/test/browser/services/openerService.test.ts
0
https://github.com/microsoft/vscode/commit/324d1a25760c6abeb4a0492c0c5a22795b695bf4
[ 0.00017735034634824842, 0.00017398982890881598, 0.0001675467792665586, 0.0001742614695103839, 0.000002385497964496608 ]
{ "id": 4, "code_window": [ "\t\tif (element.isCanceled) {\n", "\t\t\tthis.traceLayout('runProgressiveRender', `canceled, index=${index}`);\n", "\t\t\telement.renderData = undefined;\n", "\t\t\tthis.basicRenderElement(element.response.value, element, index, templateData, true);\n", "\t\t\tisFullyRendered = true;\n", "\t\t} else {\n", "\t\t\t// TODO- this method has the side effect of updating element.renderData\n", "\t\t\tconst toRender = this.getProgressiveMarkdownToRender(element);\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tthis.basicRenderElement(element.response.value, element, index, templateData);\n" ], "file_path": "src/vs/workbench/contrib/interactiveSession/browser/interactiveSessionListRenderer.ts", "type": "replace", "edit_start_line_idx": 301 }
#include <stdlib.h> #include <stdio.h> #include <unistd.h> #include <cuda_runtime.h> #if defined(assert) #undef assert #endif #define assert(c) \ do { \ if(!(c)) { \ fprintf(stderr, "Assertion \"%s\" failed. (%s:%d)\n", \ #c, __FILE__, __LINE__); \ exit(1); \ } \ } while(0) #define assertSucceeded(c) \ do { \ unsigned __tmp = c; \ if(__tmp != cudaSuccess) { \ fprintf(stderr, "Operation \"%s\" failed with error code %x. (%s:%d)\n", \ #c, (__tmp), __FILE__, __LINE__); \ exit(__tmp); \ } \ } while(0) #define ARRAY_LENGTH(x) (sizeof(x) / sizeof(x[0])) constexpr int dataLength = 1 << 24; constexpr int threadsPerBlock = 128; typedef unsigned char byte; struct TestType { union { struct { unsigned lowHalf; unsigned highHalf; } halfAndHalf; unsigned long long whole; } takeYourPick; int arr[5]; struct { char a; char b; } structArr[5]; float theFloats[2]; double theDouble; }; __global__ void cudaComputeHash(TestType* input, unsigned *results) { int idx = blockIdx.x * threadsPerBlock + threadIdx.x; TestType* myInput = input + idx; unsigned myResult = 0; myResult += myInput->takeYourPick.halfAndHalf.lowHalf - idx; myResult += myInput->takeYourPick.halfAndHalf.highHalf - idx; for(size_t i = 0; i < ARRAY_LENGTH(myInput->arr); i++) { myResult += myInput->arr[i] - idx; } for(size_t i = 0; i < sizeof(myInput->structArr); i++) { myResult += reinterpret_cast<byte *>(myInput->structArr)[i] - '0'; } __syncthreads(); results[idx] = myResult; } int main() { int cudaDeviceCount; assertSucceeded(cudaGetDeviceCount(&cudaDeviceCount)); assert(cudaDeviceCount > 0); assertSucceeded(cudaSetDevice(0)); TestType* input; unsigned* results; assertSucceeded(cudaMallocManaged(&input, sizeof(TestType) * dataLength)); assert(!!input); for (size_t i = 0; i < dataLength; i++) { input[i].takeYourPick.halfAndHalf.lowHalf = i + 1; input[i].takeYourPick.halfAndHalf.highHalf = i + 3; for(size_t j = 0; j < ARRAY_LENGTH(input[i].arr); j++) { input[i].arr[j] = i + j + 2; } for(size_t j = 0; j < sizeof(input[i].structArr); j++) { reinterpret_cast<byte *>(input[i].structArr)[j] = '0' + static_cast<char>((i + j) % 10); } input[i].theFloats[0] = i + 1; input[i].theFloats[1] = input[i].theFloats[0] / 2; input[i].theDouble = input[i].theFloats[1] + 1; } assertSucceeded(cudaMallocManaged(reinterpret_cast<void **>(&results), sizeof(unsigned) * dataLength)); assert(!!results); constexpr int blocks = dataLength / threadsPerBlock; cudaComputeHash<<<blocks, threadsPerBlock>>>(input, results); assertSucceeded(cudaDeviceSynchronize()); const unsigned expectedResult = 1 + 3 + ARRAY_LENGTH(input[0].arr) * (ARRAY_LENGTH(input[0].arr) - 1) / 2 + ARRAY_LENGTH(input[0].arr) * 2 + sizeof(input[0].structArr) * (sizeof(input[0].structArr) - 1) / 2; for (unsigned i = 0; i < dataLength; i++) { if (results[i] != expectedResult){ fprintf(stderr, "results[%u] (%u) != %u\n", i, results[i], expectedResult); exit(1); } } assertSucceeded(cudaFree(input)); assertSucceeded(cudaFree(results)); fprintf(stderr, "Success\n"); exit(0); }
extensions/vscode-colorize-tests/test/colorize-fixtures/test.cu
0
https://github.com/microsoft/vscode/commit/324d1a25760c6abeb4a0492c0c5a22795b695bf4
[ 0.0001786187494872138, 0.0001753918477334082, 0.00017226641648449004, 0.00017611663497518748, 0.000001974385213543428 ]
{ "id": 6, "code_window": [ "\t/* Very aggressive list styles try to apply focus colors to every codicon in a list row. */\n", "\tcolor: var(--vscode-foreground) !important;\n", "}\n" ], "labels": [ "keep", "keep", "add" ], "after_edit": [ "\n", ".interactive-session .interactive-item-container.filtered-response .value .rendered-markdown {\n", "\t-webkit-mask-image: linear-gradient(rgba(0, 0, 0, 0.85), rgba(0, 0, 0, 0.05));\n", "\tmask-image: linear-gradient(rgba(0, 0, 0, 0.85), rgba(0, 0, 0, 0.05));\n", "}" ], "file_path": "src/vs/workbench/contrib/interactiveSession/browser/media/interactiveSession.css", "type": "add", "edit_start_line_idx": 327 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as dom from 'vs/base/browser/dom'; import { renderIcon } from 'vs/base/browser/ui/iconLabel/iconLabels'; import { IListVirtualDelegate } from 'vs/base/browser/ui/list/list'; import { IListAccessibilityProvider } from 'vs/base/browser/ui/list/listWidget'; import { ITreeNode, ITreeRenderer } from 'vs/base/browser/ui/tree/tree'; import { IntervalTimer } from 'vs/base/common/async'; import { Codicon } from 'vs/base/common/codicons'; import { Emitter, Event } from 'vs/base/common/event'; import { FuzzyScore } from 'vs/base/common/filters'; import { IMarkdownString, MarkdownString } from 'vs/base/common/htmlContent'; import { Disposable, DisposableStore, IDisposable } from 'vs/base/common/lifecycle'; import { ResourceMap } from 'vs/base/common/map'; import { FileAccess } from 'vs/base/common/network'; import { ThemeIcon } from 'vs/base/common/themables'; import { EditorExtensionsRegistry } from 'vs/editor/browser/editorExtensions'; import { CodeEditorWidget } from 'vs/editor/browser/widget/codeEditorWidget'; import { EDITOR_FONT_DEFAULTS, IEditorOptions } from 'vs/editor/common/config/editorOptions'; import { Range } from 'vs/editor/common/core/range'; import { ILanguageService } from 'vs/editor/common/languages/language'; import { ITextModel } from 'vs/editor/common/model'; import { IModelService } from 'vs/editor/common/services/model'; import { BracketMatchingController } from 'vs/editor/contrib/bracketMatching/browser/bracketMatching'; import { ContextMenuController } from 'vs/editor/contrib/contextmenu/browser/contextmenu'; import { IMarkdownRenderResult, MarkdownRenderer } from 'vs/editor/contrib/markdownRenderer/browser/markdownRenderer'; import { ViewportSemanticTokensContribution } from 'vs/editor/contrib/semanticTokens/browser/viewportSemanticTokens'; import { SmartSelectController } from 'vs/editor/contrib/smartSelect/browser/smartSelect'; import { WordHighlighterContribution } from 'vs/editor/contrib/wordHighlighter/browser/wordHighlighter'; import { localize } from 'vs/nls'; import { MenuWorkbenchToolBar } from 'vs/platform/actions/browser/toolbar'; import { MenuId } from 'vs/platform/actions/common/actions'; import { ICommandService } from 'vs/platform/commands/common/commands'; import { IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { IContextKeyService } from 'vs/platform/contextkey/common/contextkey'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { ServiceCollection } from 'vs/platform/instantiation/common/serviceCollection'; import { ILogService } from 'vs/platform/log/common/log'; import { defaultButtonStyles } from 'vs/platform/theme/browser/defaultStyles'; import { MenuPreventer } from 'vs/workbench/contrib/codeEditor/browser/menuPreventer'; import { SelectionClipboardContributionID } from 'vs/workbench/contrib/codeEditor/browser/selectionClipboard'; import { getSimpleEditorOptions } from 'vs/workbench/contrib/codeEditor/browser/simpleEditorOptions'; import { IInteractiveSessionCodeBlockActionContext } from 'vs/workbench/contrib/interactiveSession/browser/actions/interactiveSessionCodeblockActions'; import { InteractiveSessionFollowups } from 'vs/workbench/contrib/interactiveSession/browser/interactiveSessionFollowups'; import { InteractiveSessionEditorOptions } from 'vs/workbench/contrib/interactiveSession/browser/interactiveSessionOptions'; import { CONTEXT_RESPONSE_HAS_PROVIDER_ID, CONTEXT_RESPONSE_VOTE } from 'vs/workbench/contrib/interactiveSession/common/interactiveSessionContextKeys'; import { IInteractiveSessionReplyFollowup, IInteractiveSessionService, IInteractiveSlashCommand, InteractiveSessionVoteDirection } from 'vs/workbench/contrib/interactiveSession/common/interactiveSessionService'; import { IInteractiveRequestViewModel, IInteractiveResponseViewModel, IInteractiveWelcomeMessageViewModel, isRequestVM, isResponseVM, isWelcomeVM } from 'vs/workbench/contrib/interactiveSession/common/interactiveSessionViewModel'; import { getNWords } from 'vs/workbench/contrib/interactiveSession/common/interactiveSessionWordCounter'; const $ = dom.$; export type InteractiveTreeItem = IInteractiveRequestViewModel | IInteractiveResponseViewModel | IInteractiveWelcomeMessageViewModel; interface IInteractiveListItemTemplate { rowContainer: HTMLElement; titleToolbar: MenuWorkbenchToolBar; avatar: HTMLElement; username: HTMLElement; value: HTMLElement; contextKeyService: IContextKeyService; templateDisposables: IDisposable; elementDisposables: DisposableStore; } interface IItemHeightChangeParams { element: InteractiveTreeItem; height: number; } const forceVerboseLayoutTracing = false; export interface IInteractiveSessionRendererDelegate { getListLength(): number; getSlashCommands(): IInteractiveSlashCommand[]; } export class InteractiveListItemRenderer extends Disposable implements ITreeRenderer<InteractiveTreeItem, FuzzyScore, IInteractiveListItemTemplate> { static readonly cursorCharacter = '\u258c'; static readonly ID = 'item'; private readonly renderer: MarkdownRenderer; protected readonly _onDidClickFollowup = this._register(new Emitter<IInteractiveSessionReplyFollowup>()); readonly onDidClickFollowup: Event<IInteractiveSessionReplyFollowup> = this._onDidClickFollowup.event; protected readonly _onDidChangeItemHeight = this._register(new Emitter<IItemHeightChangeParams>()); readonly onDidChangeItemHeight: Event<IItemHeightChangeParams> = this._onDidChangeItemHeight.event; private readonly _editorPool: EditorPool; private _currentLayoutWidth: number = 0; constructor( private readonly editorOptions: InteractiveSessionEditorOptions, private readonly delegate: IInteractiveSessionRendererDelegate, @IInstantiationService private readonly instantiationService: IInstantiationService, @IConfigurationService private readonly configService: IConfigurationService, @ILogService private readonly logService: ILogService, @ICommandService private readonly commandService: ICommandService, @IContextKeyService private readonly contextKeyService: IContextKeyService, @IInteractiveSessionService private readonly interactiveSessionService: IInteractiveSessionService, ) { super(); this.renderer = this.instantiationService.createInstance(MarkdownRenderer, {}); this._editorPool = this._register(this.instantiationService.createInstance(EditorPool, this.editorOptions)); } get templateId(): string { return InteractiveListItemRenderer.ID; } private traceLayout(method: string, message: string) { if (forceVerboseLayoutTracing) { this.logService.info(`InteractiveListItemRenderer#${method}: ${message}`); } else { this.logService.trace(`InteractiveListItemRenderer#${method}: ${message}`); } } private shouldRenderProgressively(element: IInteractiveResponseViewModel): boolean { return !this.configService.getValue('interactive.experimental.disableProgressiveRendering') && element.progressiveResponseRenderingEnabled; } private getProgressiveRenderRate(element: IInteractiveResponseViewModel): number { const configuredRate = this.configService.getValue('interactive.experimental.progressiveRenderingRate'); if (typeof configuredRate === 'number') { return configuredRate; } if (element.isComplete) { return 60; } if (element.contentUpdateTimings && element.contentUpdateTimings.impliedWordLoadRate) { // This doesn't account for dead time after the last update. When the previous update is the final one and the model is only waiting for followupQuestions, that's good. // When there was one quick update and then you are waiting longer for the next one, that's not good since the rate should be decreasing. // If it's an issue, we can change this to be based on the total time from now to the beginning. const rateBoost = 1.5; return element.contentUpdateTimings.impliedWordLoadRate * rateBoost; } return 8; } layout(width: number): void { this._currentLayoutWidth = width - 40; // TODO Padding this._editorPool.inUse.forEach(editor => { editor.layout(this._currentLayoutWidth); }); } renderTemplate(container: HTMLElement): IInteractiveListItemTemplate { const templateDisposables = new DisposableStore(); const rowContainer = dom.append(container, $('.interactive-item-container')); const header = dom.append(rowContainer, $('.header')); const user = dom.append(header, $('.user')); const avatar = dom.append(user, $('.avatar')); const username = dom.append(user, $('h3.username')); const value = dom.append(rowContainer, $('.value')); const elementDisposables = new DisposableStore(); const contextKeyService = templateDisposables.add(this.contextKeyService.createScoped(rowContainer)); const scopedInstantiationService = this.instantiationService.createChild(new ServiceCollection([IContextKeyService, contextKeyService])); const titleToolbar = templateDisposables.add(scopedInstantiationService.createInstance(MenuWorkbenchToolBar, header, MenuId.InteractiveSessionTitle, { menuOptions: { shouldForwardArgs: true } })); const template: IInteractiveListItemTemplate = { avatar, username, value, rowContainer, elementDisposables, titleToolbar, templateDisposables, contextKeyService }; return template; } renderElement(node: ITreeNode<InteractiveTreeItem, FuzzyScore>, index: number, templateData: IInteractiveListItemTemplate): void { const { element } = node; const kind = isRequestVM(element) ? 'request' : isResponseVM(element) ? 'response' : 'welcome'; this.traceLayout('renderElement', `${kind}, index=${index}`); CONTEXT_RESPONSE_HAS_PROVIDER_ID.bindTo(templateData.contextKeyService).set(isResponseVM(element) && !!element.providerResponseId && !element.isPlaceholder); if (isResponseVM(element)) { CONTEXT_RESPONSE_VOTE.bindTo(templateData.contextKeyService).set(element.vote === InteractiveSessionVoteDirection.Up ? 'up' : element.vote === InteractiveSessionVoteDirection.Down ? 'down' : ''); } else { CONTEXT_RESPONSE_VOTE.bindTo(templateData.contextKeyService).set(''); } templateData.titleToolbar.context = element; templateData.rowContainer.classList.toggle('interactive-request', isRequestVM(element)); templateData.rowContainer.classList.toggle('interactive-response', isResponseVM(element)); templateData.rowContainer.classList.toggle('interactive-welcome', isWelcomeVM(element)); templateData.username.textContent = element.username; if (element.avatarIconUri) { const avatarIcon = dom.$<HTMLImageElement>('img.icon'); avatarIcon.src = FileAccess.uriToBrowserUri(element.avatarIconUri).toString(true); templateData.avatar.replaceChildren(avatarIcon); } else { const defaultIcon = isRequestVM(element) ? Codicon.account : Codicon.hubot; const avatarIcon = dom.$(ThemeIcon.asCSSSelector(defaultIcon)); templateData.avatar.replaceChildren(avatarIcon); } // Do a progressive render if // - This the last response in the list // - And the response is not complete // - Or, we previously started a progressive rendering of this element (if the element is complete, we will finish progressive rendering with a very fast rate) // - And, the feature is not disabled in configuration if (isResponseVM(element) && index === this.delegate.getListLength() - 1 && (!element.isComplete || element.renderData) && this.shouldRenderProgressively(element)) { this.traceLayout('renderElement', `start progressive render ${kind}, index=${index}`); const progressiveRenderingDisposables = templateData.elementDisposables.add(new DisposableStore()); const timer = templateData.elementDisposables.add(new IntervalTimer()); const runProgressiveRender = (initial?: boolean) => { try { if (this.doNextProgressiveRender(element, index, templateData, !!initial, progressiveRenderingDisposables)) { timer.cancel(); } } catch (err) { // Kill the timer if anything went wrong, avoid getting stuck in a nasty rendering loop. timer.cancel(); throw err; } }; runProgressiveRender(true); timer.cancelAndSet(runProgressiveRender, 50); } else if (isResponseVM(element)) { this.basicRenderElement(element.response.value, element, index, templateData, element.isCanceled); } else if (isRequestVM(element)) { this.basicRenderElement(element.messageText, element, index, templateData); } else { this.renderWelcomeMessage(element, templateData); } } private basicRenderElement(markdownValue: string, element: InteractiveTreeItem, index: number, templateData: IInteractiveListItemTemplate, fillInIncompleteTokens = false) { const result = this.renderMarkdown(new MarkdownString(markdownValue), element, templateData.elementDisposables, templateData, fillInIncompleteTokens); dom.clearNode(templateData.value); templateData.value.appendChild(result.element); templateData.elementDisposables.add(result); if (isResponseVM(element) && element.errorDetails?.message) { const errorDetails = dom.append(templateData.value, $('.interactive-response-error-details', undefined, renderIcon(Codicon.error))); errorDetails.appendChild($('span', undefined, element.errorDetails.message)); } if (isResponseVM(element) && element.commandFollowups?.length) { const followupsContainer = dom.append(templateData.value, $('.interactive-response-followups')); templateData.elementDisposables.add(new InteractiveSessionFollowups( followupsContainer, element.commandFollowups, defaultButtonStyles, followup => { this.interactiveSessionService.notifyUserAction({ providerId: element.providerId, action: { kind: 'command', command: followup } }); return this.commandService.executeCommand(followup.commandId, ...(followup.args ?? [])); })); } } private renderWelcomeMessage(element: IInteractiveWelcomeMessageViewModel, templateData: IInteractiveListItemTemplate) { dom.clearNode(templateData.value); const slashCommands = this.delegate.getSlashCommands(); for (const item of element.content) { if (Array.isArray(item)) { templateData.elementDisposables.add(new InteractiveSessionFollowups( templateData.value, item, undefined, followup => this._onDidClickFollowup.fire(followup))); } else { const result = this.renderMarkdown(item as IMarkdownString, element, templateData.elementDisposables, templateData); for (const codeElement of result.element.querySelectorAll('code')) { if (codeElement.textContent && slashCommands.find(command => codeElement.textContent === `/${command.command}`)) { codeElement.classList.add('interactive-slash-command'); } } templateData.value.appendChild(result.element); templateData.elementDisposables.add(result); } } } private doNextProgressiveRender(element: IInteractiveResponseViewModel, index: number, templateData: IInteractiveListItemTemplate, isInRenderElement: boolean, disposables: DisposableStore): boolean { disposables.clear(); let isFullyRendered = false; if (element.isCanceled) { this.traceLayout('runProgressiveRender', `canceled, index=${index}`); element.renderData = undefined; this.basicRenderElement(element.response.value, element, index, templateData, true); isFullyRendered = true; } else { // TODO- this method has the side effect of updating element.renderData const toRender = this.getProgressiveMarkdownToRender(element); isFullyRendered = !!element.renderData?.isFullyRendered; if (isFullyRendered) { // We've reached the end of the available content, so do a normal render this.traceLayout('runProgressiveRender', `end progressive render, index=${index}`); if (element.isComplete) { this.traceLayout('runProgressiveRender', `and disposing renderData, response is complete, index=${index}`); element.renderData = undefined; } else { this.traceLayout('runProgressiveRender', `Rendered all available words, but model is not complete.`); } disposables.clear(); this.basicRenderElement(element.response.value, element, index, templateData, !element.isComplete); } else if (toRender) { // Doing the progressive render const plusCursor = toRender.match(/```.*$/) ? toRender + `\n${InteractiveListItemRenderer.cursorCharacter}` : toRender + ` ${InteractiveListItemRenderer.cursorCharacter}`; const result = this.renderMarkdown(new MarkdownString(plusCursor), element, disposables, templateData, true); dom.clearNode(templateData.value); templateData.value.appendChild(result.element); disposables.add(result); } else { // Nothing new to render, not done, keep waiting return false; } } // Some render happened - update the height const height = templateData.rowContainer.offsetHeight; element.currentRenderedHeight = height; if (!isInRenderElement) { this._onDidChangeItemHeight.fire({ element, height: templateData.rowContainer.offsetHeight }); } return !!isFullyRendered; } private renderMarkdown(markdown: IMarkdownString, element: InteractiveTreeItem, disposables: DisposableStore, templateData: IInteractiveListItemTemplate, fillInIncompleteTokens = false): IMarkdownRenderResult { const disposablesList: IDisposable[] = []; let codeBlockIndex = 0; // TODO if the slash commands stay completely dynamic, this isn't quite right const slashCommands = this.delegate.getSlashCommands(); const usedSlashCommand = slashCommands.find(s => markdown.value.startsWith(`/${s.command} `)); const toRender = usedSlashCommand ? markdown.value.slice(usedSlashCommand.command.length + 2) : markdown.value; markdown = new MarkdownString(toRender); const result = this.renderer.render(markdown, { fillInIncompleteTokens, codeBlockRendererSync: (languageId, text) => { const ref = this.renderCodeBlock({ languageId, text, codeBlockIndex: codeBlockIndex++, element, parentContextKeyService: templateData.contextKeyService }, disposables); // Attach this after updating text/layout of the editor, so it should only be fired when the size updates later (horizontal scrollbar, wrapping) // not during a renderElement OR a progressive render (when we will be firing this event anyway at the end of the render) disposables.add(ref.object.onDidChangeContentHeight(() => { ref.object.layout(this._currentLayoutWidth); this._onDidChangeItemHeight.fire({ element, height: templateData.rowContainer.offsetHeight }); })); disposablesList.push(ref); return ref.object.element; } }); if (usedSlashCommand) { const slashCommandElement = $('span.interactive-slash-command', { title: usedSlashCommand.detail }, `/${usedSlashCommand.command} `); if (result.element.firstChild?.nodeName.toLowerCase() === 'p') { result.element.firstChild.insertBefore(slashCommandElement, result.element.firstChild.firstChild); } else { result.element.insertBefore($('p', undefined, slashCommandElement), result.element.firstChild); } } disposablesList.reverse().forEach(d => disposables.add(d)); return result; } private renderCodeBlock(data: IInteractiveResultCodeBlockData, disposables: DisposableStore): IDisposableReference<IInteractiveResultCodeBlockPart> { const ref = this._editorPool.get(); const editorInfo = ref.object; editorInfo.render(data, this._currentLayoutWidth); return ref; } private getProgressiveMarkdownToRender(element: IInteractiveResponseViewModel): string | undefined { const renderData = element.renderData ?? { renderedWordCount: 0, lastRenderTime: 0 }; const rate = this.getProgressiveRenderRate(element); const numWordsToRender = renderData.lastRenderTime === 0 ? 1 : renderData.renderedWordCount + // Additional words to render beyond what's already rendered Math.floor((Date.now() - renderData.lastRenderTime) / 1000 * rate); if (numWordsToRender === renderData.renderedWordCount) { return undefined; } const result = getNWords(element.response.value, numWordsToRender); element.renderData = { renderedWordCount: result.actualWordCount, lastRenderTime: Date.now(), isFullyRendered: result.isFullString }; return result.value; } disposeElement(node: ITreeNode<InteractiveTreeItem, FuzzyScore>, index: number, templateData: IInteractiveListItemTemplate): void { templateData.elementDisposables.clear(); } disposeTemplate(templateData: IInteractiveListItemTemplate): void { templateData.templateDisposables.dispose(); } } export class InteractiveSessionListDelegate implements IListVirtualDelegate<InteractiveTreeItem> { constructor( @ILogService private readonly logService: ILogService ) { } private _traceLayout(method: string, message: string) { if (forceVerboseLayoutTracing) { this.logService.info(`InteractiveSessionListDelegate#${method}: ${message}`); } else { this.logService.trace(`InteractiveSessionListDelegate#${method}: ${message}`); } } getHeight(element: InteractiveTreeItem): number { const kind = isRequestVM(element) ? 'request' : 'response'; const height = ('currentRenderedHeight' in element ? element.currentRenderedHeight : undefined) ?? 200; this._traceLayout('getHeight', `${kind}, height=${height}`); return height; } getTemplateId(element: InteractiveTreeItem): string { return InteractiveListItemRenderer.ID; } hasDynamicHeight(element: InteractiveTreeItem): boolean { return true; } } export class InteractiveSessionAccessibilityProvider implements IListAccessibilityProvider<InteractiveTreeItem> { getWidgetAriaLabel(): string { return localize('interactiveSession', "Interactive Session"); } getAriaLabel(element: InteractiveTreeItem): string { if (isRequestVM(element)) { return localize('interactiveRequest', "Request: {0}", element.messageText); } if (isResponseVM(element)) { return localize('interactiveResponse', "Response: {0}", element.response.value); } return ''; } } interface IInteractiveResultCodeBlockData { text: string; languageId: string; codeBlockIndex: number; element: InteractiveTreeItem; parentContextKeyService: IContextKeyService; } interface IInteractiveResultCodeBlockPart { readonly onDidChangeContentHeight: Event<number>; readonly element: HTMLElement; readonly textModel: ITextModel; layout(width: number): void; render(data: IInteractiveResultCodeBlockData, width: number): void; dispose(): void; } export interface IInteractiveResultCodeBlockInfo { providerId: string; responseId: string; codeBlockIndex: number; } export const codeBlockInfosByModelUri = new ResourceMap<IInteractiveResultCodeBlockInfo>(); class CodeBlockPart extends Disposable implements IInteractiveResultCodeBlockPart { private readonly _onDidChangeContentHeight = this._register(new Emitter<number>()); public readonly onDidChangeContentHeight = this._onDidChangeContentHeight.event; private readonly editor: CodeEditorWidget; private readonly toolbar: MenuWorkbenchToolBar; private readonly contextKeyService: IContextKeyService; public readonly textModel: ITextModel; public readonly element: HTMLElement; constructor( private readonly options: InteractiveSessionEditorOptions, @IInstantiationService instantiationService: IInstantiationService, @IContextKeyService contextKeyService: IContextKeyService, @ILanguageService private readonly languageService: ILanguageService, @IModelService private readonly modelService: IModelService, ) { super(); this.element = $('.interactive-result-editor-wrapper'); this.contextKeyService = this._register(contextKeyService.createScoped(this.element)); const scopedInstantiationService = instantiationService.createChild(new ServiceCollection([IContextKeyService, this.contextKeyService])); this.toolbar = this._register(scopedInstantiationService.createInstance(MenuWorkbenchToolBar, this.element, MenuId.InteractiveSessionCodeBlock, { menuOptions: { shouldForwardArgs: true } })); const editorElement = dom.append(this.element, $('.interactive-result-editor')); this.editor = this._register(scopedInstantiationService.createInstance(CodeEditorWidget, editorElement, { ...getSimpleEditorOptions(), readOnly: true, lineNumbers: 'off', selectOnLineNumbers: true, scrollBeyondLastLine: false, lineDecorationsWidth: 8, dragAndDrop: false, padding: { top: 2, bottom: 2 }, mouseWheelZoom: false, scrollbar: { alwaysConsumeMouseWheel: false }, ...this.getEditorOptionsFromConfig() }, { isSimpleWidget: true, contributions: EditorExtensionsRegistry.getSomeEditorContributions([ MenuPreventer.ID, SelectionClipboardContributionID, ContextMenuController.ID, WordHighlighterContribution.ID, ViewportSemanticTokensContribution.ID, BracketMatchingController.ID, SmartSelectController.ID, ]) })); this._register(this.options.onDidChange(() => { this.editor.updateOptions(this.getEditorOptionsFromConfig()); })); this._register(this.editor.onDidContentSizeChange(e => { if (e.contentHeightChanged) { this._onDidChangeContentHeight.fire(e.contentHeight); } })); this._register(this.editor.onDidBlurEditorWidget(() => { WordHighlighterContribution.get(this.editor)?.stopHighlighting(); })); this._register(this.editor.onDidFocusEditorWidget(() => { WordHighlighterContribution.get(this.editor)?.restoreViewState(true); })); const vscodeLanguageId = this.languageService.getLanguageIdByLanguageName('javascript'); this.textModel = this._register(this.modelService.createModel('', this.languageService.createById(vscodeLanguageId), undefined)); this.editor.setModel(this.textModel); } private getEditorOptionsFromConfig(): IEditorOptions { return { wordWrap: this.options.configuration.resultEditor.wordWrap, bracketPairColorization: this.options.configuration.resultEditor.bracketPairColorization, fontFamily: this.options.configuration.resultEditor.fontFamily === 'default' ? EDITOR_FONT_DEFAULTS.fontFamily : this.options.configuration.resultEditor.fontFamily, fontSize: this.options.configuration.resultEditor.fontSize, fontWeight: this.options.configuration.resultEditor.fontWeight, lineHeight: this.options.configuration.resultEditor.lineHeight, }; } layout(width: number): void { const realContentHeight = this.editor.getContentHeight(); const editorBorder = 2; this.editor.layout({ width: width - editorBorder, height: realContentHeight }); } render(data: IInteractiveResultCodeBlockData, width: number): void { this.contextKeyService.updateParent(data.parentContextKeyService); if (this.options.configuration.resultEditor.wordWrap === 'on') { // Intialize the editor with the new proper width so that getContentHeight // will be computed correctly in the next call to layout() this.layout(width); } this.setText(data.text); this.setLanguage(data.languageId); this.layout(width); if (isResponseVM(data.element) && data.element.providerResponseId) { // For telemetry reporting codeBlockInfosByModelUri.set(this.textModel.uri, { providerId: data.element.providerId, responseId: data.element.providerResponseId, codeBlockIndex: data.codeBlockIndex }); } else { codeBlockInfosByModelUri.delete(this.textModel.uri); } this.toolbar.context = <IInteractiveSessionCodeBlockActionContext>{ code: data.text, codeBlockIndex: data.codeBlockIndex, element: data.element }; } private setText(newText: string): void { let currentText = this.textModel.getLinesContent().join('\n'); if (newText === currentText) { return; } let removedChars = 0; if (currentText.endsWith(` ${InteractiveListItemRenderer.cursorCharacter}`)) { removedChars = 2; } else if (currentText.endsWith(InteractiveListItemRenderer.cursorCharacter)) { removedChars = 1; } if (removedChars > 0) { currentText = currentText.slice(0, currentText.length - removedChars); } if (newText.startsWith(currentText)) { const text = newText.slice(currentText.length); const lastLine = this.textModel.getLineCount(); const lastCol = this.textModel.getLineMaxColumn(lastLine); const insertAtCol = lastCol - removedChars; this.textModel.applyEdits([{ range: new Range(lastLine, insertAtCol, lastLine, lastCol), text }]); } else { // console.log(`Failed to optimize setText`); this.textModel.setValue(newText); } } private setLanguage(languageId: string): void { const vscodeLanguageId = this.languageService.getLanguageIdByLanguageName(languageId); if (vscodeLanguageId) { this.textModel.setLanguage(vscodeLanguageId); } } } interface IDisposableReference<T> extends IDisposable { object: T; } class EditorPool extends Disposable { private _pool: ResourcePool<IInteractiveResultCodeBlockPart>; public get inUse(): ReadonlySet<IInteractiveResultCodeBlockPart> { return this._pool.inUse; } constructor( private readonly options: InteractiveSessionEditorOptions, @IInstantiationService private readonly instantiationService: IInstantiationService, ) { super(); this._pool = this._register(new ResourcePool(() => this.editorFactory())); // TODO listen to changes on options } private editorFactory(): IInteractiveResultCodeBlockPart { return this.instantiationService.createInstance(CodeBlockPart, this.options); } get(): IDisposableReference<IInteractiveResultCodeBlockPart> { const object = this._pool.get(); return { object, dispose: () => this._pool.release(object) }; } } // TODO does something in lifecycle.ts cover this? class ResourcePool<T extends IDisposable> extends Disposable { private readonly pool: T[] = []; private _inUse = new Set<T>; public get inUse(): ReadonlySet<T> { return this._inUse; } constructor( private readonly _itemFactory: () => T, ) { super(); } get(): T { if (this.pool.length > 0) { const item = this.pool.pop()!; this._inUse.add(item); return item; } const item = this._register(this._itemFactory()); this._inUse.add(item); return item; } release(item: T): void { this._inUse.delete(item); this.pool.push(item); } }
src/vs/workbench/contrib/interactiveSession/browser/interactiveSessionListRenderer.ts
1
https://github.com/microsoft/vscode/commit/324d1a25760c6abeb4a0492c0c5a22795b695bf4
[ 0.0003065872297156602, 0.0001747286441968754, 0.0001646683522267267, 0.00016929689445532858, 0.00002159612085961271 ]
{ "id": 6, "code_window": [ "\t/* Very aggressive list styles try to apply focus colors to every codicon in a list row. */\n", "\tcolor: var(--vscode-foreground) !important;\n", "}\n" ], "labels": [ "keep", "keep", "add" ], "after_edit": [ "\n", ".interactive-session .interactive-item-container.filtered-response .value .rendered-markdown {\n", "\t-webkit-mask-image: linear-gradient(rgba(0, 0, 0, 0.85), rgba(0, 0, 0, 0.05));\n", "\tmask-image: linear-gradient(rgba(0, 0, 0, 0.85), rgba(0, 0, 0, 0.05));\n", "}" ], "file_path": "src/vs/workbench/contrib/interactiveSession/browser/media/interactiveSession.css", "type": "add", "edit_start_line_idx": 327 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { readUInt32BE, writeUInt32BE } from 'vs/base/common/buffer'; import { ContiguousMultilineTokens } from 'vs/editor/common/tokens/contiguousMultilineTokens'; export class ContiguousMultilineTokensBuilder { public static deserialize(buff: Uint8Array): ContiguousMultilineTokens[] { let offset = 0; const count = readUInt32BE(buff, offset); offset += 4; const result: ContiguousMultilineTokens[] = []; for (let i = 0; i < count; i++) { offset = ContiguousMultilineTokens.deserialize(buff, offset, result); } return result; } private readonly _tokens: ContiguousMultilineTokens[]; constructor() { this._tokens = []; } public add(lineNumber: number, lineTokens: Uint32Array): void { if (this._tokens.length > 0) { const last = this._tokens[this._tokens.length - 1]; if (last.endLineNumber + 1 === lineNumber) { // append last.appendLineTokens(lineTokens); return; } } this._tokens.push(new ContiguousMultilineTokens(lineNumber, [lineTokens])); } public finalize(): ContiguousMultilineTokens[] { return this._tokens; } public serialize(): Uint8Array { const size = this._serializeSize(); const result = new Uint8Array(size); this._serialize(result); return result; } private _serializeSize(): number { let result = 0; result += 4; // 4 bytes for the count for (let i = 0; i < this._tokens.length; i++) { result += this._tokens[i].serializeSize(); } return result; } private _serialize(destination: Uint8Array): void { let offset = 0; writeUInt32BE(destination, this._tokens.length, offset); offset += 4; for (let i = 0; i < this._tokens.length; i++) { offset = this._tokens[i].serialize(destination, offset); } } }
src/vs/editor/common/tokens/contiguousMultilineTokensBuilder.ts
0
https://github.com/microsoft/vscode/commit/324d1a25760c6abeb4a0492c0c5a22795b695bf4
[ 0.0001738084392854944, 0.00017088720051106066, 0.00016804806364234537, 0.00017051877512130886, 0.000001953456603587256 ]