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": 6,
"code_window": [
"\n",
"\tprivate onDidUpdateConfiguration(e: IConfigurationServiceEvent) {\n",
"\t\tthis.configure(e.config);\n",
"\t}\n",
"\n",
"\tprotected configure(config: IHTTPConfiguration) {\n",
"\t\tthis.proxyUrl = config.http && config.http.proxy;\n",
"\t\tthis.strictSSL = config.http && config.http.proxyStrictSSL;\n",
"\t\tthis.authorization = config.http && config.http.proxyAuthorization;\n",
"\t}\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tprivate configure(config: IHTTPConfiguration) {\n"
],
"file_path": "src/vs/platform/request/node/requestService.ts",
"type": "replace",
"edit_start_line_idx": 38
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
// Do not edit this file. It is machine generated.
{
"araLabelEditorActions": "편집기 작업",
"close": "닫기",
"inputDecoration": "{0} {1}",
"loadingLabel": "로드 중...",
"splitEditor": "편집기 분할"
} | i18n/kor/src/vs/workbench/browser/parts/editor/sideBySideEditorControl.i18n.json | 0 | https://github.com/microsoft/vscode/commit/10ae5b4b913b6b86351c43ebbd544a982643c5ac | [
0.0001751993113430217,
0.00017414003377780318,
0.0001730807707644999,
0.00017414003377780318,
0.000001059270289260894
] |
{
"id": 6,
"code_window": [
"\n",
"\tprivate onDidUpdateConfiguration(e: IConfigurationServiceEvent) {\n",
"\t\tthis.configure(e.config);\n",
"\t}\n",
"\n",
"\tprotected configure(config: IHTTPConfiguration) {\n",
"\t\tthis.proxyUrl = config.http && config.http.proxy;\n",
"\t\tthis.strictSSL = config.http && config.http.proxyStrictSSL;\n",
"\t\tthis.authorization = config.http && config.http.proxyAuthorization;\n",
"\t}\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tprivate configure(config: IHTTPConfiguration) {\n"
],
"file_path": "src/vs/platform/request/node/requestService.ts",
"type": "replace",
"edit_start_line_idx": 38
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
import * as assert from 'assert';
import { KeyCode as StandaloneKeyCode, Severity as StandaloneSeverity } from 'vs/editor/common/standalone/standaloneBase';
import { KeyCode as RuntimeKeyCode } from 'vs/base/common/keyCodes';
import { Keybinding } from 'vs/base/common/keybinding';
import RuntimeSeverity from 'vs/base/common/severity';
suite('StandaloneBase', () => {
test('exports enums correctly', () => {
assert.equal(StandaloneSeverity.Ignore, RuntimeSeverity.Ignore);
assert.equal(StandaloneSeverity.Info, RuntimeSeverity.Info);
assert.equal(StandaloneSeverity.Warning, RuntimeSeverity.Warning);
assert.equal(StandaloneSeverity.Error, RuntimeSeverity.Error);
});
});
suite('KeyCode', () => {
test('is exported correctly in standalone editor', () => {
function assertKeyCode(standalone: StandaloneKeyCode, runtime: RuntimeKeyCode): void {
assert.equal(standalone, runtime);
}
assertKeyCode(StandaloneKeyCode.Unknown, RuntimeKeyCode.Unknown);
assertKeyCode(StandaloneKeyCode.Backspace, RuntimeKeyCode.Backspace);
assertKeyCode(StandaloneKeyCode.Tab, RuntimeKeyCode.Tab);
assertKeyCode(StandaloneKeyCode.Enter, RuntimeKeyCode.Enter);
assertKeyCode(StandaloneKeyCode.Shift, RuntimeKeyCode.Shift);
assertKeyCode(StandaloneKeyCode.Ctrl, RuntimeKeyCode.Ctrl);
assertKeyCode(StandaloneKeyCode.Alt, RuntimeKeyCode.Alt);
assertKeyCode(StandaloneKeyCode.PauseBreak, RuntimeKeyCode.PauseBreak);
assertKeyCode(StandaloneKeyCode.CapsLock, RuntimeKeyCode.CapsLock);
assertKeyCode(StandaloneKeyCode.Escape, RuntimeKeyCode.Escape);
assertKeyCode(StandaloneKeyCode.Space, RuntimeKeyCode.Space);
assertKeyCode(StandaloneKeyCode.PageUp, RuntimeKeyCode.PageUp);
assertKeyCode(StandaloneKeyCode.PageDown, RuntimeKeyCode.PageDown);
assertKeyCode(StandaloneKeyCode.End, RuntimeKeyCode.End);
assertKeyCode(StandaloneKeyCode.Home, RuntimeKeyCode.Home);
assertKeyCode(StandaloneKeyCode.LeftArrow, RuntimeKeyCode.LeftArrow);
assertKeyCode(StandaloneKeyCode.UpArrow, RuntimeKeyCode.UpArrow);
assertKeyCode(StandaloneKeyCode.RightArrow, RuntimeKeyCode.RightArrow);
assertKeyCode(StandaloneKeyCode.DownArrow, RuntimeKeyCode.DownArrow);
assertKeyCode(StandaloneKeyCode.Insert, RuntimeKeyCode.Insert);
assertKeyCode(StandaloneKeyCode.Delete, RuntimeKeyCode.Delete);
assertKeyCode(StandaloneKeyCode.KEY_0, RuntimeKeyCode.KEY_0);
assertKeyCode(StandaloneKeyCode.KEY_1, RuntimeKeyCode.KEY_1);
assertKeyCode(StandaloneKeyCode.KEY_2, RuntimeKeyCode.KEY_2);
assertKeyCode(StandaloneKeyCode.KEY_3, RuntimeKeyCode.KEY_3);
assertKeyCode(StandaloneKeyCode.KEY_4, RuntimeKeyCode.KEY_4);
assertKeyCode(StandaloneKeyCode.KEY_5, RuntimeKeyCode.KEY_5);
assertKeyCode(StandaloneKeyCode.KEY_6, RuntimeKeyCode.KEY_6);
assertKeyCode(StandaloneKeyCode.KEY_7, RuntimeKeyCode.KEY_7);
assertKeyCode(StandaloneKeyCode.KEY_8, RuntimeKeyCode.KEY_8);
assertKeyCode(StandaloneKeyCode.KEY_9, RuntimeKeyCode.KEY_9);
assertKeyCode(StandaloneKeyCode.KEY_A, RuntimeKeyCode.KEY_A);
assertKeyCode(StandaloneKeyCode.KEY_B, RuntimeKeyCode.KEY_B);
assertKeyCode(StandaloneKeyCode.KEY_C, RuntimeKeyCode.KEY_C);
assertKeyCode(StandaloneKeyCode.KEY_D, RuntimeKeyCode.KEY_D);
assertKeyCode(StandaloneKeyCode.KEY_E, RuntimeKeyCode.KEY_E);
assertKeyCode(StandaloneKeyCode.KEY_F, RuntimeKeyCode.KEY_F);
assertKeyCode(StandaloneKeyCode.KEY_G, RuntimeKeyCode.KEY_G);
assertKeyCode(StandaloneKeyCode.KEY_H, RuntimeKeyCode.KEY_H);
assertKeyCode(StandaloneKeyCode.KEY_I, RuntimeKeyCode.KEY_I);
assertKeyCode(StandaloneKeyCode.KEY_J, RuntimeKeyCode.KEY_J);
assertKeyCode(StandaloneKeyCode.KEY_K, RuntimeKeyCode.KEY_K);
assertKeyCode(StandaloneKeyCode.KEY_L, RuntimeKeyCode.KEY_L);
assertKeyCode(StandaloneKeyCode.KEY_M, RuntimeKeyCode.KEY_M);
assertKeyCode(StandaloneKeyCode.KEY_N, RuntimeKeyCode.KEY_N);
assertKeyCode(StandaloneKeyCode.KEY_O, RuntimeKeyCode.KEY_O);
assertKeyCode(StandaloneKeyCode.KEY_P, RuntimeKeyCode.KEY_P);
assertKeyCode(StandaloneKeyCode.KEY_Q, RuntimeKeyCode.KEY_Q);
assertKeyCode(StandaloneKeyCode.KEY_R, RuntimeKeyCode.KEY_R);
assertKeyCode(StandaloneKeyCode.KEY_S, RuntimeKeyCode.KEY_S);
assertKeyCode(StandaloneKeyCode.KEY_T, RuntimeKeyCode.KEY_T);
assertKeyCode(StandaloneKeyCode.KEY_U, RuntimeKeyCode.KEY_U);
assertKeyCode(StandaloneKeyCode.KEY_V, RuntimeKeyCode.KEY_V);
assertKeyCode(StandaloneKeyCode.KEY_W, RuntimeKeyCode.KEY_W);
assertKeyCode(StandaloneKeyCode.KEY_X, RuntimeKeyCode.KEY_X);
assertKeyCode(StandaloneKeyCode.KEY_Y, RuntimeKeyCode.KEY_Y);
assertKeyCode(StandaloneKeyCode.KEY_Z, RuntimeKeyCode.KEY_Z);
assertKeyCode(StandaloneKeyCode.Meta, RuntimeKeyCode.Meta);
assertKeyCode(StandaloneKeyCode.ContextMenu, RuntimeKeyCode.ContextMenu);
assertKeyCode(StandaloneKeyCode.F1, RuntimeKeyCode.F1);
assertKeyCode(StandaloneKeyCode.F2, RuntimeKeyCode.F2);
assertKeyCode(StandaloneKeyCode.F3, RuntimeKeyCode.F3);
assertKeyCode(StandaloneKeyCode.F4, RuntimeKeyCode.F4);
assertKeyCode(StandaloneKeyCode.F5, RuntimeKeyCode.F5);
assertKeyCode(StandaloneKeyCode.F6, RuntimeKeyCode.F6);
assertKeyCode(StandaloneKeyCode.F7, RuntimeKeyCode.F7);
assertKeyCode(StandaloneKeyCode.F8, RuntimeKeyCode.F8);
assertKeyCode(StandaloneKeyCode.F9, RuntimeKeyCode.F9);
assertKeyCode(StandaloneKeyCode.F10, RuntimeKeyCode.F10);
assertKeyCode(StandaloneKeyCode.F11, RuntimeKeyCode.F11);
assertKeyCode(StandaloneKeyCode.F12, RuntimeKeyCode.F12);
assertKeyCode(StandaloneKeyCode.F13, RuntimeKeyCode.F13);
assertKeyCode(StandaloneKeyCode.F14, RuntimeKeyCode.F14);
assertKeyCode(StandaloneKeyCode.F15, RuntimeKeyCode.F15);
assertKeyCode(StandaloneKeyCode.F16, RuntimeKeyCode.F16);
assertKeyCode(StandaloneKeyCode.F17, RuntimeKeyCode.F17);
assertKeyCode(StandaloneKeyCode.F18, RuntimeKeyCode.F18);
assertKeyCode(StandaloneKeyCode.F19, RuntimeKeyCode.F19);
assertKeyCode(StandaloneKeyCode.NumLock, RuntimeKeyCode.NumLock);
assertKeyCode(StandaloneKeyCode.ScrollLock, RuntimeKeyCode.ScrollLock);
assertKeyCode(StandaloneKeyCode.US_SEMICOLON, RuntimeKeyCode.US_SEMICOLON);
assertKeyCode(StandaloneKeyCode.US_EQUAL, RuntimeKeyCode.US_EQUAL);
assertKeyCode(StandaloneKeyCode.US_COMMA, RuntimeKeyCode.US_COMMA);
assertKeyCode(StandaloneKeyCode.US_MINUS, RuntimeKeyCode.US_MINUS);
assertKeyCode(StandaloneKeyCode.US_DOT, RuntimeKeyCode.US_DOT);
assertKeyCode(StandaloneKeyCode.US_SLASH, RuntimeKeyCode.US_SLASH);
assertKeyCode(StandaloneKeyCode.US_BACKTICK, RuntimeKeyCode.US_BACKTICK);
assertKeyCode(StandaloneKeyCode.US_OPEN_SQUARE_BRACKET, RuntimeKeyCode.US_OPEN_SQUARE_BRACKET);
assertKeyCode(StandaloneKeyCode.US_BACKSLASH, RuntimeKeyCode.US_BACKSLASH);
assertKeyCode(StandaloneKeyCode.US_CLOSE_SQUARE_BRACKET, RuntimeKeyCode.US_CLOSE_SQUARE_BRACKET);
assertKeyCode(StandaloneKeyCode.US_QUOTE, RuntimeKeyCode.US_QUOTE);
assertKeyCode(StandaloneKeyCode.OEM_8, RuntimeKeyCode.OEM_8);
assertKeyCode(StandaloneKeyCode.OEM_102, RuntimeKeyCode.OEM_102);
assertKeyCode(StandaloneKeyCode.NUMPAD_0, RuntimeKeyCode.NUMPAD_0);
assertKeyCode(StandaloneKeyCode.NUMPAD_1, RuntimeKeyCode.NUMPAD_1);
assertKeyCode(StandaloneKeyCode.NUMPAD_2, RuntimeKeyCode.NUMPAD_2);
assertKeyCode(StandaloneKeyCode.NUMPAD_3, RuntimeKeyCode.NUMPAD_3);
assertKeyCode(StandaloneKeyCode.NUMPAD_4, RuntimeKeyCode.NUMPAD_4);
assertKeyCode(StandaloneKeyCode.NUMPAD_5, RuntimeKeyCode.NUMPAD_5);
assertKeyCode(StandaloneKeyCode.NUMPAD_6, RuntimeKeyCode.NUMPAD_6);
assertKeyCode(StandaloneKeyCode.NUMPAD_7, RuntimeKeyCode.NUMPAD_7);
assertKeyCode(StandaloneKeyCode.NUMPAD_8, RuntimeKeyCode.NUMPAD_8);
assertKeyCode(StandaloneKeyCode.NUMPAD_9, RuntimeKeyCode.NUMPAD_9);
assertKeyCode(StandaloneKeyCode.NUMPAD_MULTIPLY, RuntimeKeyCode.NUMPAD_MULTIPLY);
assertKeyCode(StandaloneKeyCode.NUMPAD_ADD, RuntimeKeyCode.NUMPAD_ADD);
assertKeyCode(StandaloneKeyCode.NUMPAD_SEPARATOR, RuntimeKeyCode.NUMPAD_SEPARATOR);
assertKeyCode(StandaloneKeyCode.NUMPAD_SUBTRACT, RuntimeKeyCode.NUMPAD_SUBTRACT);
assertKeyCode(StandaloneKeyCode.NUMPAD_DECIMAL, RuntimeKeyCode.NUMPAD_DECIMAL);
assertKeyCode(StandaloneKeyCode.NUMPAD_DIVIDE, RuntimeKeyCode.NUMPAD_DIVIDE);
assertKeyCode(StandaloneKeyCode.MAX_VALUE, RuntimeKeyCode.MAX_VALUE);
});
test('getUserSettingsKeybindingRegex', () => {
let regex = new RegExp(Keybinding.getUserSettingsKeybindingRegex());
function testIsGood(userSettingsLabel: string, message: string = userSettingsLabel): void {
let userSettings = '"' + userSettingsLabel.replace(/\\/g, '\\\\') + '"';
let isGood = regex.test(userSettings);
assert.ok(isGood, message);
}
// check that all key codes are covered by the regex
let ignore: boolean[] = [];
ignore[RuntimeKeyCode.Shift] = true;
ignore[RuntimeKeyCode.Ctrl] = true;
ignore[RuntimeKeyCode.Alt] = true;
ignore[RuntimeKeyCode.Meta] = true;
for (let keyCode = RuntimeKeyCode.Unknown + 1; keyCode < RuntimeKeyCode.MAX_VALUE; keyCode++) {
if (ignore[keyCode]) {
continue;
}
let userSettings = Keybinding.toUserSettingsLabel(keyCode);
testIsGood(userSettings, keyCode + ' - ' + StandaloneKeyCode[keyCode] + ' - ' + userSettings);
}
// one modifier
testIsGood('ctrl+a');
testIsGood('shift+a');
testIsGood('alt+a');
testIsGood('cmd+a');
testIsGood('meta+a');
testIsGood('win+a');
// more modifiers
testIsGood('ctrl+shift+a');
testIsGood('shift+alt+a');
testIsGood('ctrl+shift+alt+a');
// chords
testIsGood('ctrl+a ctrl+a');
});
}); | src/vs/editor/test/common/standalone/standaloneBase.test.ts | 0 | https://github.com/microsoft/vscode/commit/10ae5b4b913b6b86351c43ebbd544a982643c5ac | [
0.00017853429017122835,
0.000175578985363245,
0.00017214869149029255,
0.00017557089449837804,
0.0000016482255205119145
] |
{
"id": 0,
"code_window": [
" context2.close()\n",
" ]);\n",
" expect(browser.browserContexts().length).toBe(1);\n",
" });\n",
" it('should set the default viewport', async({ newPage }) => {\n",
" const page = await newPage({ viewport: { width: 456, height: 789 } });\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
" it('should propagate default viewport to the page', async({ newPage }) => {\n"
],
"file_path": "test/browsercontext.spec.js",
"type": "replace",
"edit_start_line_idx": 95
} | /**
* Copyright 2018 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.
*/
module.exports.describe = function({testRunner, expect, product, FFOX, CHROME, WEBKIT}) {
const {describe, xdescribe, fdescribe} = testRunner;
const {it, fit, xit, dit} = testRunner;
const {beforeAll, beforeEach, afterAll, afterEach} = testRunner;
describe('Page.screenshot', function() {
it('should work', async({page, server}) => {
await page.setViewport({width: 500, height: 500});
await page.goto(server.PREFIX + '/grid.html');
const screenshot = await page.screenshot();
expect(screenshot).toBeGolden('screenshot-sanity.png');
});
it('should clip rect', async({page, server}) => {
await page.setViewport({width: 500, height: 500});
await page.goto(server.PREFIX + '/grid.html');
const screenshot = await page.screenshot({
clip: {
x: 50,
y: 100,
width: 150,
height: 100
}
});
expect(screenshot).toBeGolden('screenshot-clip-rect.png');
});
it('should clip elements to the viewport', async({page, server}) => {
await page.setViewport({width: 500, height: 500});
await page.goto(server.PREFIX + '/grid.html');
const screenshot = await page.screenshot({
clip: {
x: 50,
y: 450,
width: 1000,
height: 100
}
});
expect(screenshot).toBeGolden('screenshot-offscreen-clip.png');
});
it('should throw on clip outside the viewport', async({page, server}) => {
await page.setViewport({width: 500, height: 500});
await page.goto(server.PREFIX + '/grid.html');
const screenshotError = await page.screenshot({
clip: {
x: 50,
y: 650,
width: 100,
height: 100
}
}).catch(error => error);
expect(screenshotError.message).toBe('Clipped area is either empty or outside the viewport');
});
it('should run in parallel', async({page, server}) => {
await page.setViewport({width: 500, height: 500});
await page.goto(server.PREFIX + '/grid.html');
const promises = [];
for (let i = 0; i < 3; ++i) {
promises.push(page.screenshot({
clip: {
x: 50 * i,
y: 0,
width: 50,
height: 50
}
}));
}
const screenshots = await Promise.all(promises);
expect(screenshots[1]).toBeGolden('grid-cell-1.png');
});
it('should take fullPage screenshots', async({page, server}) => {
await page.setViewport({width: 500, height: 500});
await page.goto(server.PREFIX + '/grid.html');
const screenshot = await page.screenshot({
fullPage: true
});
expect(screenshot).toBeGolden('screenshot-grid-fullpage.png');
});
it('should run in parallel in multiple pages', async({page, server, context}) => {
const N = 2;
const pages = await Promise.all(Array(N).fill(0).map(async() => {
const page = await context.newPage();
await page.goto(server.PREFIX + '/grid.html');
return page;
}));
const promises = [];
for (let i = 0; i < N; ++i)
promises.push(pages[i].screenshot({ clip: { x: 50 * i, y: 0, width: 50, height: 50 } }));
const screenshots = await Promise.all(promises);
for (let i = 0; i < N; ++i)
expect(screenshots[i]).toBeGolden(`grid-cell-${i}.png`);
await Promise.all(pages.map(page => page.close()));
});
it.skip(FFOX)('should allow transparency', async({page, server}) => {
await page.setViewport({ width: 50, height: 150 });
await page.setContent(`
<style>
body { margin: 0 }
div { width: 50px; height: 50px; }
</style>
<div style="background:black"></div>
<div style="background:white"></div>
<div style="background:transparent"></div>
`);
const screenshot = await page.screenshot({omitBackground: true});
expect(screenshot).toBeGolden('transparent.png');
});
it('should render white background on jpeg file', async({page, server}) => {
await page.setViewport({ width: 100, height: 100 });
await page.goto(server.EMPTY_PAGE);
const screenshot = await page.screenshot({omitBackground: true, type: 'jpeg'});
expect(screenshot).toBeGolden('white.jpg');
});
it('should work with odd clip size on Retina displays', async({page, server}) => {
const screenshot = await page.screenshot({
clip: {
x: 0,
y: 0,
width: 11,
height: 11,
}
});
expect(screenshot).toBeGolden('screenshot-clip-odd-size.png');
});
it('should return base64', async({page, server}) => {
await page.setViewport({width: 500, height: 500});
await page.goto(server.PREFIX + '/grid.html');
const screenshot = await page.screenshot({
encoding: 'base64'
});
expect(Buffer.from(screenshot, 'base64')).toBeGolden('screenshot-sanity.png');
});
it.skip(WEBKIT || FFOX)('should work with a mobile viewport', async({page, server}) => {
await page.setViewport({
width: 320,
height: 480,
isMobile: true
});
await page.goto(server.PREFIX + '/grid.html');
const screenshot = await page.screenshot();
expect(screenshot).toBeGolden('screenshot-mobile.png');
});
});
describe('ElementHandle.screenshot', function() {
it('should work', async({page, server}) => {
await page.setViewport({width: 500, height: 500});
await page.goto(server.PREFIX + '/grid.html');
await page.evaluate(() => window.scrollBy(50, 100));
const elementHandle = await page.$('.box:nth-of-type(3)');
const screenshot = await elementHandle.screenshot();
expect(screenshot).toBeGolden('screenshot-element-bounding-box.png');
});
it('should take into account padding and border', async({page, server}) => {
await page.setViewport({width: 500, height: 500});
await page.setContent(`
<div style="height: 14px">oooo</div>
<style>div {
border: 2px solid blue;
background: green;
width: 50px;
height: 50px;
}
</style>
<div id="d"></div>
`);
const elementHandle = await page.$('div#d');
const screenshot = await elementHandle.screenshot();
expect(screenshot).toBeGolden('screenshot-element-padding-border.png');
});
it('should capture full element when larger than viewport in parallel', async({page, server}) => {
await page.setViewport({width: 500, height: 500});
await page.setContent(`
<div style="height: 14px">oooo</div>
<style>
div.to-screenshot {
border: 1px solid blue;
width: 600px;
height: 600px;
margin-left: 50px;
}
::-webkit-scrollbar{
display: none;
}
</style>
<div class="to-screenshot"></div>
<div class="to-screenshot"></div>
<div class="to-screenshot"></div>
`);
const elementHandles = await page.$$('div.to-screenshot');
const promises = elementHandles.map(handle => handle.screenshot());
const screenshots = await Promise.all(promises);
expect(screenshots[2]).toBeGolden('screenshot-element-larger-than-viewport.png');
expect(await page.evaluate(() => ({ w: window.innerWidth, h: window.innerHeight }))).toEqual({ w: 500, h: 500 });
});
// Fails on GTK due to async setViewport.
it('should capture full element when larger than viewport', async({page, server}) => {
await page.setViewport({width: 500, height: 500});
await page.setContent(`
<div style="height: 14px">oooo</div>
<style>
div.to-screenshot {
border: 1px solid blue;
width: 600px;
height: 600px;
margin-left: 50px;
}
::-webkit-scrollbar{
display: none;
}
</style>
<div class="to-screenshot"></div>
<div class="to-screenshot"></div>
<div class="to-screenshot"></div>
`);
const elementHandle = await page.$('div.to-screenshot');
const screenshot = await elementHandle.screenshot();
expect(screenshot).toBeGolden('screenshot-element-larger-than-viewport.png');
expect(await page.evaluate(() => ({ w: window.innerWidth, h: window.innerHeight }))).toEqual({ w: 500, h: 500 });
});
it('should scroll element into view', async({page, server}) => {
await page.setViewport({width: 500, height: 500});
await page.setContent(`
<div style="height: 14px">oooo</div>
<style>div.above {
border: 2px solid blue;
background: red;
height: 1500px;
}
div.to-screenshot {
border: 2px solid blue;
background: green;
width: 50px;
height: 50px;
}
</style>
<div class="above"></div>
<div class="to-screenshot"></div>
`);
const elementHandle = await page.$('div.to-screenshot');
const screenshot = await elementHandle.screenshot();
expect(screenshot).toBeGolden('screenshot-element-scrolled-into-view.png');
});
it('should work with a rotated element', async({page, server}) => {
await page.setViewport({width: 500, height: 500});
await page.setContent(`<div style="position:absolute;
top: 100px;
left: 100px;
width: 100px;
height: 100px;
background: green;
transform: rotateZ(200deg);"> </div>`);
const elementHandle = await page.$('div');
const screenshot = await elementHandle.screenshot();
expect(screenshot).toBeGolden('screenshot-element-rotate.png');
});
it('should fail to screenshot a detached element', async({page, server}) => {
await page.setContent('<h1>remove this</h1>');
const elementHandle = await page.$('h1');
await page.evaluate(element => element.remove(), elementHandle);
const screenshotError = await elementHandle.screenshot().catch(error => error);
expect(screenshotError.message).toBe('Node is either not visible or not an HTMLElement');
});
it('should not hang with zero width/height element', async({page, server}) => {
await page.setContent('<div style="width: 50px; height: 0"></div>');
const div = await page.$('div');
const error = await div.screenshot().catch(e => e);
expect(error.message).toBe('Node has 0 height.');
});
it('should work for an element with fractional dimensions', async({page}) => {
await page.setContent('<div style="width:48.51px;height:19.8px;border:1px solid black;"></div>');
const elementHandle = await page.$('div');
const screenshot = await elementHandle.screenshot();
expect(screenshot).toBeGolden('screenshot-element-fractional.png');
});
it('should work for an element with an offset', async({page}) => {
await page.setContent('<div style="position:absolute; top: 10.3px; left: 20.4px;width:50.3px;height:20.2px;border:1px solid black;"></div>');
const elementHandle = await page.$('div');
const screenshot = await elementHandle.screenshot();
expect(screenshot).toBeGolden('screenshot-element-fractional-offset.png');
});
});
};
| test/screenshot.spec.js | 1 | https://github.com/microsoft/playwright/commit/310d4b193b4a7d3944af95424e44e4293392db24 | [
0.9912471175193787,
0.6088947653770447,
0.00015935815463308245,
0.9133160710334778,
0.4354906976222992
] |
{
"id": 0,
"code_window": [
" context2.close()\n",
" ]);\n",
" expect(browser.browserContexts().length).toBe(1);\n",
" });\n",
" it('should set the default viewport', async({ newPage }) => {\n",
" const page = await newPage({ viewport: { width: 456, height: 789 } });\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
" it('should propagate default viewport to the page', async({ newPage }) => {\n"
],
"file_path": "test/browsercontext.spec.js",
"type": "replace",
"edit_start_line_idx": 95
} | console.log('Cheers!');
| test/assets/frames/script.js | 0 | https://github.com/microsoft/playwright/commit/310d4b193b4a7d3944af95424e44e4293392db24 | [
0.00017408642452210188,
0.00017408642452210188,
0.00017408642452210188,
0.00017408642452210188,
0
] |
{
"id": 0,
"code_window": [
" context2.close()\n",
" ]);\n",
" expect(browser.browserContexts().length).toBe(1);\n",
" });\n",
" it('should set the default viewport', async({ newPage }) => {\n",
" const page = await newPage({ viewport: { width: 456, height: 789 } });\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
" it('should propagate default viewport to the page', async({ newPage }) => {\n"
],
"file_path": "test/browsercontext.spec.js",
"type": "replace",
"edit_start_line_idx": 95
} | import num from './es6/es6module.js';
window.__es6injected = num; | test/assets/es6/es6pathimport.js | 0 | https://github.com/microsoft/playwright/commit/310d4b193b4a7d3944af95424e44e4293392db24 | [
0.00017478283552918583,
0.00017478283552918583,
0.00017478283552918583,
0.00017478283552918583,
0
] |
{
"id": 0,
"code_window": [
" context2.close()\n",
" ]);\n",
" expect(browser.browserContexts().length).toBe(1);\n",
" });\n",
" it('should set the default viewport', async({ newPage }) => {\n",
" const page = await newPage({ viewport: { width: 456, height: 789 } });\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
" it('should propagate default viewport to the page', async({ newPage }) => {\n"
],
"file_path": "test/browsercontext.spec.js",
"type": "replace",
"edit_start_line_idx": 95
} | {"foo": "bar"}
| test/assets/simple.json | 0 | https://github.com/microsoft/playwright/commit/310d4b193b4a7d3944af95424e44e4293392db24 | [
0.00017174275126308203,
0.00017174275126308203,
0.00017174275126308203,
0.00017174275126308203,
0
] |
{
"id": 1,
"code_window": [
" const page = await newPage({ viewport: { width: 456, height: 789 } });\n",
" expect(await page.evaluate('window.innerWidth')).toBe(456);\n",
" expect(await page.evaluate('window.innerHeight')).toBe(789);\n",
" });\n"
],
"labels": [
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" expect(page.viewport().width).toBe(456);\n",
" expect(page.viewport().height).toBe(789);\n"
],
"file_path": "test/browsercontext.spec.js",
"type": "add",
"edit_start_line_idx": 97
} | /**
* Copyright 2018 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.
*/
const utils = require('./utils');
module.exports.describe = function({testRunner, expect, playwright, CHROME, WEBKIT}) {
const {describe, xdescribe, fdescribe} = testRunner;
const {it, fit, xit, dit} = testRunner;
const {beforeAll, beforeEach, afterAll, afterEach} = testRunner;
describe('BrowserContext', function() {
it('should have default context', async function({browser, server}) {
expect(browser.browserContexts().length).toBe(1);
const defaultContext = browser.browserContexts()[0];
let error = null;
await defaultContext.close().catch(e => error = e);
expect(browser.defaultContext()).toBe(defaultContext);
expect(error.message).toContain('cannot be closed');
});
it('should create new incognito context', async function({browser, newContext}) {
expect(browser.browserContexts().length).toBe(1);
const context = await newContext();
expect(browser.browserContexts().length).toBe(2);
expect(browser.browserContexts().indexOf(context) !== -1).toBe(true);
await context.close();
expect(browser.browserContexts().length).toBe(1);
});
it('window.open should use parent tab context', async function({newContext, server}) {
const context = await newContext();
const page = await context.newPage();
await page.goto(server.EMPTY_PAGE);
const [popupTarget] = await Promise.all([
utils.waitEvent(page, 'popup'),
page.evaluate(url => window.open(url), server.EMPTY_PAGE)
]);
expect(popupTarget.browserContext()).toBe(context);
});
it('should isolate localStorage and cookies', async function({browser, newContext, server}) {
// Create two incognito contexts.
const context1 = await newContext();
const context2 = await newContext();
expect((await context1.pages()).length).toBe(0);
expect((await context2.pages()).length).toBe(0);
// Create a page in first incognito context.
const page1 = await context1.newPage();
await page1.goto(server.EMPTY_PAGE);
await page1.evaluate(() => {
localStorage.setItem('name', 'page1');
document.cookie = 'name=page1';
});
expect((await context1.pages()).length).toBe(1);
expect((await context2.pages()).length).toBe(0);
// Create a page in second incognito context.
const page2 = await context2.newPage();
await page2.goto(server.EMPTY_PAGE);
await page2.evaluate(() => {
localStorage.setItem('name', 'page2');
document.cookie = 'name=page2';
});
expect((await context1.pages()).length).toBe(1);
expect((await context2.pages()).length).toBe(1);
expect((await context1.pages())[0]).toBe(page1);
expect((await context2.pages())[0]).toBe(page2);
// Make sure pages don't share localstorage or cookies.
expect(await page1.evaluate(() => localStorage.getItem('name'))).toBe('page1');
expect(await page1.evaluate(() => document.cookie)).toBe('name=page1');
expect(await page2.evaluate(() => localStorage.getItem('name'))).toBe('page2');
expect(await page2.evaluate(() => document.cookie)).toBe('name=page2');
// Cleanup contexts.
await Promise.all([
context1.close(),
context2.close()
]);
expect(browser.browserContexts().length).toBe(1);
});
it('should set the default viewport', async({ newPage }) => {
const page = await newPage({ viewport: { width: 456, height: 789 } });
expect(await page.evaluate('window.innerWidth')).toBe(456);
expect(await page.evaluate('window.innerHeight')).toBe(789);
});
it('should take fullPage screenshots when default viewport is null', async({server, newPage}) => {
const page = await newPage({ viewport: null });
await page.goto(server.PREFIX + '/grid.html');
const sizeBefore = await page.evaluate(() => ({ width: document.body.offsetWidth, height: document.body.offsetHeight }));
const screenshot = await page.screenshot({
fullPage: true
});
expect(screenshot).toBeInstanceOf(Buffer);
const sizeAfter = await page.evaluate(() => ({ width: document.body.offsetWidth, height: document.body.offsetHeight }));
expect(sizeBefore.width).toBe(sizeAfter.width);
expect(sizeBefore.height).toBe(sizeAfter.height);
});
});
describe('BrowserContext({setUserAgent})', function() {
it('should work', async({newPage, server}) => {
{
const page = await newPage();
expect(await page.evaluate(() => navigator.userAgent)).toContain('Mozilla');
}
{
const page = await newPage({ userAgent: 'foobar' });
const [request] = await Promise.all([
server.waitForRequest('/empty.html'),
page.goto(server.EMPTY_PAGE),
]);
expect(request.headers['user-agent']).toBe('foobar');
}
});
it('should work for subframes', async({newPage, server}) => {
{
const page = await newPage();
expect(await page.evaluate(() => navigator.userAgent)).toContain('Mozilla');
}
{
const page = await newPage({ userAgent: 'foobar' });
const [request] = await Promise.all([
server.waitForRequest('/empty.html'),
utils.attachFrame(page, 'frame1', server.EMPTY_PAGE),
]);
expect(request.headers['user-agent']).toBe('foobar');
}
});
it('should emulate device user-agent', async({newPage, server}) => {
{
const page = await newPage();
await page.goto(server.PREFIX + '/mobile.html');
expect(await page.evaluate(() => navigator.userAgent)).not.toContain('iPhone');
}
{
const page = await newPage({ userAgent: playwright.devices['iPhone 6'].userAgent });
await page.goto(server.PREFIX + '/mobile.html');
expect(await page.evaluate(() => navigator.userAgent)).toContain('iPhone');
}
});
});
describe('BrowserContext({bypassCSP})', function() {
it('should bypass CSP meta tag', async({newPage, server}) => {
// Make sure CSP prohibits addScriptTag.
{
const page = await newPage();
await page.goto(server.PREFIX + '/csp.html');
await page.addScriptTag({content: 'window.__injected = 42;'}).catch(e => void e);
expect(await page.evaluate(() => window.__injected)).toBe(undefined);
}
// By-pass CSP and try one more time.
{
const page = await newPage({ bypassCSP: true });
await page.goto(server.PREFIX + '/csp.html');
await page.addScriptTag({content: 'window.__injected = 42;'});
expect(await page.evaluate(() => window.__injected)).toBe(42);
}
});
it('should bypass CSP header', async({newPage, server}) => {
// Make sure CSP prohibits addScriptTag.
server.setCSP('/empty.html', 'default-src "self"');
{
const page = await newPage();
await page.goto(server.EMPTY_PAGE);
await page.addScriptTag({content: 'window.__injected = 42;'}).catch(e => void e);
expect(await page.evaluate(() => window.__injected)).toBe(undefined);
}
// By-pass CSP and try one more time.
{
const page = await newPage({ bypassCSP: true });
await page.goto(server.EMPTY_PAGE);
await page.addScriptTag({content: 'window.__injected = 42;'});
expect(await page.evaluate(() => window.__injected)).toBe(42);
}
});
it('should bypass after cross-process navigation', async({newPage, server}) => {
const page = await newPage({ bypassCSP: true });
await page.goto(server.PREFIX + '/csp.html');
await page.addScriptTag({content: 'window.__injected = 42;'});
expect(await page.evaluate(() => window.__injected)).toBe(42);
await page.goto(server.CROSS_PROCESS_PREFIX + '/csp.html');
await page.addScriptTag({content: 'window.__injected = 42;'});
expect(await page.evaluate(() => window.__injected)).toBe(42);
});
it('should bypass CSP in iframes as well', async({newPage, server}) => {
// Make sure CSP prohibits addScriptTag in an iframe.
{
const page = await newPage();
await page.goto(server.EMPTY_PAGE);
const frame = await utils.attachFrame(page, 'frame1', server.PREFIX + '/csp.html');
await frame.addScriptTag({content: 'window.__injected = 42;'}).catch(e => void e);
expect(await frame.evaluate(() => window.__injected)).toBe(undefined);
}
// By-pass CSP and try one more time.
{
const page = await newPage({ bypassCSP: true });
await page.goto(server.EMPTY_PAGE);
const frame = await utils.attachFrame(page, 'frame1', server.PREFIX + '/csp.html');
await frame.addScriptTag({content: 'window.__injected = 42;'}).catch(e => void e);
expect(await frame.evaluate(() => window.__injected)).toBe(42);
}
});
});
describe('BrowserContext({javaScriptEnabled})', function() {
it('should work', async({newPage}) => {
{
const page = await newPage({ javaScriptEnabled: false });
await page.goto('data:text/html, <script>var something = "forbidden"</script>');
let error = null;
await page.evaluate('something').catch(e => error = e);
if (WEBKIT)
expect(error.message).toContain('Can\'t find variable: something');
else
expect(error.message).toContain('something is not defined');
}
{
const page = await newPage();
await page.goto('data:text/html, <script>var something = "forbidden"</script>');
expect(await page.evaluate('something')).toBe('forbidden');
}
});
it('should be able to navigate after disabling javascript', async({newPage, server}) => {
const page = await newPage({ javaScriptEnabled: false });
await page.goto(server.EMPTY_PAGE);
});
});
};
| test/browsercontext.spec.js | 1 | https://github.com/microsoft/playwright/commit/310d4b193b4a7d3944af95424e44e4293392db24 | [
0.9973980188369751,
0.0820423886179924,
0.00016467274690512568,
0.0013861446641385555,
0.2614525854587555
] |
{
"id": 1,
"code_window": [
" const page = await newPage({ viewport: { width: 456, height: 789 } });\n",
" expect(await page.evaluate('window.innerWidth')).toBe(456);\n",
" expect(await page.evaluate('window.innerHeight')).toBe(789);\n",
" });\n"
],
"labels": [
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" expect(page.viewport().width).toBe(456);\n",
" expect(page.viewport().height).toBe(789);\n"
],
"file_path": "test/browsercontext.spec.js",
"type": "add",
"edit_start_line_idx": 97
} | /**
* 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.
*/
const utils = require('../utils');
const { waitEvent } = utils;
module.exports.describe = function({testRunner, expect, FFOX, CHROME, WEBKIT}) {
const {describe, xdescribe, fdescribe} = testRunner;
const {it, fit, xit, dit} = testRunner;
const {beforeAll, beforeEach, afterAll, afterEach} = testRunner;
describe('Workers', function() {
it('Page.workers', async function({page, server}) {
await Promise.all([
new Promise(x => page.once('workercreated', x)),
page.goto(server.PREFIX + '/worker/worker.html')]);
const worker = page.workers()[0];
expect(worker.url()).toContain('worker.js');
expect(await worker.evaluate(() => self['workerFunction']())).toBe('worker function result');
await page.goto(server.EMPTY_PAGE);
expect(page.workers().length).toBe(0);
});
it('should emit created and destroyed events', async function({page}) {
const workerCreatedPromise = new Promise(x => page.once('workercreated', x));
const workerObj = await page.evaluateHandle(() => new Worker('data:text/javascript,1'));
const worker = await workerCreatedPromise;
const workerThisObj = await worker.evaluateHandle(() => this);
const workerDestroyedPromise = new Promise(x => page.once('workerdestroyed', x));
await page.evaluate(workerObj => workerObj.terminate(), workerObj);
expect(await workerDestroyedPromise).toBe(worker);
const error = await workerThisObj.getProperty('self').catch(error => error);
expect(error.message).toContain('Most likely the worker has been closed.');
});
it('should report console logs', async function({page}) {
const [message] = await Promise.all([
waitEvent(page, 'console'),
page.evaluate(() => new Worker(`data:text/javascript,console.log(1)`)),
]);
expect(message.text()).toBe('1');
expect(message.location()).toEqual({
url: 'data:text/javascript,console.log(1)',
lineNumber: 0,
columnNumber: 8,
});
});
it('should have JSHandles for console logs', async function({page}) {
const logPromise = new Promise(x => page.on('console', x));
await page.evaluate(() => new Worker(`data:text/javascript,console.log(1,2,3,this)`));
const log = await logPromise;
expect(log.text()).toBe('1 2 3 JSHandle@object');
expect(log.args().length).toBe(4);
expect(await (await log.args()[3].getProperty('origin')).jsonValue()).toBe('null');
});
it('should evaluate', async function({page}) {
const workerCreatedPromise = new Promise(x => page.once('workercreated', x));
await page.evaluate(() => new Worker(`data:text/javascript,console.log(1)`));
const worker = await workerCreatedPromise;
expect(await worker.evaluate('1+1')).toBe(2);
});
it('should report errors', async function({page}) {
const errorPromise = new Promise(x => page.on('pageerror', x));
await page.evaluate(() => new Worker(`data:text/javascript, throw new Error('this is my error');`));
const errorLog = await errorPromise;
expect(errorLog.message).toContain('this is my error');
});
});
};
| test/chromium/workers.spec.js | 0 | https://github.com/microsoft/playwright/commit/310d4b193b4a7d3944af95424e44e4293392db24 | [
0.8624807596206665,
0.10243991017341614,
0.00017243913316633552,
0.0004867188981734216,
0.26893576979637146
] |
{
"id": 1,
"code_window": [
" const page = await newPage({ viewport: { width: 456, height: 789 } });\n",
" expect(await page.evaluate('window.innerWidth')).toBe(456);\n",
" expect(await page.evaluate('window.innerHeight')).toBe(789);\n",
" });\n"
],
"labels": [
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" expect(page.viewport().width).toBe(456);\n",
" expect(page.viewport().height).toBe(789);\n"
],
"file_path": "test/browsercontext.spec.js",
"type": "add",
"edit_start_line_idx": 97
} | # Setting Up Build Bots
We currently have 4 build bots that produce 6 builds
- **[buildbot-linux]** Ubuntu 18.04 machine
- builds: `Webkit-Linux`, `Firefox-Linux`
- **[buildbot-mac-10.14]** Mac 10.14 machine
- builds: `WebKit-mac-10.14`, `Firefox-Mac`
- **[buildbot-mac-10.15]** machine
- builds: `WebKit-mac-10.15`
- **[buildbot-windows]** Windows 10 machine
- builds: `Firefox-win32`, `Firefox-win64`
This document describes setting up bots infrastructure to produce
browser builds.
Each bot configuration has 3 parts:
1. Setup toolchains to build browsers
2. Setup bot-specific environment required for bot operations
- `azure-cli`
- setting `AZ_ACCOUNT_KEY`, `AZ_ACCOUNT_NAME`, `TELEGRAM_BOT_KEY` env variables
3. Running relevant build script `//browser_patches/buildbots/buildbot-*.sh` using host scheduling system (cron on Linux, launchctl on Mac, polling on Win).
- [Windows](#windows)
- [Setting Up Browser Toolchains](#setting-up-browser-toolchains)
- [Setting Bot Environment](#setting-bot-environment)
- [Running Build Loop](#running-build-loop)
- [Mac](#mac)
- [Setting Up Browser Toolchains](#setting-up-browser-toolchains-1)
- [Setting Bot Environment](#setting-bot-environment-1)
- [Running Build Loop](#running-build-loop-1)
- [Linux](#linux)
- [Setting Up Browser Toolchains](#setting-up-browser-toolchains-2)
- [Setting Bot Environment](#setting-bot-environment-2)
- [Running Build Loop](#running-build-loop-2)
# Windows
## Setting Up Browser Toolchains
We currently only build firefox on Windows. Follow instructions on [Building Firefox for Windows](https://developer.mozilla.org/en-US/docs/Mozilla/Developer_guide/Build_Instructions/Windows_Prerequisites). Get the checkout with mercurial and run "./mach bootstrap" from mercurial root.
After this step, you should have `c:\mozilla-build` folder
and `c:\mozilla-source` folder with firefox checkout.
## Setting Bot Environment
### 1. Install azure-cli
Install [azure-cli](https://docs.microsoft.com/en-us/cli/azure/install-azure-cli-windows?view=azure-cli-latest) for windows using MS Installer
### 2. Export "az" to the mingw world
Run `cmd` as administrator and run the following line:
```
> echo cmd.exe /c "\"C:\Program Files (x86)\Microsoft SDKs\Azure\CLI2\wbin\az.cmd\" $1 $2 $3 $4 $5 $6 $7 $8 $9 ${10} ${11} ${12} ${13} ${14} ${15} ${16}" > "%SYSTEMROOT%\az"
```
This command will create a `c:\Windows\az` file that will call azure-cli with passed parameters (Not the most beautiful solution, but it works!)
### 3. Set custom env variables to mingw env
Edit `c:\mozilla-build\start-shell.bat` and add the following lines in the beginning:
```bat
SET AZ_ACCOUNT_NAME=<account-name>
SET AZ_ACCOUNT_KEY=<account-key>
SET TELEGRAM_BOT_KEY=<bot_key>
```
change `<account-name>` and `<account-key>` with relevant keys/names.
> **NOTE:** No spaces or quotes are allowed here!
### 4. Disable git autocrlf
Run `c:\mozilla-build\start-shell.bat` and run `git config --global core.autocrlf false`.
### 5. Checkout PlayWright to /c/
Run `c:\mozilla-build\start-shell.bat` and checkout PlayWright repo to `/c/playwright`.
## Running Build Loop
1. Launch `c:\mozilla-build/start-shell.bat`
2. Run `/c/playwright/browser_patches/buildbots/buildbot-windows.sh`
3. Disable "QuickEdit" terminal mode to avoid [terminal freezing and postponing builds](https://stackoverflow.com/questions/33883530/why-is-my-command-prompt-freezing-on-windows-10)
# Mac
## Setting Up Browser Toolchains
1. Install XCode from AppStore
2. Run XCode once and install components, if it requires any.
2. Install XCode command-line tools: `xcode-select --install`
3. Install homebrew: https://brew.sh/
Mac 10.14 builds both firefox and webkit, whereas we only build webkit on mac 10.15.
Browser Toolchains:
- [Building Firefox On Mac](https://developer.mozilla.org/en-US/docs/Mozilla/Developer_guide/Build_Instructions/Mac_OS_X_Prerequisites)
- [Building WebKit On Mac](https://webkit.org/building-webkit/) (though as of Dec, 2019 it does not require any additional steps)
## Setting Bot Environment
1. Install [`azure-cli`](https://docs.microsoft.com/en-us/cli/azure/install-azure-cli-macos?view=azure-cli-latest)
2. Clone `https://github.com/microsoft/playwright`
3. Run `//browser_patches/prepare_checkout.sh` for every browser you care about
4. Make sure `//browser_patches/{webkit,firefox}/build.sh` works and compiles browsers
## Running Build Loop
We use `launchctl` on Mac instead of cron since launchctl lets us run daemons even for non-logged-in users.
Create a `/Library/LaunchDaemons/dev.playwright.plist` with the contents below (will require `sudo` access).
Make sure to change the following fields:
1. Set values for all keys in the `EnvironmentVariables` dict.
2. Put a proper path to the `Program`
3. Make sure to put correct `UserName`
```xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Label</key>
<string>dev.playwright</string>
<key>Program</key>
<string>/Users/aslushnikov/prog/cron/playwright/browser_patches/buildbots/buildbot-mac-10.14.sh</string>
<key>UserName</key>
<string>aslushnikov</string>
<key>EnvironmentVariables</key>
<dict>
<key>PATH</key>
<string>/usr/bin:/usr/sbin</string>
<key>TELEGRAM_BOT_KEY</key>
<string></string>
<key>AZ_ACCOUNT_NAME</key>
<string></string>
<key>AZ_ACCOUNT_KEY</key>
<string></string>
<key>MOZ_NOSPAM</key>
<string>1</string>
</dict>
<key>StandardOutPath</key>
<string>/tmp/launchctl-playwright-buildbot.log</string>
<key>StandardErrorPath</key>
<string>/tmp/launchctl-playwright-buildbot.errorlog</string>
<key>StartInterval</key>
<integer>300</integer>
</dict>
</plist>
```
Next, you can either use `launchctl load` command to load the daemon, or reboot bot to make sure it auto-starts.
> **NOTE**: mozbuild uses [terminal-notifier](https://github.com/julienXX/terminal-notifier) which hangs
> in launchctl environment. The `MOZ_NOSPAM` env variable disables terminal notifications.
Finally, MacBooks tend to go to sleep no matter what their "energy settings" are. To disable sleep permanently on Macs ([source](https://gist.github.com/pwnsdx/2ae98341e7e5e64d32b734b871614915)):
```sh
sudo pmset -a sleep 0; sudo pmset -a hibernatemode 0; sudo pmset -a disablesleep 1;
```
# Linux
## Setting Up Browser Toolchains
1. Note: firefox binaries will crash randomly if compiled with clang 6. They do work when compiled with clang 9.
To install clang 9 on ubuntu and make it default:
```sh
$ sudo apt-get install clang-9
$ sudo update-alternatives --install /usr/bin/clang++ clang++ /usr/bin/clang++-9 100
$ sudo update-alternatives --install /usr/bin/clang clang /usr/bin/clang-9 100
```
> **NOTE**: Firefox build config can be checked official Firefox builds, navigating to `about:buildconfig` URL.
## Setting Bot Environment
> TODO: instructions to set up linux bot
## Running Build Loop
> TODO: instructions to set up cron jobs
| browser_patches/buildbots/README.md | 0 | https://github.com/microsoft/playwright/commit/310d4b193b4a7d3944af95424e44e4293392db24 | [
0.0001775989367160946,
0.00016923279326874763,
0.0001604386925464496,
0.00016859163588378578,
0.000004887097475148039
] |
{
"id": 1,
"code_window": [
" const page = await newPage({ viewport: { width: 456, height: 789 } });\n",
" expect(await page.evaluate('window.innerWidth')).toBe(456);\n",
" expect(await page.evaluate('window.innerHeight')).toBe(789);\n",
" });\n"
],
"labels": [
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" expect(page.viewport().width).toBe(456);\n",
" expect(page.viewport().height).toBe(789);\n"
],
"file_path": "test/browsercontext.spec.js",
"type": "add",
"edit_start_line_idx": 97
} | /**
* Copyright 2019 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 {helper, debugError} from '../helper';
import * as js from '../javascript';
import { FFSession } from './ffConnection';
import { Protocol } from './protocol';
export class FFExecutionContext implements js.ExecutionContextDelegate {
_session: FFSession;
_executionContextId: string;
constructor(session: FFSession, executionContextId: string) {
this._session = session;
this._executionContextId = executionContextId;
}
async evaluate(context: js.ExecutionContext, returnByValue: boolean, pageFunction: Function | string, ...args: any[]): Promise<any> {
if (returnByValue) {
try {
const handle = await this.evaluate(context, false /* returnByValue */, pageFunction, ...args as any);
const result = await handle.jsonValue();
await handle.dispose();
return result;
} catch (e) {
if (e.message.includes('cyclic object value') || e.message.includes('Object is not serializable'))
return undefined;
throw e;
}
}
if (helper.isString(pageFunction)) {
const payload = await this._session.send('Runtime.evaluate', {
expression: pageFunction.trim(),
executionContextId: this._executionContextId,
}).catch(rewriteError);
checkException(payload.exceptionDetails);
return context._createHandle(payload.result);
}
if (typeof pageFunction !== 'function')
throw new Error(`Expected to get |string| or |function| as the first argument, but got "${pageFunction}" instead.`);
let functionText = pageFunction.toString();
try {
new Function('(' + functionText + ')');
} catch (e1) {
// This means we might have a function shorthand. Try another
// time prefixing 'function '.
if (functionText.startsWith('async '))
functionText = 'async function ' + functionText.substring('async '.length);
else
functionText = 'function ' + functionText;
try {
new Function('(' + functionText + ')');
} catch (e2) {
// We tried hard to serialize, but there's a weird beast here.
throw new Error('Passed function is not well-serializable!');
}
}
const protocolArgs = args.map(arg => {
if (arg instanceof js.JSHandle) {
if (arg._context !== context)
throw new Error('JSHandles can be evaluated only in the context they were created!');
if (arg._disposed)
throw new Error('JSHandle is disposed!');
return this._toCallArgument(arg._remoteObject);
}
if (Object.is(arg, Infinity))
return {unserializableValue: 'Infinity'};
if (Object.is(arg, -Infinity))
return {unserializableValue: '-Infinity'};
if (Object.is(arg, -0))
return {unserializableValue: '-0'};
if (Object.is(arg, NaN))
return {unserializableValue: 'NaN'};
return {value: arg};
});
let callFunctionPromise;
try {
callFunctionPromise = this._session.send('Runtime.callFunction', {
functionDeclaration: functionText,
args: protocolArgs,
executionContextId: this._executionContextId
});
} catch (err) {
if (err instanceof TypeError && err.message.startsWith('Converting circular structure to JSON'))
err.message += ' Are you passing a nested JSHandle?';
throw err;
}
const payload = await callFunctionPromise.catch(rewriteError);
checkException(payload.exceptionDetails);
return context._createHandle(payload.result);
function rewriteError(error) : never {
if (error.message.includes('Failed to find execution context with id') || error.message.includes('Execution context was destroyed!'))
throw new Error('Execution context was destroyed, most likely because of a navigation.');
throw error;
}
}
async getProperties(handle: js.JSHandle): Promise<Map<string, js.JSHandle>> {
const response = await this._session.send('Runtime.getObjectProperties', {
executionContextId: this._executionContextId,
objectId: handle._remoteObject.objectId,
});
const result = new Map();
for (const property of response.properties)
result.set(property.name, handle._context._createHandle(property.value));
return result;
}
async releaseHandle(handle: js.JSHandle): Promise<void> {
if (!handle._remoteObject.objectId)
return;
await this._session.send('Runtime.disposeObject', {
executionContextId: this._executionContextId,
objectId: handle._remoteObject.objectId,
}).catch(error => {
// Exceptions might happen in case of a page been navigated or closed.
// Swallow these since they are harmless and we don't leak anything in this case.
debugError(error);
});
}
async handleJSONValue<T>(handle: js.JSHandle<T>): Promise<T> {
const payload = handle._remoteObject;
if (!payload.objectId)
return deserializeValue(payload);
const simpleValue = await this._session.send('Runtime.callFunction', {
executionContextId: this._executionContextId,
returnByValue: true,
functionDeclaration: (e => e).toString(),
args: [this._toCallArgument(payload)],
});
return deserializeValue(simpleValue.result);
}
handleToString(handle: js.JSHandle, includeType: boolean): string {
const payload = handle._remoteObject;
if (payload.objectId)
return 'JSHandle@' + (payload.subtype || payload.type);
return (includeType ? 'JSHandle:' : '') + deserializeValue(payload);
}
private _toCallArgument(payload: any): any {
return { value: payload.value, unserializableValue: payload.unserializableValue, objectId: payload.objectId };
}
}
function checkException(exceptionDetails?: any) {
if (exceptionDetails) {
if (exceptionDetails.value)
throw new Error('Evaluation failed: ' + JSON.stringify(exceptionDetails.value));
else
throw new Error('Evaluation failed: ' + exceptionDetails.text + '\n' + exceptionDetails.stack);
}
}
export function deserializeValue({unserializableValue, value}: Protocol.RemoteObject) {
if (unserializableValue === 'Infinity')
return Infinity;
if (unserializableValue === '-Infinity')
return -Infinity;
if (unserializableValue === '-0')
return -0;
if (unserializableValue === 'NaN')
return NaN;
return value;
}
| src/firefox/ffExecutionContext.ts | 0 | https://github.com/microsoft/playwright/commit/310d4b193b4a7d3944af95424e44e4293392db24 | [
0.0007992453756742179,
0.00020666448108386248,
0.0001623525022296235,
0.00017414585454389453,
0.0001397205051034689
] |
{
"id": 2,
"code_window": [
" expect(await page.evaluate('window.innerWidth')).toBe(456);\n",
" expect(await page.evaluate('window.innerHeight')).toBe(789);\n",
" });\n",
" it('should take fullPage screenshots when default viewport is null', async({server, newPage}) => {\n",
" const page = await newPage({ viewport: null });\n",
" await page.goto(server.PREFIX + '/grid.html');\n",
" const sizeBefore = await page.evaluate(() => ({ width: document.body.offsetWidth, height: document.body.offsetHeight }));\n",
" const screenshot = await page.screenshot({\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" it.skip(WEBKIT)('should propagate default mediaType and colorScheme to the page', async({ newPage }) => {\n",
" const page = await newPage({ mediaType: 'print', colorScheme: 'dark' });\n",
" expect(await page.evaluate(() => matchMedia('print').matches)).toBe(true);\n",
" expect(await page.evaluate(() => matchMedia('(prefers-color-scheme: dark)').matches)).toBe(true);\n",
" });\n"
],
"file_path": "test/browsercontext.spec.js",
"type": "add",
"edit_start_line_idx": 100
} | /**
* Copyright 2019 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.
*/
const fs = require('fs');
const path = require('path');
const os = require('os');
const rm = require('rimraf').sync;
const GoldenUtils = require('./golden-utils');
const {Matchers} = require('../utils/testrunner/');
const YELLOW_COLOR = '\x1b[33m';
const RESET_COLOR = '\x1b[0m';
module.exports.describe = ({testRunner, product, playwrightPath}) => {
const {describe, xdescribe, fdescribe} = testRunner;
const {it, fit, xit, dit} = testRunner;
const {beforeAll, beforeEach, afterAll, afterEach} = testRunner;
const CHROME = product === 'Chromium';
const FFOX = product === 'Firefox';
const WEBKIT = product === 'WebKit';
const MAC = os.platform() === 'darwin';
const LINUX = os.platform() === 'linux';
const WIN = os.platform() === 'win32';
const playwright = require(playwrightPath);
const headless = (process.env.HEADLESS || 'true').trim().toLowerCase() === 'true';
const slowMo = parseInt((process.env.SLOW_MO || '0').trim(), 10);
const executablePath = {
'Chromium': process.env.CRPATH,
'Firefox': process.env.FFPATH,
'WebKit': process.env.WKPATH,
}[product];
const defaultBrowserOptions = {
handleSIGINT: false,
executablePath,
slowMo,
headless,
dumpio: !!process.env.DUMPIO,
};
if (defaultBrowserOptions.executablePath) {
console.warn(`${YELLOW_COLOR}WARN: running ${product} tests with ${defaultBrowserOptions.executablePath}${RESET_COLOR}`);
} else {
// Make sure the `npm install` was run after the chromium roll.
if (!fs.existsSync(playwright.executablePath()))
throw new Error(`Browser is not downloaded. Run 'npm install' and try to re-run tests`);
}
const GOLDEN_DIR = path.join(__dirname, 'golden-' + product.toLowerCase());
const OUTPUT_DIR = path.join(__dirname, 'output-' + product.toLowerCase());
const ASSETS_DIR = path.join(__dirname, 'assets');
if (fs.existsSync(OUTPUT_DIR))
rm(OUTPUT_DIR);
const {expect} = new Matchers({
toBeGolden: GoldenUtils.compare.bind(null, GOLDEN_DIR, OUTPUT_DIR)
});
const testOptions = {
testRunner,
product,
FFOX,
WEBKIT,
CHROME,
MAC,
LINUX,
WIN,
playwright,
expect,
defaultBrowserOptions,
playwrightPath,
headless: !!defaultBrowserOptions.headless,
ASSETS_DIR,
};
describe('Browser', function() {
beforeAll(async state => {
state.browserServer = await playwright.launchServer(defaultBrowserOptions);
state.browser = await state.browserServer.connect();
});
afterAll(async state => {
await state.browserServer.close();
state.browser = null;
state.browserServer = null;
});
beforeEach(async(state, test) => {
const contexts = [];
const onLine = (line) => test.output += line + '\n';
let rl;
if (!WEBKIT) {
rl = require('readline').createInterface({ input: state.browserServer.process().stderr });
test.output = '';
rl.on('line', onLine);
}
state.tearDown = async () => {
await Promise.all(contexts.map(c => c.close()));
if (!WEBKIT) {
rl.removeListener('line', onLine);
rl.close();
}
};
state.newContext = async (options) => {
const context = await state.browser.newContext(options);
contexts.push(context);
return context;
};
state.newPage = async (options) => {
const context = await state.newContext(options);
return await context.newPage(options);
};
});
afterEach(async state => {
await state.tearDown();
});
describe('Page', function() {
beforeEach(async state => {
state.context = await state.newContext();
state.page = await state.context.newPage();
});
afterEach(async state => {
state.context = null;
state.page = null;
});
// Page-level tests that are given a browser, a context and a page.
// Each test is launched in a new browser context.
testRunner.loadTests(require('./accessibility.spec.js'), testOptions);
testRunner.loadTests(require('./click.spec.js'), testOptions);
testRunner.loadTests(require('./cookies.spec.js'), testOptions);
testRunner.loadTests(require('./dialog.spec.js'), testOptions);
testRunner.loadTests(require('./elementhandle.spec.js'), testOptions);
testRunner.loadTests(require('./emulation.spec.js'), testOptions);
testRunner.loadTests(require('./evaluation.spec.js'), testOptions);
testRunner.loadTests(require('./frame.spec.js'), testOptions);
testRunner.loadTests(require('./input.spec.js'), testOptions);
testRunner.loadTests(require('./jshandle.spec.js'), testOptions);
testRunner.loadTests(require('./keyboard.spec.js'), testOptions);
testRunner.loadTests(require('./mouse.spec.js'), testOptions);
testRunner.loadTests(require('./navigation.spec.js'), testOptions);
testRunner.loadTests(require('./network.spec.js'), testOptions);
testRunner.loadTests(require('./page.spec.js'), testOptions);
testRunner.loadTests(require('./queryselector.spec.js'), testOptions);
testRunner.loadTests(require('./screenshot.spec.js'), testOptions);
testRunner.loadTests(require('./waittask.spec.js'), testOptions);
testRunner.loadTests(require('./interception.spec.js'), testOptions);
testRunner.loadTests(require('./geolocation.spec.js'), testOptions);
if (CHROME) {
testRunner.loadTests(require('./chromium/chromium.spec.js'), testOptions);
testRunner.loadTests(require('./chromium/coverage.spec.js'), testOptions);
testRunner.loadTests(require('./chromium/pdf.spec.js'), testOptions);
testRunner.loadTests(require('./chromium/session.spec.js'), testOptions);
testRunner.loadTests(require('./chromium/workers.spec.js'), testOptions);
}
if (CHROME || FFOX) {
testRunner.loadTests(require('./features/permissions.spec.js'), testOptions);
}
});
// Browser-level tests that are given a browser.
testRunner.loadTests(require('./browser.spec.js'), testOptions);
testRunner.loadTests(require('./browsercontext.spec.js'), testOptions);
testRunner.loadTests(require('./ignorehttpserrors.spec.js'), testOptions);
if (CHROME) {
testRunner.loadTests(require('./chromium/browser.spec.js'), testOptions);
}
if (FFOX) {
testRunner.loadTests(require('./firefox/browser.spec.js'), testOptions);
}
});
// Top-level tests that launch Browser themselves.
testRunner.loadTests(require('./defaultbrowsercontext.spec.js'), testOptions);
testRunner.loadTests(require('./fixtures.spec.js'), testOptions);
testRunner.loadTests(require('./launcher.spec.js'), testOptions);
if (CHROME) {
testRunner.loadTests(require('./chromium/connect.spec.js'), testOptions);
testRunner.loadTests(require('./chromium/launcher.spec.js'), testOptions);
testRunner.loadTests(require('./chromium/headful.spec.js'), testOptions);
testRunner.loadTests(require('./chromium/oopif.spec.js'), testOptions);
testRunner.loadTests(require('./chromium/tracing.spec.js'), testOptions);
}
if (FFOX) {
testRunner.loadTests(require('./firefox/launcher.spec.js'), testOptions);
}
if (WEBKIT) {
testRunner.loadTests(require('./webkit/launcher.spec.js'), testOptions);
}
};
| test/playwright.spec.js | 1 | https://github.com/microsoft/playwright/commit/310d4b193b4a7d3944af95424e44e4293392db24 | [
0.00022325624013319612,
0.00017626908083911985,
0.00016471685376018286,
0.00017350709822494537,
0.000012661650544032454
] |
{
"id": 2,
"code_window": [
" expect(await page.evaluate('window.innerWidth')).toBe(456);\n",
" expect(await page.evaluate('window.innerHeight')).toBe(789);\n",
" });\n",
" it('should take fullPage screenshots when default viewport is null', async({server, newPage}) => {\n",
" const page = await newPage({ viewport: null });\n",
" await page.goto(server.PREFIX + '/grid.html');\n",
" const sizeBefore = await page.evaluate(() => ({ width: document.body.offsetWidth, height: document.body.offsetHeight }));\n",
" const screenshot = await page.screenshot({\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" it.skip(WEBKIT)('should propagate default mediaType and colorScheme to the page', async({ newPage }) => {\n",
" const page = await newPage({ mediaType: 'print', colorScheme: 'dark' });\n",
" expect(await page.evaluate(() => matchMedia('print').matches)).toBe(true);\n",
" expect(await page.evaluate(() => matchMedia('(prefers-color-scheme: dark)').matches)).toBe(true);\n",
" });\n"
],
"file_path": "test/browsercontext.spec.js",
"type": "add",
"edit_start_line_idx": 100
} | <script>
window.result = window.injected;
</script> | test/assets/tamperable.html | 0 | https://github.com/microsoft/playwright/commit/310d4b193b4a7d3944af95424e44e4293392db24 | [
0.00016740975843276829,
0.00016740975843276829,
0.00016740975843276829,
0.00016740975843276829,
0
] |
{
"id": 2,
"code_window": [
" expect(await page.evaluate('window.innerWidth')).toBe(456);\n",
" expect(await page.evaluate('window.innerHeight')).toBe(789);\n",
" });\n",
" it('should take fullPage screenshots when default viewport is null', async({server, newPage}) => {\n",
" const page = await newPage({ viewport: null });\n",
" await page.goto(server.PREFIX + '/grid.html');\n",
" const sizeBefore = await page.evaluate(() => ({ width: document.body.offsetWidth, height: document.body.offsetHeight }));\n",
" const screenshot = await page.screenshot({\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" it.skip(WEBKIT)('should propagate default mediaType and colorScheme to the page', async({ newPage }) => {\n",
" const page = await newPage({ mediaType: 'print', colorScheme: 'dark' });\n",
" expect(await page.evaluate(() => matchMedia('print').matches)).toBe(true);\n",
" expect(await page.evaluate(() => matchMedia('(prefers-color-scheme: dark)').matches)).toBe(true);\n",
" });\n"
],
"file_path": "test/browsercontext.spec.js",
"type": "add",
"edit_start_line_idx": 100
} | /**
* 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.
*/
const fs = require('fs');
const path = require('path');
const {FlakinessDashboard} = require('../utils/flakiness-dashboard');
const PROJECT_ROOT = fs.existsSync(path.join(__dirname, '..', 'package.json')) ? path.join(__dirname, '..') : path.join(__dirname, '..', '..');
const COVERAGE_TESTSUITE_NAME = '**API COVERAGE**';
/**
* @param {Map<string, boolean>} apiCoverage
* @param {Object} events
* @param {string} className
* @param {!Object} classType
*/
function traceAPICoverage(apiCoverage, events, className, classType) {
className = className.substring(0, 1).toLowerCase() + className.substring(1);
for (const methodName of Reflect.ownKeys(classType.prototype)) {
const method = Reflect.get(classType.prototype, methodName);
if (methodName === 'constructor' || typeof methodName !== 'string' || methodName.startsWith('_') || typeof method !== 'function')
continue;
apiCoverage.set(`${className}.${methodName}`, false);
Reflect.set(classType.prototype, methodName, function(...args) {
apiCoverage.set(`${className}.${methodName}`, true);
return method.call(this, ...args);
});
}
if (events[classType.name]) {
for (const event of Object.values(events[classType.name])) {
if (typeof event !== 'symbol')
apiCoverage.set(`${className}.emit(${JSON.stringify(event)})`, false);
}
const method = Reflect.get(classType.prototype, 'emit');
Reflect.set(classType.prototype, 'emit', function(event, ...args) {
if (typeof event !== 'symbol' && this.listenerCount(event))
apiCoverage.set(`${className}.emit(${JSON.stringify(event)})`, true);
return method.call(this, event, ...args);
});
}
}
const utils = module.exports = {
recordAPICoverage: function(testRunner, api, events) {
const coverage = new Map();
for (const [className, classType] of Object.entries(api))
traceAPICoverage(coverage, events, className, classType);
testRunner.describe(COVERAGE_TESTSUITE_NAME, () => {
testRunner.it('should call all API methods', () => {
const missingMethods = [];
for (const method of coverage.keys()) {
if (!coverage.get(method))
missingMethods.push(method);
}
if (missingMethods.length)
throw new Error('Certain API Methods are not called: ' + missingMethods.join(', '));
});
});
},
/**
* @return {string}
*/
projectRoot: function() {
return PROJECT_ROOT;
},
/**
* @param {!Page} page
* @param {string} frameId
* @param {string} url
* @return {!Playwright.Frame}
*/
attachFrame: async function(page, frameId, url) {
const frames = new Set(page.frames());
const handle = await page.evaluateHandle(attachFrame, frameId, url);
try {
return await handle.asElement().contentFrame();
} catch(e) {
// we might not support contentFrame, but this can still work ok.
for (const frame of page.frames()) {
if (!frames.has(frame))
return frame;
}
}
return null;
async function attachFrame(frameId, url) {
const frame = document.createElement('iframe');
frame.src = url;
frame.id = frameId;
document.body.appendChild(frame);
// TODO(einbinder) do this right
// Access a scriptable global object to ensure JS context is
// initialized. WebKit will create it lazily only as need be.
frame.contentWindow;
await new Promise(x => frame.onload = x);
return frame;
}
},
isFavicon: function(request) {
return request.url().includes('favicon.ico');
},
/**
* @param {!Page} page
* @param {string} frameId
*/
detachFrame: async function(page, frameId) {
await page.evaluate(detachFrame, frameId);
function detachFrame(frameId) {
const frame = document.getElementById(frameId);
frame.remove();
}
},
/**
* @param {!Page} page
* @param {string} frameId
* @param {string} url
*/
navigateFrame: async function(page, frameId, url) {
await page.evaluate(navigateFrame, frameId, url);
function navigateFrame(frameId, url) {
const frame = document.getElementById(frameId);
frame.src = url;
return new Promise(x => frame.onload = x);
}
},
/**
* @param {!Frame} frame
* @param {string=} indentation
* @return {Array<string>}
*/
dumpFrames: function(frame, indentation) {
indentation = indentation || '';
let description = frame.url().replace(/:\d{4}\//, ':<PORT>/');
if (frame.name())
description += ' (' + frame.name() + ')';
const result = [indentation + description];
const childFrames = frame.childFrames();
childFrames.sort((a, b) => {
if (a.url() !== b.url())
return a.url() < b.url() ? -1 : 1;
return a.name() < b.name() ? -1 : 1;
});
for (const child of childFrames)
result.push(...utils.dumpFrames(child, ' ' + indentation));
return result;
},
/**
* @param {!EventEmitter} emitter
* @param {string} eventName
* @return {!Promise<!Object>}
*/
waitEvent: function(emitter, eventName, predicate = () => true) {
return new Promise(fulfill => {
emitter.on(eventName, function listener(event) {
if (!predicate(event))
return;
emitter.removeListener(eventName, listener);
fulfill(event);
});
});
},
initializeFlakinessDashboardIfNeeded: async function(testRunner) {
// Generate testIDs for all tests and verify they don't clash.
// This will add |test.testId| for every test.
//
// NOTE: we do this on CI's so that problems arise on PR trybots.
if (process.env.CI)
generateTestIDs(testRunner);
// FLAKINESS_DASHBOARD_PASSWORD is an encrypted/secured variable.
// Encrypted variables get a special treatment in CI's when handling PRs so that
// secrets are not leaked to untrusted code.
// - AppVeyor DOES NOT decrypt secured variables for PRs
// - Travis DOES NOT decrypt encrypted variables for PRs
// - Cirrus CI DOES NOT decrypt encrypted variables for PRs *unless* PR is sent
// from someone who has WRITE ACCESS to the repo.
//
// Since we don't want to run flakiness dashboard for PRs on all CIs, we
// check existance of FLAKINESS_DASHBOARD_PASSWORD and absense of
// CIRRUS_BASE_SHA env variables.
if (!process.env.FLAKINESS_DASHBOARD_PASSWORD || process.env.CIRRUS_BASE_SHA)
return;
const {sha, timestamp} = await FlakinessDashboard.getCommitDetails(__dirname, 'HEAD');
const dashboard = new FlakinessDashboard({
commit: {
sha,
timestamp,
url: `https://github.com/Microsoft/playwright/commit/${sha}`,
},
build: {
url: process.env.FLAKINESS_DASHBOARD_BUILD_URL,
},
dashboardRepo: {
url: 'https://github.com/aslushnikov/playwright-flakiness-dashboard.git',
username: 'playwright-flakiness',
email: '[email protected]',
password: process.env.FLAKINESS_DASHBOARD_PASSWORD,
branch: process.env.FLAKINESS_DASHBOARD_NAME,
},
});
testRunner.on('testfinished', test => {
// Do not report tests from COVERAGE testsuite.
// They don't bring much value to us.
if (test.fullName.includes(COVERAGE_TESTSUITE_NAME))
return;
const testpath = test.location.filePath.substring(utils.projectRoot().length);
const url = `https://github.com/Microsoft/playwright/blob/${sha}/${testpath}#L${test.location.lineNumber}`;
dashboard.reportTestResult({
testId: test.testId,
name: test.location.fileName + ':' + test.location.lineNumber,
description: test.fullName,
url,
result: test.result,
});
});
testRunner.on('finished', async({result}) => {
dashboard.setBuildResult(result);
await dashboard.uploadAndCleanup();
});
function generateTestIDs(testRunner) {
const testIds = new Map();
for (const test of testRunner.tests()) {
const testIdComponents = [test.name];
for (let suite = test.suite; !!suite.parentSuite; suite = suite.parentSuite)
testIdComponents.push(suite.name);
testIdComponents.reverse();
const testId = testIdComponents.join('>');
const clashingTest = testIds.get(testId);
if (clashingTest)
throw new Error(`Two tests with clashing IDs: ${test.location.fileName}:${test.location.lineNumber} and ${clashingTest.location.fileName}:${clashingTest.location.lineNumber}`);
testIds.set(testId, test);
test.testId = testId;
}
}
},
};
| test/utils.js | 0 | https://github.com/microsoft/playwright/commit/310d4b193b4a7d3944af95424e44e4293392db24 | [
0.0002661759499460459,
0.00017715839203447104,
0.00016527365369256586,
0.00017450490850023925,
0.000017794154700823128
] |
{
"id": 2,
"code_window": [
" expect(await page.evaluate('window.innerWidth')).toBe(456);\n",
" expect(await page.evaluate('window.innerHeight')).toBe(789);\n",
" });\n",
" it('should take fullPage screenshots when default viewport is null', async({server, newPage}) => {\n",
" const page = await newPage({ viewport: null });\n",
" await page.goto(server.PREFIX + '/grid.html');\n",
" const sizeBefore = await page.evaluate(() => ({ width: document.body.offsetWidth, height: document.body.offsetHeight }));\n",
" const screenshot = await page.screenshot({\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" it.skip(WEBKIT)('should propagate default mediaType and colorScheme to the page', async({ newPage }) => {\n",
" const page = await newPage({ mediaType: 'print', colorScheme: 'dark' });\n",
" expect(await page.evaluate(() => matchMedia('print').matches)).toBe(true);\n",
" expect(await page.evaluate(() => matchMedia('(prefers-color-scheme: dark)').matches)).toBe(true);\n",
" });\n"
],
"file_path": "test/browsercontext.spec.js",
"type": "add",
"edit_start_line_idx": 100
} |
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright 2017 Google Inc.
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.
| utils/testserver/LICENSE | 0 | https://github.com/microsoft/playwright/commit/310d4b193b4a7d3944af95424e44e4293392db24 | [
0.00018127975636161864,
0.00017827855481300503,
0.00017573787772562355,
0.00017828200361691415,
0.000001410593085893197
] |
{
"id": 3,
"code_window": [
" const sizeAfter = await page.evaluate(() => ({ width: document.body.offsetWidth, height: document.body.offsetHeight }));\n",
" expect(sizeBefore.width).toBe(sizeAfter.width);\n",
" expect(sizeBefore.height).toBe(sizeAfter.height);\n",
" });\n",
" });\n",
"\n",
" describe('BrowserContext({setUserAgent})', function() {\n",
" it('should work', async({newPage, server}) => {\n",
" {\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" it('should restore default viewport after fullPage screenshot', async({ newPage }) => {\n",
" const page = await newPage({ viewport: { width: 456, height: 789 } });\n",
" expect(page.viewport().width).toBe(456);\n",
" expect(page.viewport().height).toBe(789);\n",
" expect(await page.evaluate('window.innerWidth')).toBe(456);\n",
" expect(await page.evaluate('window.innerHeight')).toBe(789);\n",
" const screenshot = await page.screenshot({ fullPage: true });\n",
" expect(screenshot).toBeInstanceOf(Buffer);\n",
" expect(page.viewport().width).toBe(456);\n",
" expect(page.viewport().height).toBe(789);\n",
" expect(await page.evaluate('window.innerWidth')).toBe(456);\n",
" expect(await page.evaluate('window.innerHeight')).toBe(789);\n",
" });\n"
],
"file_path": "test/browsercontext.spec.js",
"type": "add",
"edit_start_line_idx": 113
} | /**
* Copyright 2018 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.
*/
const utils = require('./utils');
module.exports.describe = function({testRunner, expect, playwright, CHROME, WEBKIT}) {
const {describe, xdescribe, fdescribe} = testRunner;
const {it, fit, xit, dit} = testRunner;
const {beforeAll, beforeEach, afterAll, afterEach} = testRunner;
describe('BrowserContext', function() {
it('should have default context', async function({browser, server}) {
expect(browser.browserContexts().length).toBe(1);
const defaultContext = browser.browserContexts()[0];
let error = null;
await defaultContext.close().catch(e => error = e);
expect(browser.defaultContext()).toBe(defaultContext);
expect(error.message).toContain('cannot be closed');
});
it('should create new incognito context', async function({browser, newContext}) {
expect(browser.browserContexts().length).toBe(1);
const context = await newContext();
expect(browser.browserContexts().length).toBe(2);
expect(browser.browserContexts().indexOf(context) !== -1).toBe(true);
await context.close();
expect(browser.browserContexts().length).toBe(1);
});
it('window.open should use parent tab context', async function({newContext, server}) {
const context = await newContext();
const page = await context.newPage();
await page.goto(server.EMPTY_PAGE);
const [popupTarget] = await Promise.all([
utils.waitEvent(page, 'popup'),
page.evaluate(url => window.open(url), server.EMPTY_PAGE)
]);
expect(popupTarget.browserContext()).toBe(context);
});
it('should isolate localStorage and cookies', async function({browser, newContext, server}) {
// Create two incognito contexts.
const context1 = await newContext();
const context2 = await newContext();
expect((await context1.pages()).length).toBe(0);
expect((await context2.pages()).length).toBe(0);
// Create a page in first incognito context.
const page1 = await context1.newPage();
await page1.goto(server.EMPTY_PAGE);
await page1.evaluate(() => {
localStorage.setItem('name', 'page1');
document.cookie = 'name=page1';
});
expect((await context1.pages()).length).toBe(1);
expect((await context2.pages()).length).toBe(0);
// Create a page in second incognito context.
const page2 = await context2.newPage();
await page2.goto(server.EMPTY_PAGE);
await page2.evaluate(() => {
localStorage.setItem('name', 'page2');
document.cookie = 'name=page2';
});
expect((await context1.pages()).length).toBe(1);
expect((await context2.pages()).length).toBe(1);
expect((await context1.pages())[0]).toBe(page1);
expect((await context2.pages())[0]).toBe(page2);
// Make sure pages don't share localstorage or cookies.
expect(await page1.evaluate(() => localStorage.getItem('name'))).toBe('page1');
expect(await page1.evaluate(() => document.cookie)).toBe('name=page1');
expect(await page2.evaluate(() => localStorage.getItem('name'))).toBe('page2');
expect(await page2.evaluate(() => document.cookie)).toBe('name=page2');
// Cleanup contexts.
await Promise.all([
context1.close(),
context2.close()
]);
expect(browser.browserContexts().length).toBe(1);
});
it('should set the default viewport', async({ newPage }) => {
const page = await newPage({ viewport: { width: 456, height: 789 } });
expect(await page.evaluate('window.innerWidth')).toBe(456);
expect(await page.evaluate('window.innerHeight')).toBe(789);
});
it('should take fullPage screenshots when default viewport is null', async({server, newPage}) => {
const page = await newPage({ viewport: null });
await page.goto(server.PREFIX + '/grid.html');
const sizeBefore = await page.evaluate(() => ({ width: document.body.offsetWidth, height: document.body.offsetHeight }));
const screenshot = await page.screenshot({
fullPage: true
});
expect(screenshot).toBeInstanceOf(Buffer);
const sizeAfter = await page.evaluate(() => ({ width: document.body.offsetWidth, height: document.body.offsetHeight }));
expect(sizeBefore.width).toBe(sizeAfter.width);
expect(sizeBefore.height).toBe(sizeAfter.height);
});
});
describe('BrowserContext({setUserAgent})', function() {
it('should work', async({newPage, server}) => {
{
const page = await newPage();
expect(await page.evaluate(() => navigator.userAgent)).toContain('Mozilla');
}
{
const page = await newPage({ userAgent: 'foobar' });
const [request] = await Promise.all([
server.waitForRequest('/empty.html'),
page.goto(server.EMPTY_PAGE),
]);
expect(request.headers['user-agent']).toBe('foobar');
}
});
it('should work for subframes', async({newPage, server}) => {
{
const page = await newPage();
expect(await page.evaluate(() => navigator.userAgent)).toContain('Mozilla');
}
{
const page = await newPage({ userAgent: 'foobar' });
const [request] = await Promise.all([
server.waitForRequest('/empty.html'),
utils.attachFrame(page, 'frame1', server.EMPTY_PAGE),
]);
expect(request.headers['user-agent']).toBe('foobar');
}
});
it('should emulate device user-agent', async({newPage, server}) => {
{
const page = await newPage();
await page.goto(server.PREFIX + '/mobile.html');
expect(await page.evaluate(() => navigator.userAgent)).not.toContain('iPhone');
}
{
const page = await newPage({ userAgent: playwright.devices['iPhone 6'].userAgent });
await page.goto(server.PREFIX + '/mobile.html');
expect(await page.evaluate(() => navigator.userAgent)).toContain('iPhone');
}
});
});
describe('BrowserContext({bypassCSP})', function() {
it('should bypass CSP meta tag', async({newPage, server}) => {
// Make sure CSP prohibits addScriptTag.
{
const page = await newPage();
await page.goto(server.PREFIX + '/csp.html');
await page.addScriptTag({content: 'window.__injected = 42;'}).catch(e => void e);
expect(await page.evaluate(() => window.__injected)).toBe(undefined);
}
// By-pass CSP and try one more time.
{
const page = await newPage({ bypassCSP: true });
await page.goto(server.PREFIX + '/csp.html');
await page.addScriptTag({content: 'window.__injected = 42;'});
expect(await page.evaluate(() => window.__injected)).toBe(42);
}
});
it('should bypass CSP header', async({newPage, server}) => {
// Make sure CSP prohibits addScriptTag.
server.setCSP('/empty.html', 'default-src "self"');
{
const page = await newPage();
await page.goto(server.EMPTY_PAGE);
await page.addScriptTag({content: 'window.__injected = 42;'}).catch(e => void e);
expect(await page.evaluate(() => window.__injected)).toBe(undefined);
}
// By-pass CSP and try one more time.
{
const page = await newPage({ bypassCSP: true });
await page.goto(server.EMPTY_PAGE);
await page.addScriptTag({content: 'window.__injected = 42;'});
expect(await page.evaluate(() => window.__injected)).toBe(42);
}
});
it('should bypass after cross-process navigation', async({newPage, server}) => {
const page = await newPage({ bypassCSP: true });
await page.goto(server.PREFIX + '/csp.html');
await page.addScriptTag({content: 'window.__injected = 42;'});
expect(await page.evaluate(() => window.__injected)).toBe(42);
await page.goto(server.CROSS_PROCESS_PREFIX + '/csp.html');
await page.addScriptTag({content: 'window.__injected = 42;'});
expect(await page.evaluate(() => window.__injected)).toBe(42);
});
it('should bypass CSP in iframes as well', async({newPage, server}) => {
// Make sure CSP prohibits addScriptTag in an iframe.
{
const page = await newPage();
await page.goto(server.EMPTY_PAGE);
const frame = await utils.attachFrame(page, 'frame1', server.PREFIX + '/csp.html');
await frame.addScriptTag({content: 'window.__injected = 42;'}).catch(e => void e);
expect(await frame.evaluate(() => window.__injected)).toBe(undefined);
}
// By-pass CSP and try one more time.
{
const page = await newPage({ bypassCSP: true });
await page.goto(server.EMPTY_PAGE);
const frame = await utils.attachFrame(page, 'frame1', server.PREFIX + '/csp.html');
await frame.addScriptTag({content: 'window.__injected = 42;'}).catch(e => void e);
expect(await frame.evaluate(() => window.__injected)).toBe(42);
}
});
});
describe('BrowserContext({javaScriptEnabled})', function() {
it('should work', async({newPage}) => {
{
const page = await newPage({ javaScriptEnabled: false });
await page.goto('data:text/html, <script>var something = "forbidden"</script>');
let error = null;
await page.evaluate('something').catch(e => error = e);
if (WEBKIT)
expect(error.message).toContain('Can\'t find variable: something');
else
expect(error.message).toContain('something is not defined');
}
{
const page = await newPage();
await page.goto('data:text/html, <script>var something = "forbidden"</script>');
expect(await page.evaluate('something')).toBe('forbidden');
}
});
it('should be able to navigate after disabling javascript', async({newPage, server}) => {
const page = await newPage({ javaScriptEnabled: false });
await page.goto(server.EMPTY_PAGE);
});
});
};
| test/browsercontext.spec.js | 1 | https://github.com/microsoft/playwright/commit/310d4b193b4a7d3944af95424e44e4293392db24 | [
0.9930889010429382,
0.07958387583494186,
0.0001647097960812971,
0.002734030596911907,
0.263631135225296
] |
{
"id": 3,
"code_window": [
" const sizeAfter = await page.evaluate(() => ({ width: document.body.offsetWidth, height: document.body.offsetHeight }));\n",
" expect(sizeBefore.width).toBe(sizeAfter.width);\n",
" expect(sizeBefore.height).toBe(sizeAfter.height);\n",
" });\n",
" });\n",
"\n",
" describe('BrowserContext({setUserAgent})', function() {\n",
" it('should work', async({newPage, server}) => {\n",
" {\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" it('should restore default viewport after fullPage screenshot', async({ newPage }) => {\n",
" const page = await newPage({ viewport: { width: 456, height: 789 } });\n",
" expect(page.viewport().width).toBe(456);\n",
" expect(page.viewport().height).toBe(789);\n",
" expect(await page.evaluate('window.innerWidth')).toBe(456);\n",
" expect(await page.evaluate('window.innerHeight')).toBe(789);\n",
" const screenshot = await page.screenshot({ fullPage: true });\n",
" expect(screenshot).toBeInstanceOf(Buffer);\n",
" expect(page.viewport().width).toBe(456);\n",
" expect(page.viewport().height).toBe(789);\n",
" expect(await page.evaluate('window.innerWidth')).toBe(456);\n",
" expect(await page.evaluate('window.innerHeight')).toBe(789);\n",
" });\n"
],
"file_path": "test/browsercontext.spec.js",
"type": "add",
"edit_start_line_idx": 113
} | // @ts-check
const path = require('path');
const fs = require('fs');
const StreamZip = require('node-stream-zip');
const vm = require('vm');
const os = require('os');
async function generateChromeProtocol(revision) {
const outputPath = path.join(__dirname, '..', '..', 'src', 'chromium', 'protocol.ts');
if (revision.local && fs.existsSync(outputPath))
return;
const playwright = await require('../../chromium');
const browserServer = await playwright.launchServer({executablePath: revision.executablePath});
const origin = browserServer.wsEndpoint().match(/ws:\/\/([0-9A-Za-z:\.]*)\//)[1];
const page = await (await browserServer.connect()).defaultContext().newPage();
await page.goto(`http://${origin}/json/protocol`);
const json = JSON.parse(await page.evaluate(() => document.documentElement.innerText));
await browserServer.close();
fs.writeFileSync(outputPath, jsonToTS(json));
console.log(`Wrote protocol.ts to ${path.relative(process.cwd(), outputPath)}`);
}
async function generateWebKitProtocol(revision) {
const outputPath = path.join(__dirname, '..', '..', 'src', 'webkit', 'protocol.ts');
if (revision.local && fs.existsSync(outputPath))
return;
const json = JSON.parse(fs.readFileSync(path.join(revision.folderPath, 'protocol.json'), 'utf8'));
fs.writeFileSync(outputPath, jsonToTS({domains: json}));
console.log(`Wrote protocol.ts for WebKit to ${path.relative(process.cwd(), outputPath)}`);
}
function jsonToTS(json) {
return `// This is generated from /utils/protocol-types-generator/index.js
type binary = string;
export module Protocol {${json.domains.map(domain => `${domain.description ? `
/**
* ${domain.description}
*/` : ''}
export module ${domain.domain} {${(domain.types || []).map(type => `${type.description ? `
/**
* ${type.description}
*/` : ''}${type.properties ? `
export interface ${type.id} {${(type.properties || []).map(property => `${property.description ? `
/**
* ${property.description}
*/` : ''}
${property.name}${property.optional ? '?' : ''}: ${typeOfProperty(property)};`).join(``)}
}` : `
export type ${type.id} = ${typeOfProperty(type)};`}`).join('')}
${(domain.events || []).map(event => `${event.description ? `
/**
* ${event.description}
*/` : ''}${event.parameters ? `
export type ${event.name}Payload = {${event.parameters.map(parameter => `${parameter.description ? `
/**
* ${parameter.description}
*/` : ''}
${parameter.name}${parameter.optional ? '?' : ''}: ${typeOfProperty(parameter)};`).join(``)}
}` : `
export type ${event.name}Payload = void;`}`).join('')}
${(domain.commands || []).map(command => `${command.description ? `
/**
* ${command.description}
*/` : ''}
export type ${command.name}Parameters = {${(command.parameters || []).map(parameter => `${parameter.description ? `
/**
* ${parameter.description}
*/` : ''}
${parameter.name}${parameter.optional ? '?' : ''}: ${typeOfProperty(parameter)};`).join(``)}
}
export type ${command.name}ReturnValue = {${(command.returns || []).map(retVal => `${retVal.description ? `
/**
* ${retVal.description}
*/` : ''}
${retVal.name}${retVal.optional ? '?' : ''}: ${typeOfProperty(retVal)};`).join(``)}
}`).join('')}
}
`).join('')}
export interface Events {${json.domains.map(domain => (domain.events || []).map(event => `
"${domain.domain}.${event.name}": ${domain.domain}.${event.name}Payload;`).join('')).join('')}
}
export interface CommandParameters {${json.domains.map(domain => (domain.commands || []).map(command => `
"${domain.domain}.${command.name}": ${domain.domain}.${command.name}Parameters;`).join('')).join('')}
}
export interface CommandReturnValues {${json.domains.map(domain => (domain.commands || []).map(command => `
"${domain.domain}.${command.name}": ${domain.domain}.${command.name}ReturnValue;`).join('')).join('')}
}
}
`;
}
/**
* @typedef {Object} Property
* @property {string=} $ref
* @property {!Array=} enum
* @property {string=} type
* @property {!Property=} items
* @property {string=} description
*/
/**
* @param {!Property} property
* @param {string=} domain
*/
function typeOfProperty(property, domain) {
if (property.$ref) return property.$ref.includes('.') || !domain ? property.$ref : domain + '.' + property.$ref;
if (property.enum) return property.enum.map(value => JSON.stringify(value)).join('|');
switch (property.type) {
case 'array':
return typeOfProperty(property.items, domain) + '[]';
case 'integer':
return 'number';
case 'object':
return '{ [key: string]: string }';
}
return property.type;
}
async function generateFirefoxProtocol(revision) {
const outputPath = path.join(__dirname, '..', '..', 'src', 'firefox', 'protocol.ts');
if (revision.local && fs.existsSync(outputPath))
return;
const omnija = os.platform() === 'darwin' ?
path.join(revision.executablePath, '..', '..', 'Resources', 'omni.ja') :
path.join(revision.executablePath, '..', 'omni.ja');
const zip = new StreamZip({file: omnija, storeEntries: true});
// @ts-ignore
await new Promise(x => zip.on('ready', x));
const data = zip.entryDataSync(zip.entry('chrome/juggler/content/protocol/Protocol.js'))
const ctx = vm.createContext();
const protocolJSCode = data.toString('utf8');
function inject() {
this.ChromeUtils = {
import: () => ({t})
}
const t = {};
t.String = {"$type": "string"};
t.Number = {"$type": "number"};
t.Boolean = {"$type": "boolean"};
t.Undefined = {"$type": "undefined"};
t.Any = {"$type": "any"};
t.Enum = function(values) {
return {"$type": "enum", "$values": values};
}
t.Nullable = function(scheme) {
return {...scheme, "$nullable": true};
}
t.Optional = function(scheme) {
return {...scheme, "$optional": true};
}
t.Array = function(scheme) {
return {"$type": "array", "$items": scheme};
}
t.Recursive = function(types, schemeName) {
return {"$type": "ref", "$ref": schemeName };
}
}
const json = vm.runInContext(`(${inject})();${protocolJSCode}; this.protocol.types = types; this.protocol;`, ctx);
fs.writeFileSync(outputPath, firefoxJSONToTS(json));
console.log(`Wrote protocol.ts for Firefox to ${path.relative(process.cwd(), outputPath)}`);
}
function firefoxJSONToTS(json) {
const domains = Object.entries(json.domains);
return `// This is generated from /utils/protocol-types-generator/index.js
export module Protocol {${Object.entries(json.types).map(([typeName, type]) => `
export type ${typeName} = ${firefoxTypeToString(type, ' ')};`).join('')}
${domains.map(([domainName, domain]) => `
export module ${domainName} {${(Object.entries(domain.events)).map(([eventName, event]) => `
export type ${eventName}Payload = ${firefoxTypeToString(event)}`).join('')}${(Object.entries(domain.methods)).map(([commandName, command]) => `
export type ${commandName}Parameters = ${firefoxTypeToString(command.params)};
export type ${commandName}ReturnValue = ${firefoxTypeToString(command.returns)};`).join('')}
}`).join('')}
export interface Events {${domains.map(([domainName, domain]) => Object.keys(domain.events).map(eventName => `
"${domainName}.${eventName}": ${domainName}.${eventName}Payload;`).join('')).join('')}
}
export interface CommandParameters {${domains.map(([domainName, domain]) => Object.keys(domain.methods).map(commandName => `
"${domainName}.${commandName}": ${domainName}.${commandName}Parameters;`).join('')).join('')}
}
export interface CommandReturnValues {${domains.map(([domainName, domain]) => Object.keys(domain.methods).map(commandName => `
"${domainName}.${commandName}": ${domainName}.${commandName}ReturnValue;`).join('')).join('')}
}
}`
}
function firefoxTypeToString(type, indent=' ') {
if (!type)
return 'void';
if (!type['$type']) {
const properties = Object.entries(type).filter(([name]) => !name.startsWith('$'));
const lines = [];
lines.push('{');
for (const [propertyName, property] of properties) {
const nameSuffix = property['$optional'] ? '?' : '';
const valueSuffix = property['$nullable'] ? '|null' : ''
lines.push(`${indent} ${propertyName}${nameSuffix}: ${firefoxTypeToString(property, indent + ' ')}${valueSuffix};`);
}
lines.push(`${indent}}`);
return lines.join('\n');
}
if (type['$type'] === 'ref')
return type['$ref'];
if (type['$type'] === 'array')
return firefoxTypeToString(type['$items'], indent) + '[]';
if (type['$type'] === 'enum')
return type['$values'].map(v => JSON.stringify(v)).join('|');
return type['$type'];
}
module.exports = {generateChromeProtocol, generateFirefoxProtocol, generateWebKitProtocol}; | utils/protocol-types-generator/index.js | 0 | https://github.com/microsoft/playwright/commit/310d4b193b4a7d3944af95424e44e4293392db24 | [
0.0020553567446768284,
0.00025974001619033515,
0.00016480938938912004,
0.0001748169306665659,
0.00039185589412227273
] |
{
"id": 3,
"code_window": [
" const sizeAfter = await page.evaluate(() => ({ width: document.body.offsetWidth, height: document.body.offsetHeight }));\n",
" expect(sizeBefore.width).toBe(sizeAfter.width);\n",
" expect(sizeBefore.height).toBe(sizeAfter.height);\n",
" });\n",
" });\n",
"\n",
" describe('BrowserContext({setUserAgent})', function() {\n",
" it('should work', async({newPage, server}) => {\n",
" {\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" it('should restore default viewport after fullPage screenshot', async({ newPage }) => {\n",
" const page = await newPage({ viewport: { width: 456, height: 789 } });\n",
" expect(page.viewport().width).toBe(456);\n",
" expect(page.viewport().height).toBe(789);\n",
" expect(await page.evaluate('window.innerWidth')).toBe(456);\n",
" expect(await page.evaluate('window.innerHeight')).toBe(789);\n",
" const screenshot = await page.screenshot({ fullPage: true });\n",
" expect(screenshot).toBeInstanceOf(Buffer);\n",
" expect(page.viewport().width).toBe(456);\n",
" expect(page.viewport().height).toBe(789);\n",
" expect(await page.evaluate('window.innerWidth')).toBe(456);\n",
" expect(await page.evaluate('window.innerHeight')).toBe(789);\n",
" });\n"
],
"file_path": "test/browsercontext.spec.js",
"type": "add",
"edit_start_line_idx": 113
} | <script>
window.result = window.injected;
</script> | test/assets/tamperable.html | 0 | https://github.com/microsoft/playwright/commit/310d4b193b4a7d3944af95424e44e4293392db24 | [
0.00017211258818861097,
0.00017211258818861097,
0.00017211258818861097,
0.00017211258818861097,
0
] |
{
"id": 3,
"code_window": [
" const sizeAfter = await page.evaluate(() => ({ width: document.body.offsetWidth, height: document.body.offsetHeight }));\n",
" expect(sizeBefore.width).toBe(sizeAfter.width);\n",
" expect(sizeBefore.height).toBe(sizeAfter.height);\n",
" });\n",
" });\n",
"\n",
" describe('BrowserContext({setUserAgent})', function() {\n",
" it('should work', async({newPage, server}) => {\n",
" {\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" it('should restore default viewport after fullPage screenshot', async({ newPage }) => {\n",
" const page = await newPage({ viewport: { width: 456, height: 789 } });\n",
" expect(page.viewport().width).toBe(456);\n",
" expect(page.viewport().height).toBe(789);\n",
" expect(await page.evaluate('window.innerWidth')).toBe(456);\n",
" expect(await page.evaluate('window.innerHeight')).toBe(789);\n",
" const screenshot = await page.screenshot({ fullPage: true });\n",
" expect(screenshot).toBeInstanceOf(Buffer);\n",
" expect(page.viewport().width).toBe(456);\n",
" expect(page.viewport().height).toBe(789);\n",
" expect(await page.evaluate('window.innerWidth')).toBe(456);\n",
" expect(await page.evaluate('window.innerHeight')).toBe(789);\n",
" });\n"
],
"file_path": "test/browsercontext.spec.js",
"type": "add",
"edit_start_line_idx": 113
} | [
{
"url": "http://localhost:<PORT>/csscoverage/involved.html",
"ranges": [
{
"start": 149,
"end": 297
},
{
"start": 327,
"end": 433
}
],
"text": "\n@charset \"utf-8\";\n@namespace svg url(http://www.w3.org/2000/svg);\n@font-face {\n font-family: \"Example Font\";\n src: url(\"./Dosis-Regular.ttf\");\n}\n\n#fluffy {\n border: 1px solid black;\n z-index: 1;\n /* -webkit-disabled-property: rgb(1, 2, 3) */\n -lol-cats: \"dogs\" /* non-existing property */\n}\n\n@media (min-width: 1px) {\n span {\n -webkit-border-radius: 10px;\n font-family: \"Example Font\";\n animation: 1s identifier;\n }\n}\n"
}
] | test/golden-chromium/csscoverage-involved.txt | 0 | https://github.com/microsoft/playwright/commit/310d4b193b4a7d3944af95424e44e4293392db24 | [
0.00017788264085538685,
0.00017730638501234353,
0.00017673014372121543,
0.00017730638501234353,
5.762485670857131e-7
] |
{
"id": 4,
"code_window": [
" const page = await newPage({ userAgent: 'foobar' });\n",
" const [request] = await Promise.all([\n",
" server.waitForRequest('/empty.html'),\n",
" page.goto(server.EMPTY_PAGE),\n",
" ]);\n",
" expect(request.headers['user-agent']).toBe('foobar'); \n",
" }\n",
" });\n",
" it('should work for subframes', async({newPage, server}) => {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" expect(request.headers['user-agent']).toBe('foobar');\n"
],
"file_path": "test/browsercontext.spec.js",
"type": "replace",
"edit_start_line_idx": 127
} | /**
* Copyright 2018 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.
*/
module.exports.describe = function({testRunner, expect, product, FFOX, CHROME, WEBKIT}) {
const {describe, xdescribe, fdescribe} = testRunner;
const {it, fit, xit, dit} = testRunner;
const {beforeAll, beforeEach, afterAll, afterEach} = testRunner;
describe('Page.screenshot', function() {
it('should work', async({page, server}) => {
await page.setViewport({width: 500, height: 500});
await page.goto(server.PREFIX + '/grid.html');
const screenshot = await page.screenshot();
expect(screenshot).toBeGolden('screenshot-sanity.png');
});
it('should clip rect', async({page, server}) => {
await page.setViewport({width: 500, height: 500});
await page.goto(server.PREFIX + '/grid.html');
const screenshot = await page.screenshot({
clip: {
x: 50,
y: 100,
width: 150,
height: 100
}
});
expect(screenshot).toBeGolden('screenshot-clip-rect.png');
});
it('should clip elements to the viewport', async({page, server}) => {
await page.setViewport({width: 500, height: 500});
await page.goto(server.PREFIX + '/grid.html');
const screenshot = await page.screenshot({
clip: {
x: 50,
y: 450,
width: 1000,
height: 100
}
});
expect(screenshot).toBeGolden('screenshot-offscreen-clip.png');
});
it('should throw on clip outside the viewport', async({page, server}) => {
await page.setViewport({width: 500, height: 500});
await page.goto(server.PREFIX + '/grid.html');
const screenshotError = await page.screenshot({
clip: {
x: 50,
y: 650,
width: 100,
height: 100
}
}).catch(error => error);
expect(screenshotError.message).toBe('Clipped area is either empty or outside the viewport');
});
it('should run in parallel', async({page, server}) => {
await page.setViewport({width: 500, height: 500});
await page.goto(server.PREFIX + '/grid.html');
const promises = [];
for (let i = 0; i < 3; ++i) {
promises.push(page.screenshot({
clip: {
x: 50 * i,
y: 0,
width: 50,
height: 50
}
}));
}
const screenshots = await Promise.all(promises);
expect(screenshots[1]).toBeGolden('grid-cell-1.png');
});
it('should take fullPage screenshots', async({page, server}) => {
await page.setViewport({width: 500, height: 500});
await page.goto(server.PREFIX + '/grid.html');
const screenshot = await page.screenshot({
fullPage: true
});
expect(screenshot).toBeGolden('screenshot-grid-fullpage.png');
});
it('should run in parallel in multiple pages', async({page, server, context}) => {
const N = 2;
const pages = await Promise.all(Array(N).fill(0).map(async() => {
const page = await context.newPage();
await page.goto(server.PREFIX + '/grid.html');
return page;
}));
const promises = [];
for (let i = 0; i < N; ++i)
promises.push(pages[i].screenshot({ clip: { x: 50 * i, y: 0, width: 50, height: 50 } }));
const screenshots = await Promise.all(promises);
for (let i = 0; i < N; ++i)
expect(screenshots[i]).toBeGolden(`grid-cell-${i}.png`);
await Promise.all(pages.map(page => page.close()));
});
it.skip(FFOX)('should allow transparency', async({page, server}) => {
await page.setViewport({ width: 50, height: 150 });
await page.setContent(`
<style>
body { margin: 0 }
div { width: 50px; height: 50px; }
</style>
<div style="background:black"></div>
<div style="background:white"></div>
<div style="background:transparent"></div>
`);
const screenshot = await page.screenshot({omitBackground: true});
expect(screenshot).toBeGolden('transparent.png');
});
it('should render white background on jpeg file', async({page, server}) => {
await page.setViewport({ width: 100, height: 100 });
await page.goto(server.EMPTY_PAGE);
const screenshot = await page.screenshot({omitBackground: true, type: 'jpeg'});
expect(screenshot).toBeGolden('white.jpg');
});
it('should work with odd clip size on Retina displays', async({page, server}) => {
const screenshot = await page.screenshot({
clip: {
x: 0,
y: 0,
width: 11,
height: 11,
}
});
expect(screenshot).toBeGolden('screenshot-clip-odd-size.png');
});
it('should return base64', async({page, server}) => {
await page.setViewport({width: 500, height: 500});
await page.goto(server.PREFIX + '/grid.html');
const screenshot = await page.screenshot({
encoding: 'base64'
});
expect(Buffer.from(screenshot, 'base64')).toBeGolden('screenshot-sanity.png');
});
it.skip(WEBKIT || FFOX)('should work with a mobile viewport', async({page, server}) => {
await page.setViewport({
width: 320,
height: 480,
isMobile: true
});
await page.goto(server.PREFIX + '/grid.html');
const screenshot = await page.screenshot();
expect(screenshot).toBeGolden('screenshot-mobile.png');
});
});
describe('ElementHandle.screenshot', function() {
it('should work', async({page, server}) => {
await page.setViewport({width: 500, height: 500});
await page.goto(server.PREFIX + '/grid.html');
await page.evaluate(() => window.scrollBy(50, 100));
const elementHandle = await page.$('.box:nth-of-type(3)');
const screenshot = await elementHandle.screenshot();
expect(screenshot).toBeGolden('screenshot-element-bounding-box.png');
});
it('should take into account padding and border', async({page, server}) => {
await page.setViewport({width: 500, height: 500});
await page.setContent(`
<div style="height: 14px">oooo</div>
<style>div {
border: 2px solid blue;
background: green;
width: 50px;
height: 50px;
}
</style>
<div id="d"></div>
`);
const elementHandle = await page.$('div#d');
const screenshot = await elementHandle.screenshot();
expect(screenshot).toBeGolden('screenshot-element-padding-border.png');
});
it('should capture full element when larger than viewport in parallel', async({page, server}) => {
await page.setViewport({width: 500, height: 500});
await page.setContent(`
<div style="height: 14px">oooo</div>
<style>
div.to-screenshot {
border: 1px solid blue;
width: 600px;
height: 600px;
margin-left: 50px;
}
::-webkit-scrollbar{
display: none;
}
</style>
<div class="to-screenshot"></div>
<div class="to-screenshot"></div>
<div class="to-screenshot"></div>
`);
const elementHandles = await page.$$('div.to-screenshot');
const promises = elementHandles.map(handle => handle.screenshot());
const screenshots = await Promise.all(promises);
expect(screenshots[2]).toBeGolden('screenshot-element-larger-than-viewport.png');
expect(await page.evaluate(() => ({ w: window.innerWidth, h: window.innerHeight }))).toEqual({ w: 500, h: 500 });
});
// Fails on GTK due to async setViewport.
it('should capture full element when larger than viewport', async({page, server}) => {
await page.setViewport({width: 500, height: 500});
await page.setContent(`
<div style="height: 14px">oooo</div>
<style>
div.to-screenshot {
border: 1px solid blue;
width: 600px;
height: 600px;
margin-left: 50px;
}
::-webkit-scrollbar{
display: none;
}
</style>
<div class="to-screenshot"></div>
<div class="to-screenshot"></div>
<div class="to-screenshot"></div>
`);
const elementHandle = await page.$('div.to-screenshot');
const screenshot = await elementHandle.screenshot();
expect(screenshot).toBeGolden('screenshot-element-larger-than-viewport.png');
expect(await page.evaluate(() => ({ w: window.innerWidth, h: window.innerHeight }))).toEqual({ w: 500, h: 500 });
});
it('should scroll element into view', async({page, server}) => {
await page.setViewport({width: 500, height: 500});
await page.setContent(`
<div style="height: 14px">oooo</div>
<style>div.above {
border: 2px solid blue;
background: red;
height: 1500px;
}
div.to-screenshot {
border: 2px solid blue;
background: green;
width: 50px;
height: 50px;
}
</style>
<div class="above"></div>
<div class="to-screenshot"></div>
`);
const elementHandle = await page.$('div.to-screenshot');
const screenshot = await elementHandle.screenshot();
expect(screenshot).toBeGolden('screenshot-element-scrolled-into-view.png');
});
it('should work with a rotated element', async({page, server}) => {
await page.setViewport({width: 500, height: 500});
await page.setContent(`<div style="position:absolute;
top: 100px;
left: 100px;
width: 100px;
height: 100px;
background: green;
transform: rotateZ(200deg);"> </div>`);
const elementHandle = await page.$('div');
const screenshot = await elementHandle.screenshot();
expect(screenshot).toBeGolden('screenshot-element-rotate.png');
});
it('should fail to screenshot a detached element', async({page, server}) => {
await page.setContent('<h1>remove this</h1>');
const elementHandle = await page.$('h1');
await page.evaluate(element => element.remove(), elementHandle);
const screenshotError = await elementHandle.screenshot().catch(error => error);
expect(screenshotError.message).toBe('Node is either not visible or not an HTMLElement');
});
it('should not hang with zero width/height element', async({page, server}) => {
await page.setContent('<div style="width: 50px; height: 0"></div>');
const div = await page.$('div');
const error = await div.screenshot().catch(e => e);
expect(error.message).toBe('Node has 0 height.');
});
it('should work for an element with fractional dimensions', async({page}) => {
await page.setContent('<div style="width:48.51px;height:19.8px;border:1px solid black;"></div>');
const elementHandle = await page.$('div');
const screenshot = await elementHandle.screenshot();
expect(screenshot).toBeGolden('screenshot-element-fractional.png');
});
it('should work for an element with an offset', async({page}) => {
await page.setContent('<div style="position:absolute; top: 10.3px; left: 20.4px;width:50.3px;height:20.2px;border:1px solid black;"></div>');
const elementHandle = await page.$('div');
const screenshot = await elementHandle.screenshot();
expect(screenshot).toBeGolden('screenshot-element-fractional-offset.png');
});
});
};
| test/screenshot.spec.js | 1 | https://github.com/microsoft/playwright/commit/310d4b193b4a7d3944af95424e44e4293392db24 | [
0.02879444509744644,
0.0026103181298822165,
0.00016834876441862434,
0.0008605389157310128,
0.005435431841760874
] |
{
"id": 4,
"code_window": [
" const page = await newPage({ userAgent: 'foobar' });\n",
" const [request] = await Promise.all([\n",
" server.waitForRequest('/empty.html'),\n",
" page.goto(server.EMPTY_PAGE),\n",
" ]);\n",
" expect(request.headers['user-agent']).toBe('foobar'); \n",
" }\n",
" });\n",
" it('should work for subframes', async({newPage, server}) => {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" expect(request.headers['user-agent']).toBe('foobar');\n"
],
"file_path": "test/browsercontext.spec.js",
"type": "replace",
"edit_start_line_idx": 127
} | /**
* Copyright 2017 Google Inc. All rights reserved.
* Modifications copyright (c) Microsoft Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { CRSession } from '../crConnection';
import { assert, debugError, helper, RegisteredListener } from '../../helper';
import { Protocol } from '../protocol';
import { EVALUATION_SCRIPT_URL } from '../crExecutionContext';
type CoverageEntry = {
url: string,
text: string,
ranges : {start: number, end: number}[]
};
export class CRCoverage {
private _jsCoverage: JSCoverage;
private _cssCoverage: CSSCoverage;
constructor(client: CRSession) {
this._jsCoverage = new JSCoverage(client);
this._cssCoverage = new CSSCoverage(client);
}
async startJSCoverage(options: {
resetOnNavigation?: boolean;
reportAnonymousScripts?: boolean;
}) {
return await this._jsCoverage.start(options);
}
async stopJSCoverage(): Promise<CoverageEntry[]> {
return await this._jsCoverage.stop();
}
async startCSSCoverage(options: { resetOnNavigation?: boolean; } = {}) {
return await this._cssCoverage.start(options);
}
async stopCSSCoverage(): Promise<CoverageEntry[]> {
return await this._cssCoverage.stop();
}
}
class JSCoverage {
_client: CRSession;
_enabled: boolean;
_scriptURLs: Map<string, string>;
_scriptSources: Map<string, string>;
_eventListeners: RegisteredListener[];
_resetOnNavigation: boolean;
_reportAnonymousScripts: boolean;
constructor(client: CRSession) {
this._client = client;
this._enabled = false;
this._scriptURLs = new Map();
this._scriptSources = new Map();
this._eventListeners = [];
this._resetOnNavigation = false;
}
async start(options: {
resetOnNavigation?: boolean;
reportAnonymousScripts?: boolean;
} = {}) {
assert(!this._enabled, 'JSCoverage is already enabled');
const {
resetOnNavigation = true,
reportAnonymousScripts = false
} = options;
this._resetOnNavigation = resetOnNavigation;
this._reportAnonymousScripts = reportAnonymousScripts;
this._enabled = true;
this._scriptURLs.clear();
this._scriptSources.clear();
this._eventListeners = [
helper.addEventListener(this._client, 'Debugger.scriptParsed', this._onScriptParsed.bind(this)),
helper.addEventListener(this._client, 'Runtime.executionContextsCleared', this._onExecutionContextsCleared.bind(this)),
];
this._client.on('Debugger.paused', () => this._client.send('Debugger.resume'));
await Promise.all([
this._client.send('Profiler.enable'),
this._client.send('Profiler.startPreciseCoverage', {callCount: false, detailed: true}),
this._client.send('Debugger.enable'),
this._client.send('Debugger.setSkipAllPauses', {skip: true})
]);
}
_onExecutionContextsCleared() {
if (!this._resetOnNavigation)
return;
this._scriptURLs.clear();
this._scriptSources.clear();
}
async _onScriptParsed(event: Protocol.Debugger.scriptParsedPayload) {
// Ignore playwright-injected scripts
if (event.url === EVALUATION_SCRIPT_URL)
return;
// Ignore other anonymous scripts unless the reportAnonymousScripts option is true.
if (!event.url && !this._reportAnonymousScripts)
return;
try {
const response = await this._client.send('Debugger.getScriptSource', {scriptId: event.scriptId});
this._scriptURLs.set(event.scriptId, event.url);
this._scriptSources.set(event.scriptId, response.scriptSource);
} catch (e) {
// This might happen if the page has already navigated away.
debugError(e);
}
}
async stop(): Promise<CoverageEntry[]> {
assert(this._enabled, 'JSCoverage is not enabled');
this._enabled = false;
const [profileResponse] = await Promise.all([
this._client.send('Profiler.takePreciseCoverage'),
this._client.send('Profiler.stopPreciseCoverage'),
this._client.send('Profiler.disable'),
this._client.send('Debugger.disable'),
]);
helper.removeEventListeners(this._eventListeners);
const coverage = [];
for (const entry of profileResponse.result) {
let url = this._scriptURLs.get(entry.scriptId);
if (!url && this._reportAnonymousScripts)
url = 'debugger://VM' + entry.scriptId;
const text = this._scriptSources.get(entry.scriptId);
if (text === undefined || url === undefined)
continue;
const flattenRanges = [];
for (const func of entry.functions)
flattenRanges.push(...func.ranges);
const ranges = convertToDisjointRanges(flattenRanges);
coverage.push({url, ranges, text});
}
return coverage;
}
}
class CSSCoverage {
_client: CRSession;
_enabled: boolean;
_stylesheetURLs: Map<string, string>;
_stylesheetSources: Map<string, string>;
_eventListeners: RegisteredListener[];
_resetOnNavigation: boolean;
constructor(client: CRSession) {
this._client = client;
this._enabled = false;
this._stylesheetURLs = new Map();
this._stylesheetSources = new Map();
this._eventListeners = [];
this._resetOnNavigation = false;
}
async start(options: { resetOnNavigation?: boolean; } = {}) {
assert(!this._enabled, 'CSSCoverage is already enabled');
const {resetOnNavigation = true} = options;
this._resetOnNavigation = resetOnNavigation;
this._enabled = true;
this._stylesheetURLs.clear();
this._stylesheetSources.clear();
this._eventListeners = [
helper.addEventListener(this._client, 'CSS.styleSheetAdded', this._onStyleSheet.bind(this)),
helper.addEventListener(this._client, 'Runtime.executionContextsCleared', this._onExecutionContextsCleared.bind(this)),
];
await Promise.all([
this._client.send('DOM.enable'),
this._client.send('CSS.enable'),
this._client.send('CSS.startRuleUsageTracking'),
]);
}
_onExecutionContextsCleared() {
if (!this._resetOnNavigation)
return;
this._stylesheetURLs.clear();
this._stylesheetSources.clear();
}
async _onStyleSheet(event: Protocol.CSS.styleSheetAddedPayload) {
const header = event.header;
// Ignore anonymous scripts
if (!header.sourceURL)
return;
try {
const response = await this._client.send('CSS.getStyleSheetText', {styleSheetId: header.styleSheetId});
this._stylesheetURLs.set(header.styleSheetId, header.sourceURL);
this._stylesheetSources.set(header.styleSheetId, response.text);
} catch (e) {
// This might happen if the page has already navigated away.
debugError(e);
}
}
async stop(): Promise<CoverageEntry[]> {
assert(this._enabled, 'CSSCoverage is not enabled');
this._enabled = false;
const ruleTrackingResponse = await this._client.send('CSS.stopRuleUsageTracking');
await Promise.all([
this._client.send('CSS.disable'),
this._client.send('DOM.disable'),
]);
helper.removeEventListeners(this._eventListeners);
// aggregate by styleSheetId
const styleSheetIdToCoverage = new Map();
for (const entry of ruleTrackingResponse.ruleUsage) {
let ranges = styleSheetIdToCoverage.get(entry.styleSheetId);
if (!ranges) {
ranges = [];
styleSheetIdToCoverage.set(entry.styleSheetId, ranges);
}
ranges.push({
startOffset: entry.startOffset,
endOffset: entry.endOffset,
count: entry.used ? 1 : 0,
});
}
const coverage = [];
for (const styleSheetId of this._stylesheetURLs.keys()) {
const url = this._stylesheetURLs.get(styleSheetId);
const text = this._stylesheetSources.get(styleSheetId);
const ranges = convertToDisjointRanges(styleSheetIdToCoverage.get(styleSheetId) || []);
coverage.push({url, ranges, text});
}
return coverage;
}
}
function convertToDisjointRanges(nestedRanges: {
startOffset: number;
endOffset: number;
count: number; }[]): { start: number; end: number; }[] {
const points = [];
for (const range of nestedRanges) {
points.push({ offset: range.startOffset, type: 0, range });
points.push({ offset: range.endOffset, type: 1, range });
}
// Sort points to form a valid parenthesis sequence.
points.sort((a, b) => {
// Sort with increasing offsets.
if (a.offset !== b.offset)
return a.offset - b.offset;
// All "end" points should go before "start" points.
if (a.type !== b.type)
return b.type - a.type;
const aLength = a.range.endOffset - a.range.startOffset;
const bLength = b.range.endOffset - b.range.startOffset;
// For two "start" points, the one with longer range goes first.
if (a.type === 0)
return bLength - aLength;
// For two "end" points, the one with shorter range goes first.
return aLength - bLength;
});
const hitCountStack = [];
const results = [];
let lastOffset = 0;
// Run scanning line to intersect all ranges.
for (const point of points) {
if (hitCountStack.length && lastOffset < point.offset && hitCountStack[hitCountStack.length - 1] > 0) {
const lastResult = results.length ? results[results.length - 1] : null;
if (lastResult && lastResult.end === lastOffset)
lastResult.end = point.offset;
else
results.push({start: lastOffset, end: point.offset});
}
lastOffset = point.offset;
if (point.type === 0)
hitCountStack.push(point.range.count);
else
hitCountStack.pop();
}
// Filter out empty ranges.
return results.filter(range => range.end - range.start > 1);
}
| src/chromium/features/crCoverage.ts | 0 | https://github.com/microsoft/playwright/commit/310d4b193b4a7d3944af95424e44e4293392db24 | [
0.00017758639296516776,
0.00017181321163661778,
0.00016287161270156503,
0.00017253906116820872,
0.000003576158405849128
] |
{
"id": 4,
"code_window": [
" const page = await newPage({ userAgent: 'foobar' });\n",
" const [request] = await Promise.all([\n",
" server.waitForRequest('/empty.html'),\n",
" page.goto(server.EMPTY_PAGE),\n",
" ]);\n",
" expect(request.headers['user-agent']).toBe('foobar'); \n",
" }\n",
" });\n",
" it('should work for subframes', async({newPage, server}) => {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" expect(request.headers['user-agent']).toBe('foobar');\n"
],
"file_path": "test/browsercontext.spec.js",
"type": "replace",
"edit_start_line_idx": 127
} | /**
* 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 { WKTargetSession, isSwappedOutError } from './wkConnection';
import { helper } from '../helper';
import { valueFromRemoteObject, releaseObject } from './wkProtocolHelper';
import { Protocol } from './protocol';
import * as js from '../javascript';
export const EVALUATION_SCRIPT_URL = '__playwright_evaluation_script__';
const SOURCE_URL_REGEX = /^[\040\t]*\/\/[@#] sourceURL=\s*(\S*?)\s*$/m;
export class WKExecutionContext implements js.ExecutionContextDelegate {
private _globalObjectId?: Promise<string>;
_session: WKTargetSession;
_contextId: number;
private _contextDestroyedCallback: () => void;
private _executionContextDestroyedPromise: Promise<unknown>;
_jsonStringifyObjectId: Protocol.Runtime.RemoteObjectId | undefined;
constructor(client: WKTargetSession, contextPayload: Protocol.Runtime.ExecutionContextDescription) {
this._session = client;
this._contextId = contextPayload.id;
this._contextDestroyedCallback = null;
this._executionContextDestroyedPromise = new Promise((resolve, reject) => {
this._contextDestroyedCallback = resolve;
});
}
_dispose() {
this._contextDestroyedCallback();
}
async evaluate(context: js.ExecutionContext, returnByValue: boolean, pageFunction: Function | string, ...args: any[]): Promise<any> {
if (helper.isString(pageFunction)) {
const contextId = this._contextId;
const expression: string = pageFunction as string;
const expressionWithSourceUrl = SOURCE_URL_REGEX.test(expression) ? expression : expression + '\n' + suffix;
return this._session.send('Runtime.evaluate', {
expression: expressionWithSourceUrl,
contextId,
returnByValue: false,
emulateUserGesture: true
}).then(response => {
if (response.result.type === 'object' && response.result.className === 'Promise') {
return Promise.race([
this._executionContextDestroyedPromise.then(() => contextDestroyedResult),
this._awaitPromise(response.result.objectId),
]);
}
return response;
}).then(response => {
if (response.wasThrown)
throw new Error('Evaluation failed: ' + response.result.description);
if (!returnByValue)
return context._createHandle(response.result);
if (response.result.objectId)
return this._returnObjectByValue(response.result.objectId);
return valueFromRemoteObject(response.result);
}).catch(rewriteError);
}
if (typeof pageFunction !== 'function')
throw new Error(`Expected to get |string| or |function| as the first argument, but got "${pageFunction}" instead.`);
let functionText = pageFunction.toString();
try {
new Function('(' + functionText + ')');
} catch (e1) {
// This means we might have a function shorthand. Try another
// time prefixing 'function '.
if (functionText.startsWith('async '))
functionText = 'async function ' + functionText.substring('async '.length);
else
functionText = 'function ' + functionText;
try {
new Function('(' + functionText + ')');
} catch (e2) {
// We tried hard to serialize, but there's a weird beast here.
throw new Error('Passed function is not well-serializable!');
}
}
let serializableArgs;
if (args.some(isUnserializable)) {
serializableArgs = [];
const paramStrings = [];
for (const arg of args) {
if (isUnserializable(arg)) {
paramStrings.push(unserializableToString(arg));
} else {
paramStrings.push('arguments[' + serializableArgs.length + ']');
serializableArgs.push(arg);
}
}
functionText = `() => (${functionText})(${paramStrings.join(',')})`;
} else {
serializableArgs = args;
}
const thisObjectId = await this._contextGlobalObjectId();
let callFunctionOnPromise;
try {
callFunctionOnPromise = this._session.send('Runtime.callFunctionOn', {
functionDeclaration: functionText + '\n' + suffix + '\n',
objectId: thisObjectId,
arguments: serializableArgs.map((arg: any) => this._convertArgument(arg)),
returnByValue: false,
emulateUserGesture: true
});
} catch (err) {
if (err instanceof TypeError && err.message.startsWith('Converting circular structure to JSON'))
err.message += ' Are you passing a nested JSHandle?';
throw err;
}
return callFunctionOnPromise.then(response => {
if (response.result.type === 'object' && response.result.className === 'Promise') {
return Promise.race([
this._executionContextDestroyedPromise.then(() => contextDestroyedResult),
this._awaitPromise(response.result.objectId),
]);
}
return response;
}).then(response => {
if (response.wasThrown)
throw new Error('Evaluation failed: ' + response.result.description);
if (!returnByValue)
return context._createHandle(response.result);
if (response.result.objectId)
return this._returnObjectByValue(response.result.objectId);
return valueFromRemoteObject(response.result);
}).catch(rewriteError);
function unserializableToString(arg: any) {
if (Object.is(arg, -0))
return '-0';
if (Object.is(arg, Infinity))
return 'Infinity';
if (Object.is(arg, -Infinity))
return '-Infinity';
if (Object.is(arg, NaN))
return 'NaN';
if (arg instanceof js.JSHandle) {
const remoteObj = toRemoteObject(arg);
if (!remoteObj.objectId)
return valueFromRemoteObject(remoteObj);
}
throw new Error('Unsupported value: ' + arg + ' (' + (typeof arg) + ')');
}
function isUnserializable(arg: any) {
if (typeof arg === 'bigint')
return true;
if (Object.is(arg, -0))
return true;
if (Object.is(arg, Infinity))
return true;
if (Object.is(arg, -Infinity))
return true;
if (Object.is(arg, NaN))
return true;
if (arg instanceof js.JSHandle) {
const remoteObj = toRemoteObject(arg);
if (!remoteObj.objectId)
return !Object.is(valueFromRemoteObject(remoteObj), remoteObj.value);
}
return false;
}
function rewriteError(error: Error): Protocol.Runtime.evaluateReturnValue {
if (error.message.includes('Object couldn\'t be returned by value'))
return {result: {type: 'undefined'}};
if (error.message.includes('Missing injected script for given'))
throw new Error('Execution context was destroyed, most likely because of a navigation.');
throw error;
}
}
private _contextGlobalObjectId() {
if (!this._globalObjectId) {
this._globalObjectId = this._session.send('Runtime.evaluate', {
expression: 'this',
contextId: this._contextId
}).catch(e => {
if (isSwappedOutError(e))
throw new Error('Execution context was destroyed, most likely because of a navigation.');
throw e;
}).then(response => {
return response.result.objectId;
});
}
return this._globalObjectId;
}
private _awaitPromise(objectId: Protocol.Runtime.RemoteObjectId) {
return this._session.send('Runtime.awaitPromise', {
promiseObjectId: objectId,
returnByValue: false
}).catch(e => {
if (isSwappedOutError(e))
return contextDestroyedResult;
throw e;
});
}
private _returnObjectByValue(objectId: Protocol.Runtime.RemoteObjectId) {
const serializeFunction = function(stringify: (o: any) => string) {
try {
return stringify(this);
} catch (e) {
if (e instanceof TypeError)
return void 0;
throw e;
}
};
return this._session.send('Runtime.callFunctionOn', {
// Serialize object using standard JSON implementation to correctly pass 'undefined'.
functionDeclaration: serializeFunction + '\n' + suffix + '\n',
objectId: objectId,
arguments: [ { objectId: this._jsonStringifyObjectId } ],
returnByValue: true
}).catch(e => {
if (isSwappedOutError(e))
return contextDestroyedResult;
throw e;
}).then(serializeResponse => {
if (serializeResponse.wasThrown)
throw new Error('Serialization failed: ' + serializeResponse.result.description);
// This is the case of too long property chain, not serializable to json string.
if (serializeResponse.result.type === 'undefined')
return undefined;
if (serializeResponse.result.type !== 'string')
throw new Error('Unexpected result of JSON.stringify: ' + JSON.stringify(serializeResponse, null, 2));
return JSON.parse(serializeResponse.result.value);
});
}
async getProperties(handle: js.JSHandle): Promise<Map<string, js.JSHandle>> {
const response = await this._session.send('Runtime.getProperties', {
objectId: toRemoteObject(handle).objectId,
ownProperties: true
});
const result = new Map();
for (const property of response.properties) {
if (!property.enumerable)
continue;
result.set(property.name, handle._context._createHandle(property.value));
}
return result;
}
async releaseHandle(handle: js.JSHandle): Promise<void> {
await releaseObject(this._session, toRemoteObject(handle));
}
async handleJSONValue<T>(handle: js.JSHandle<T>): Promise<T> {
const remoteObject = toRemoteObject(handle);
if (remoteObject.objectId) {
const response = await this._session.send('Runtime.callFunctionOn', {
functionDeclaration: 'function() { return this; }',
objectId: remoteObject.objectId,
returnByValue: true
});
return valueFromRemoteObject(response.result);
}
return valueFromRemoteObject(remoteObject);
}
handleToString(handle: js.JSHandle, includeType: boolean): string {
const object = toRemoteObject(handle);
if (object.objectId) {
let type: string = object.subtype || object.type;
// FIXME: promise doesn't have special subtype in WebKit.
if (object.className === 'Promise')
type = 'promise';
return 'JSHandle@' + type;
}
return (includeType ? 'JSHandle:' : '') + valueFromRemoteObject(object);
}
private _convertArgument(arg: js.JSHandle | any) : Protocol.Runtime.CallArgument {
const objectHandle = arg && (arg instanceof js.JSHandle) ? arg : null;
if (objectHandle) {
if (objectHandle._context._delegate !== this)
throw new Error('JSHandles can be evaluated only in the context they were created!');
if (objectHandle._disposed)
throw new Error('JSHandle is disposed!');
const remoteObject = toRemoteObject(arg);
if (!remoteObject.objectId)
return { value: valueFromRemoteObject(remoteObject) };
return { objectId: remoteObject.objectId };
}
return { value: arg };
}
}
const suffix = `//# sourceURL=${EVALUATION_SCRIPT_URL}`;
const contextDestroyedResult = {
wasThrown: true,
result: {
description: 'Protocol error: Execution context was destroyed, most likely because of a navigation.'
} as Protocol.Runtime.RemoteObject
};
function toRemoteObject(handle: js.JSHandle): Protocol.Runtime.RemoteObject {
return handle._remoteObject as Protocol.Runtime.RemoteObject;
}
| src/webkit/wkExecutionContext.ts | 0 | https://github.com/microsoft/playwright/commit/310d4b193b4a7d3944af95424e44e4293392db24 | [
0.0001887231192085892,
0.00017308547103311867,
0.00016528468404430896,
0.00017288087110500783,
0.0000036322219330031658
] |
{
"id": 4,
"code_window": [
" const page = await newPage({ userAgent: 'foobar' });\n",
" const [request] = await Promise.all([\n",
" server.waitForRequest('/empty.html'),\n",
" page.goto(server.EMPTY_PAGE),\n",
" ]);\n",
" expect(request.headers['user-agent']).toBe('foobar'); \n",
" }\n",
" });\n",
" it('should work for subframes', async({newPage, server}) => {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" expect(request.headers['user-agent']).toBe('foobar');\n"
],
"file_path": "test/browsercontext.spec.js",
"type": "replace",
"edit_start_line_idx": 127
} | // Mock script for background extension
window.MAGIC = 42;
| test/assets/simple-extension/index.js | 0 | https://github.com/microsoft/playwright/commit/310d4b193b4a7d3944af95424e44e4293392db24 | [
0.0001697860861895606,
0.0001697860861895606,
0.0001697860861895606,
0.0001697860861895606,
0
] |
{
"id": 5,
"code_window": [
" const [request] = await Promise.all([\n",
" server.waitForRequest('/empty.html'),\n",
" utils.attachFrame(page, 'frame1', server.EMPTY_PAGE),\n",
" ]);\n",
" expect(request.headers['user-agent']).toBe('foobar'); \n",
" }\n",
" });\n",
" it('should emulate device user-agent', async({newPage, server}) => {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" expect(request.headers['user-agent']).toBe('foobar');\n"
],
"file_path": "test/browsercontext.spec.js",
"type": "replace",
"edit_start_line_idx": 141
} | /**
* Copyright 2018 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.
*/
const utils = require('./utils');
module.exports.describe = function({testRunner, expect, playwright, CHROME, WEBKIT}) {
const {describe, xdescribe, fdescribe} = testRunner;
const {it, fit, xit, dit} = testRunner;
const {beforeAll, beforeEach, afterAll, afterEach} = testRunner;
describe('BrowserContext', function() {
it('should have default context', async function({browser, server}) {
expect(browser.browserContexts().length).toBe(1);
const defaultContext = browser.browserContexts()[0];
let error = null;
await defaultContext.close().catch(e => error = e);
expect(browser.defaultContext()).toBe(defaultContext);
expect(error.message).toContain('cannot be closed');
});
it('should create new incognito context', async function({browser, newContext}) {
expect(browser.browserContexts().length).toBe(1);
const context = await newContext();
expect(browser.browserContexts().length).toBe(2);
expect(browser.browserContexts().indexOf(context) !== -1).toBe(true);
await context.close();
expect(browser.browserContexts().length).toBe(1);
});
it('window.open should use parent tab context', async function({newContext, server}) {
const context = await newContext();
const page = await context.newPage();
await page.goto(server.EMPTY_PAGE);
const [popupTarget] = await Promise.all([
utils.waitEvent(page, 'popup'),
page.evaluate(url => window.open(url), server.EMPTY_PAGE)
]);
expect(popupTarget.browserContext()).toBe(context);
});
it('should isolate localStorage and cookies', async function({browser, newContext, server}) {
// Create two incognito contexts.
const context1 = await newContext();
const context2 = await newContext();
expect((await context1.pages()).length).toBe(0);
expect((await context2.pages()).length).toBe(0);
// Create a page in first incognito context.
const page1 = await context1.newPage();
await page1.goto(server.EMPTY_PAGE);
await page1.evaluate(() => {
localStorage.setItem('name', 'page1');
document.cookie = 'name=page1';
});
expect((await context1.pages()).length).toBe(1);
expect((await context2.pages()).length).toBe(0);
// Create a page in second incognito context.
const page2 = await context2.newPage();
await page2.goto(server.EMPTY_PAGE);
await page2.evaluate(() => {
localStorage.setItem('name', 'page2');
document.cookie = 'name=page2';
});
expect((await context1.pages()).length).toBe(1);
expect((await context2.pages()).length).toBe(1);
expect((await context1.pages())[0]).toBe(page1);
expect((await context2.pages())[0]).toBe(page2);
// Make sure pages don't share localstorage or cookies.
expect(await page1.evaluate(() => localStorage.getItem('name'))).toBe('page1');
expect(await page1.evaluate(() => document.cookie)).toBe('name=page1');
expect(await page2.evaluate(() => localStorage.getItem('name'))).toBe('page2');
expect(await page2.evaluate(() => document.cookie)).toBe('name=page2');
// Cleanup contexts.
await Promise.all([
context1.close(),
context2.close()
]);
expect(browser.browserContexts().length).toBe(1);
});
it('should set the default viewport', async({ newPage }) => {
const page = await newPage({ viewport: { width: 456, height: 789 } });
expect(await page.evaluate('window.innerWidth')).toBe(456);
expect(await page.evaluate('window.innerHeight')).toBe(789);
});
it('should take fullPage screenshots when default viewport is null', async({server, newPage}) => {
const page = await newPage({ viewport: null });
await page.goto(server.PREFIX + '/grid.html');
const sizeBefore = await page.evaluate(() => ({ width: document.body.offsetWidth, height: document.body.offsetHeight }));
const screenshot = await page.screenshot({
fullPage: true
});
expect(screenshot).toBeInstanceOf(Buffer);
const sizeAfter = await page.evaluate(() => ({ width: document.body.offsetWidth, height: document.body.offsetHeight }));
expect(sizeBefore.width).toBe(sizeAfter.width);
expect(sizeBefore.height).toBe(sizeAfter.height);
});
});
describe('BrowserContext({setUserAgent})', function() {
it('should work', async({newPage, server}) => {
{
const page = await newPage();
expect(await page.evaluate(() => navigator.userAgent)).toContain('Mozilla');
}
{
const page = await newPage({ userAgent: 'foobar' });
const [request] = await Promise.all([
server.waitForRequest('/empty.html'),
page.goto(server.EMPTY_PAGE),
]);
expect(request.headers['user-agent']).toBe('foobar');
}
});
it('should work for subframes', async({newPage, server}) => {
{
const page = await newPage();
expect(await page.evaluate(() => navigator.userAgent)).toContain('Mozilla');
}
{
const page = await newPage({ userAgent: 'foobar' });
const [request] = await Promise.all([
server.waitForRequest('/empty.html'),
utils.attachFrame(page, 'frame1', server.EMPTY_PAGE),
]);
expect(request.headers['user-agent']).toBe('foobar');
}
});
it('should emulate device user-agent', async({newPage, server}) => {
{
const page = await newPage();
await page.goto(server.PREFIX + '/mobile.html');
expect(await page.evaluate(() => navigator.userAgent)).not.toContain('iPhone');
}
{
const page = await newPage({ userAgent: playwright.devices['iPhone 6'].userAgent });
await page.goto(server.PREFIX + '/mobile.html');
expect(await page.evaluate(() => navigator.userAgent)).toContain('iPhone');
}
});
});
describe('BrowserContext({bypassCSP})', function() {
it('should bypass CSP meta tag', async({newPage, server}) => {
// Make sure CSP prohibits addScriptTag.
{
const page = await newPage();
await page.goto(server.PREFIX + '/csp.html');
await page.addScriptTag({content: 'window.__injected = 42;'}).catch(e => void e);
expect(await page.evaluate(() => window.__injected)).toBe(undefined);
}
// By-pass CSP and try one more time.
{
const page = await newPage({ bypassCSP: true });
await page.goto(server.PREFIX + '/csp.html');
await page.addScriptTag({content: 'window.__injected = 42;'});
expect(await page.evaluate(() => window.__injected)).toBe(42);
}
});
it('should bypass CSP header', async({newPage, server}) => {
// Make sure CSP prohibits addScriptTag.
server.setCSP('/empty.html', 'default-src "self"');
{
const page = await newPage();
await page.goto(server.EMPTY_PAGE);
await page.addScriptTag({content: 'window.__injected = 42;'}).catch(e => void e);
expect(await page.evaluate(() => window.__injected)).toBe(undefined);
}
// By-pass CSP and try one more time.
{
const page = await newPage({ bypassCSP: true });
await page.goto(server.EMPTY_PAGE);
await page.addScriptTag({content: 'window.__injected = 42;'});
expect(await page.evaluate(() => window.__injected)).toBe(42);
}
});
it('should bypass after cross-process navigation', async({newPage, server}) => {
const page = await newPage({ bypassCSP: true });
await page.goto(server.PREFIX + '/csp.html');
await page.addScriptTag({content: 'window.__injected = 42;'});
expect(await page.evaluate(() => window.__injected)).toBe(42);
await page.goto(server.CROSS_PROCESS_PREFIX + '/csp.html');
await page.addScriptTag({content: 'window.__injected = 42;'});
expect(await page.evaluate(() => window.__injected)).toBe(42);
});
it('should bypass CSP in iframes as well', async({newPage, server}) => {
// Make sure CSP prohibits addScriptTag in an iframe.
{
const page = await newPage();
await page.goto(server.EMPTY_PAGE);
const frame = await utils.attachFrame(page, 'frame1', server.PREFIX + '/csp.html');
await frame.addScriptTag({content: 'window.__injected = 42;'}).catch(e => void e);
expect(await frame.evaluate(() => window.__injected)).toBe(undefined);
}
// By-pass CSP and try one more time.
{
const page = await newPage({ bypassCSP: true });
await page.goto(server.EMPTY_PAGE);
const frame = await utils.attachFrame(page, 'frame1', server.PREFIX + '/csp.html');
await frame.addScriptTag({content: 'window.__injected = 42;'}).catch(e => void e);
expect(await frame.evaluate(() => window.__injected)).toBe(42);
}
});
});
describe('BrowserContext({javaScriptEnabled})', function() {
it('should work', async({newPage}) => {
{
const page = await newPage({ javaScriptEnabled: false });
await page.goto('data:text/html, <script>var something = "forbidden"</script>');
let error = null;
await page.evaluate('something').catch(e => error = e);
if (WEBKIT)
expect(error.message).toContain('Can\'t find variable: something');
else
expect(error.message).toContain('something is not defined');
}
{
const page = await newPage();
await page.goto('data:text/html, <script>var something = "forbidden"</script>');
expect(await page.evaluate('something')).toBe('forbidden');
}
});
it('should be able to navigate after disabling javascript', async({newPage, server}) => {
const page = await newPage({ javaScriptEnabled: false });
await page.goto(server.EMPTY_PAGE);
});
});
};
| test/browsercontext.spec.js | 1 | https://github.com/microsoft/playwright/commit/310d4b193b4a7d3944af95424e44e4293392db24 | [
0.997768759727478,
0.11927581578493118,
0.0001657145330682397,
0.002537431661039591,
0.3164477050304413
] |
{
"id": 5,
"code_window": [
" const [request] = await Promise.all([\n",
" server.waitForRequest('/empty.html'),\n",
" utils.attachFrame(page, 'frame1', server.EMPTY_PAGE),\n",
" ]);\n",
" expect(request.headers['user-agent']).toBe('foobar'); \n",
" }\n",
" });\n",
" it('should emulate device user-agent', async({newPage, server}) => {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" expect(request.headers['user-agent']).toBe('foobar');\n"
],
"file_path": "test/browsercontext.spec.js",
"type": "replace",
"edit_start_line_idx": 141
} | #!/bin/bash
set -e
set +x
trap "cd $(pwd -P)" EXIT
cd "$(dirname "$0")"
REMOTE_BROWSER_UPSTREAM="browser_upstream"
BUILD_BRANCH="playwright-build"
if [[ ($1 == '--help') || ($1 == '-h') ]]; then
echo "usage: $(basename $0) [firefox|webkit] [custom_checkout_path]"
echo
echo "Prepares browser checkout. The checkout is a GIT repository that:"
echo "- has a '$REMOTE_BROWSER_UPSTREAM' remote pointing to a REMOTE_URL from UPSTREAM_CONFIG.sh"
echo "- has a '$BUILD_BRANCH' branch that is BASE_REVISION with all the patches applied."
echo
echo "You can optionally specify custom_checkout_path if you want to use some other browser checkout"
echo
exit 0
fi
if [[ $# == 0 ]]; then
echo "missing browser: 'firefox' or 'webkit'"
echo "try './$(basename $0) --help' for more information"
exit 1
fi
# FRIENDLY_CHECKOUT_PATH is used only for logging.
FRIENDLY_CHECKOUT_PATH="";
CHECKOUT_PATH=""
PATCHES_PATH=""
BUILD_NUMBER=""
if [[ ("$1" == "firefox") || ("$1" == "firefox/") ]]; then
FRIENDLY_CHECKOUT_PATH="//browser_patches/firefox/checkout";
CHECKOUT_PATH="$PWD/firefox/checkout"
PATCHES_PATH="$PWD/firefox/patches"
BUILD_NUMBER=$(cat "$PWD/firefox/BUILD_NUMBER")
source "./firefox/UPSTREAM_CONFIG.sh"
elif [[ ("$1" == "webkit") || ("$1" == "webkit/") ]]; then
FRIENDLY_CHECKOUT_PATH="//browser_patches/webkit/checkout";
CHECKOUT_PATH="$PWD/webkit/checkout"
PATCHES_PATH="$PWD/webkit/patches"
BUILD_NUMBER=$(cat "$PWD/webkit/BUILD_NUMBER")
source "./webkit/UPSTREAM_CONFIG.sh"
else
echo ERROR: unknown browser - "$1"
exit 1
fi
# we will use this just for beauty.
if [[ $# == 2 ]]; then
echo "WARNING: using custom checkout path $CHECKOUT_PATH"
CHECKOUT_PATH=$2
FRIENDLY_CHECKOUT_PATH="<custom_checkout('$2')>"
fi
# if there's no checkout folder - checkout one.
if ! [[ -d $CHECKOUT_PATH ]]; then
echo "-- $FRIENDLY_CHECKOUT_PATH is missing - checking out.."
git clone --single-branch --branch $BASE_BRANCH $REMOTE_URL $CHECKOUT_PATH
else
echo "-- checking $FRIENDLY_CHECKOUT_PATH folder - OK"
fi
# if folder exists but not a git repository - bail out.
if ! [[ -d $CHECKOUT_PATH/.git ]]; then
echo "ERROR: $FRIENDLY_CHECKOUT_PATH is not a git repository! Remove it and re-run the script."
exit 1
else
echo "-- checking $FRIENDLY_CHECKOUT_PATH is a git repo - OK"
fi
# ============== SETTING UP GIT REPOSITORY ==============
cd $CHECKOUT_PATH
# Bail out if git repo is dirty.
if [[ -n $(git status -s --untracked-files=no) ]]; then
echo "ERROR: $FRIENDLY_CHECKOUT_PATH has dirty GIT state - commit everything and re-run the script."
exit 1
fi
# Setting up |$REMOTE_BROWSER_UPSTREAM| remote and fetch the $BASE_BRANCH
if git remote get-url $REMOTE_BROWSER_UPSTREAM >/dev/null; then
echo "-- setting |$REMOTE_BROWSER_UPSTREAM| remote url to $REMOTE_URL"
git remote set-url $REMOTE_BROWSER_UPSTREAM $REMOTE_URL
else
echo "-- adding |$REMOTE_BROWSER_UPSTREAM| remote to $REMOTE_URL"
git remote add $REMOTE_BROWSER_UPSTREAM $REMOTE_URL
fi
# Check if we have the $BASE_REVISION commit in GIT
if ! git cat-file -e $BASE_REVISION^{commit}; then
# If not, fetch from REMOTE_BROWSER_UPSTREAM and check one more time.
git fetch $REMOTE_BROWSER_UPSTREAM $BASE_BRANCH
if ! git cat-file -e $BASE_REVISION^{commit}; then
echo "ERROR: $FRIENDLY_CHECKOUT_PATH/ does not include the BASE_REVISION (@$BASE_REVISION). Wrong revision number?"
exit 1
fi
fi
echo "-- checking $FRIENDLY_CHECKOUT_PATH repo has BASE_REVISION (@$BASE_REVISION) commit - OK"
# Check out the $BASE_REVISION
git checkout $BASE_REVISION
# Create a playwright-build branch and apply all the patches to it.
if git show-ref --verify --quiet refs/heads/playwright-build; then
git branch -D playwright-build
fi
git checkout -b playwright-build
echo "-- applying patches"
git apply --index $PATCHES_PATH/*
git commit -a --author="playwright-devops <[email protected]>" -m "chore: bootstrap build #$BUILD_NUMBER"
echo
echo
echo "DONE. Browser is ready to be built."
| browser_patches/prepare_checkout.sh | 0 | https://github.com/microsoft/playwright/commit/310d4b193b4a7d3944af95424e44e4293392db24 | [
0.0001726209302432835,
0.00016956351464614272,
0.00016432923439424485,
0.00016973425226751715,
0.0000023006323317531496
] |
{
"id": 5,
"code_window": [
" const [request] = await Promise.all([\n",
" server.waitForRequest('/empty.html'),\n",
" utils.attachFrame(page, 'frame1', server.EMPTY_PAGE),\n",
" ]);\n",
" expect(request.headers['user-agent']).toBe('foobar'); \n",
" }\n",
" });\n",
" it('should emulate device user-agent', async({newPage, server}) => {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" expect(request.headers['user-agent']).toBe('foobar');\n"
],
"file_path": "test/browsercontext.spec.js",
"type": "replace",
"edit_start_line_idx": 141
} | ### class: Foo
#### foo.asyncFunction()
#### foo.return42()
#### foo.returnNothing()
- returns: <[number]>
#### foo.www()
- returns <[string]>
[string]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type "String"
[number]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type "Number"
| utils/doclint/check_public_api/test/check-returns/doc.md | 0 | https://github.com/microsoft/playwright/commit/310d4b193b4a7d3944af95424e44e4293392db24 | [
0.00017253651458304375,
0.00017146108439192176,
0.00017038565420079976,
0.00017146108439192176,
0.0000010754301911219954
] |
{
"id": 5,
"code_window": [
" const [request] = await Promise.all([\n",
" server.waitForRequest('/empty.html'),\n",
" utils.attachFrame(page, 'frame1', server.EMPTY_PAGE),\n",
" ]);\n",
" expect(request.headers['user-agent']).toBe('foobar'); \n",
" }\n",
" });\n",
" it('should emulate device user-agent', async({newPage, server}) => {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" expect(request.headers['user-agent']).toBe('foobar');\n"
],
"file_path": "test/browsercontext.spec.js",
"type": "replace",
"edit_start_line_idx": 141
} | /**
* Copyright 2019 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.
*/
export const Events = {
CRBrowser: {
TargetCreated: 'targetcreated',
TargetDestroyed: 'targetdestroyed',
TargetChanged: 'targetchanged',
},
CRPage: {
WorkerCreated: 'workercreated',
WorkerDestroyed: 'workerdestroyed',
}
};
| src/chromium/events.ts | 0 | https://github.com/microsoft/playwright/commit/310d4b193b4a7d3944af95424e44e4293392db24 | [
0.00017521248082630336,
0.0001728371571516618,
0.00017112762725446373,
0.00017217136337421834,
0.0000017328143258055206
] |
{
"id": 6,
"code_window": [
" };\n",
"\n",
" state.newPage = async (options) => {\n",
" const context = await state.newContext(options);\n",
" return await context.newPage(options);\n",
" };\n",
" });\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" return await context.newPage();\n"
],
"file_path": "test/playwright.spec.js",
"type": "replace",
"edit_start_line_idx": 129
} | /**
* Copyright 2018 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.
*/
const utils = require('./utils');
module.exports.describe = function({testRunner, expect, playwright, CHROME, WEBKIT}) {
const {describe, xdescribe, fdescribe} = testRunner;
const {it, fit, xit, dit} = testRunner;
const {beforeAll, beforeEach, afterAll, afterEach} = testRunner;
describe('BrowserContext', function() {
it('should have default context', async function({browser, server}) {
expect(browser.browserContexts().length).toBe(1);
const defaultContext = browser.browserContexts()[0];
let error = null;
await defaultContext.close().catch(e => error = e);
expect(browser.defaultContext()).toBe(defaultContext);
expect(error.message).toContain('cannot be closed');
});
it('should create new incognito context', async function({browser, newContext}) {
expect(browser.browserContexts().length).toBe(1);
const context = await newContext();
expect(browser.browserContexts().length).toBe(2);
expect(browser.browserContexts().indexOf(context) !== -1).toBe(true);
await context.close();
expect(browser.browserContexts().length).toBe(1);
});
it('window.open should use parent tab context', async function({newContext, server}) {
const context = await newContext();
const page = await context.newPage();
await page.goto(server.EMPTY_PAGE);
const [popupTarget] = await Promise.all([
utils.waitEvent(page, 'popup'),
page.evaluate(url => window.open(url), server.EMPTY_PAGE)
]);
expect(popupTarget.browserContext()).toBe(context);
});
it('should isolate localStorage and cookies', async function({browser, newContext, server}) {
// Create two incognito contexts.
const context1 = await newContext();
const context2 = await newContext();
expect((await context1.pages()).length).toBe(0);
expect((await context2.pages()).length).toBe(0);
// Create a page in first incognito context.
const page1 = await context1.newPage();
await page1.goto(server.EMPTY_PAGE);
await page1.evaluate(() => {
localStorage.setItem('name', 'page1');
document.cookie = 'name=page1';
});
expect((await context1.pages()).length).toBe(1);
expect((await context2.pages()).length).toBe(0);
// Create a page in second incognito context.
const page2 = await context2.newPage();
await page2.goto(server.EMPTY_PAGE);
await page2.evaluate(() => {
localStorage.setItem('name', 'page2');
document.cookie = 'name=page2';
});
expect((await context1.pages()).length).toBe(1);
expect((await context2.pages()).length).toBe(1);
expect((await context1.pages())[0]).toBe(page1);
expect((await context2.pages())[0]).toBe(page2);
// Make sure pages don't share localstorage or cookies.
expect(await page1.evaluate(() => localStorage.getItem('name'))).toBe('page1');
expect(await page1.evaluate(() => document.cookie)).toBe('name=page1');
expect(await page2.evaluate(() => localStorage.getItem('name'))).toBe('page2');
expect(await page2.evaluate(() => document.cookie)).toBe('name=page2');
// Cleanup contexts.
await Promise.all([
context1.close(),
context2.close()
]);
expect(browser.browserContexts().length).toBe(1);
});
it('should set the default viewport', async({ newPage }) => {
const page = await newPage({ viewport: { width: 456, height: 789 } });
expect(await page.evaluate('window.innerWidth')).toBe(456);
expect(await page.evaluate('window.innerHeight')).toBe(789);
});
it('should take fullPage screenshots when default viewport is null', async({server, newPage}) => {
const page = await newPage({ viewport: null });
await page.goto(server.PREFIX + '/grid.html');
const sizeBefore = await page.evaluate(() => ({ width: document.body.offsetWidth, height: document.body.offsetHeight }));
const screenshot = await page.screenshot({
fullPage: true
});
expect(screenshot).toBeInstanceOf(Buffer);
const sizeAfter = await page.evaluate(() => ({ width: document.body.offsetWidth, height: document.body.offsetHeight }));
expect(sizeBefore.width).toBe(sizeAfter.width);
expect(sizeBefore.height).toBe(sizeAfter.height);
});
});
describe('BrowserContext({setUserAgent})', function() {
it('should work', async({newPage, server}) => {
{
const page = await newPage();
expect(await page.evaluate(() => navigator.userAgent)).toContain('Mozilla');
}
{
const page = await newPage({ userAgent: 'foobar' });
const [request] = await Promise.all([
server.waitForRequest('/empty.html'),
page.goto(server.EMPTY_PAGE),
]);
expect(request.headers['user-agent']).toBe('foobar');
}
});
it('should work for subframes', async({newPage, server}) => {
{
const page = await newPage();
expect(await page.evaluate(() => navigator.userAgent)).toContain('Mozilla');
}
{
const page = await newPage({ userAgent: 'foobar' });
const [request] = await Promise.all([
server.waitForRequest('/empty.html'),
utils.attachFrame(page, 'frame1', server.EMPTY_PAGE),
]);
expect(request.headers['user-agent']).toBe('foobar');
}
});
it('should emulate device user-agent', async({newPage, server}) => {
{
const page = await newPage();
await page.goto(server.PREFIX + '/mobile.html');
expect(await page.evaluate(() => navigator.userAgent)).not.toContain('iPhone');
}
{
const page = await newPage({ userAgent: playwright.devices['iPhone 6'].userAgent });
await page.goto(server.PREFIX + '/mobile.html');
expect(await page.evaluate(() => navigator.userAgent)).toContain('iPhone');
}
});
});
describe('BrowserContext({bypassCSP})', function() {
it('should bypass CSP meta tag', async({newPage, server}) => {
// Make sure CSP prohibits addScriptTag.
{
const page = await newPage();
await page.goto(server.PREFIX + '/csp.html');
await page.addScriptTag({content: 'window.__injected = 42;'}).catch(e => void e);
expect(await page.evaluate(() => window.__injected)).toBe(undefined);
}
// By-pass CSP and try one more time.
{
const page = await newPage({ bypassCSP: true });
await page.goto(server.PREFIX + '/csp.html');
await page.addScriptTag({content: 'window.__injected = 42;'});
expect(await page.evaluate(() => window.__injected)).toBe(42);
}
});
it('should bypass CSP header', async({newPage, server}) => {
// Make sure CSP prohibits addScriptTag.
server.setCSP('/empty.html', 'default-src "self"');
{
const page = await newPage();
await page.goto(server.EMPTY_PAGE);
await page.addScriptTag({content: 'window.__injected = 42;'}).catch(e => void e);
expect(await page.evaluate(() => window.__injected)).toBe(undefined);
}
// By-pass CSP and try one more time.
{
const page = await newPage({ bypassCSP: true });
await page.goto(server.EMPTY_PAGE);
await page.addScriptTag({content: 'window.__injected = 42;'});
expect(await page.evaluate(() => window.__injected)).toBe(42);
}
});
it('should bypass after cross-process navigation', async({newPage, server}) => {
const page = await newPage({ bypassCSP: true });
await page.goto(server.PREFIX + '/csp.html');
await page.addScriptTag({content: 'window.__injected = 42;'});
expect(await page.evaluate(() => window.__injected)).toBe(42);
await page.goto(server.CROSS_PROCESS_PREFIX + '/csp.html');
await page.addScriptTag({content: 'window.__injected = 42;'});
expect(await page.evaluate(() => window.__injected)).toBe(42);
});
it('should bypass CSP in iframes as well', async({newPage, server}) => {
// Make sure CSP prohibits addScriptTag in an iframe.
{
const page = await newPage();
await page.goto(server.EMPTY_PAGE);
const frame = await utils.attachFrame(page, 'frame1', server.PREFIX + '/csp.html');
await frame.addScriptTag({content: 'window.__injected = 42;'}).catch(e => void e);
expect(await frame.evaluate(() => window.__injected)).toBe(undefined);
}
// By-pass CSP and try one more time.
{
const page = await newPage({ bypassCSP: true });
await page.goto(server.EMPTY_PAGE);
const frame = await utils.attachFrame(page, 'frame1', server.PREFIX + '/csp.html');
await frame.addScriptTag({content: 'window.__injected = 42;'}).catch(e => void e);
expect(await frame.evaluate(() => window.__injected)).toBe(42);
}
});
});
describe('BrowserContext({javaScriptEnabled})', function() {
it('should work', async({newPage}) => {
{
const page = await newPage({ javaScriptEnabled: false });
await page.goto('data:text/html, <script>var something = "forbidden"</script>');
let error = null;
await page.evaluate('something').catch(e => error = e);
if (WEBKIT)
expect(error.message).toContain('Can\'t find variable: something');
else
expect(error.message).toContain('something is not defined');
}
{
const page = await newPage();
await page.goto('data:text/html, <script>var something = "forbidden"</script>');
expect(await page.evaluate('something')).toBe('forbidden');
}
});
it('should be able to navigate after disabling javascript', async({newPage, server}) => {
const page = await newPage({ javaScriptEnabled: false });
await page.goto(server.EMPTY_PAGE);
});
});
};
| test/browsercontext.spec.js | 1 | https://github.com/microsoft/playwright/commit/310d4b193b4a7d3944af95424e44e4293392db24 | [
0.2313821166753769,
0.011183948256075382,
0.00016459645121358335,
0.0015649654669687152,
0.044114839285612106
] |
{
"id": 6,
"code_window": [
" };\n",
"\n",
" state.newPage = async (options) => {\n",
" const context = await state.newContext(options);\n",
" return await context.newPage(options);\n",
" };\n",
" });\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" return await context.newPage();\n"
],
"file_path": "test/playwright.spec.js",
"type": "replace",
"edit_start_line_idx": 129
} | console.log('hey from the content-script');
self.thisIsTheContentScript = true;
| test/assets/simple-extension/content-script.js | 0 | https://github.com/microsoft/playwright/commit/310d4b193b4a7d3944af95424e44e4293392db24 | [
0.00017289140669163316,
0.00017289140669163316,
0.00017289140669163316,
0.00017289140669163316,
0
] |
{
"id": 6,
"code_window": [
" };\n",
"\n",
" state.newPage = async (options) => {\n",
" const context = await state.newContext(options);\n",
" return await context.newPage(options);\n",
" };\n",
" });\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" return await context.newPage();\n"
],
"file_path": "test/playwright.spec.js",
"type": "replace",
"edit_start_line_idx": 129
} | [MarkDown] foo.www() has mistyped 'return' type declaration: expected exactly 'returns: ', found 'returns '.
[MarkDown] Method Foo.asyncFunction is missing return type description
[MarkDown] Method Foo.return42 is missing return type description
[MarkDown] Method Foo.returnNothing has unneeded description of return type | utils/doclint/check_public_api/test/check-returns/result.txt | 0 | https://github.com/microsoft/playwright/commit/310d4b193b4a7d3944af95424e44e4293392db24 | [
0.00017154453962575644,
0.00017154453962575644,
0.00017154453962575644,
0.00017154453962575644,
0
] |
{
"id": 6,
"code_window": [
" };\n",
"\n",
" state.newPage = async (options) => {\n",
" const context = await state.newContext(options);\n",
" return await context.newPage(options);\n",
" };\n",
" });\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" return await context.newPage();\n"
],
"file_path": "test/playwright.spec.js",
"type": "replace",
"edit_start_line_idx": 129
} | /**
* 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.
*/
const fs = require('fs');
const os = require('os');
const path = require('path');
const {helper} = require('../lib/helper');
const rmAsync = helper.promisify(require('rimraf'));
const mkdtempAsync = helper.promisify(fs.mkdtemp);
const TMP_FOLDER = path.join(os.tmpdir(), 'pptr_tmp_folder-');
const utils = require('./utils');
module.exports.describe = function({testRunner, expect, defaultBrowserOptions, playwright, WEBKIT}) {
const {describe, xdescribe, fdescribe} = testRunner;
const {it, fit, xit, dit} = testRunner;
const {beforeAll, beforeEach, afterAll, afterEach} = testRunner;
describe('Playwright', function() {
describe('Playwright.launch', function() {
it('should reject all promises when browser is closed', async() => {
const browser = await playwright.launch(defaultBrowserOptions);
const page = await browser.defaultContext().newPage();
let error = null;
const neverResolves = page.evaluate(() => new Promise(r => {})).catch(e => error = e);
await browser.close();
await neverResolves;
expect(error.message).toContain('Protocol error');
});
it('should reject if executable path is invalid', async({server}) => {
let waitError = null;
const options = Object.assign({}, defaultBrowserOptions, {executablePath: 'random-invalid-path'});
await playwright.launch(options).catch(e => waitError = e);
expect(waitError.message).toContain('Failed to launch');
});
it('should have default URL when launching browser', async function() {
const browser = await playwright.launch(defaultBrowserOptions);
const pages = (await browser.defaultContext().pages()).map(page => page.url());
expect(pages).toEqual(['about:blank']);
await browser.close();
});
it('should have custom URL when launching browser', async function({server}) {
const options = Object.assign({}, defaultBrowserOptions);
options.args = [server.EMPTY_PAGE].concat(options.args || []);
const browser = await playwright.launch(options);
const pages = await browser.defaultContext().pages();
expect(pages.length).toBe(1);
const page = pages[0];
if (page.url() !== server.EMPTY_PAGE) {
await page.waitForNavigation();
}
expect(page.url()).toBe(server.EMPTY_PAGE);
await browser.close();
});
});
describe('Playwright.executablePath', function() {
it('should work', async({server}) => {
const executablePath = playwright.executablePath();
expect(fs.existsSync(executablePath)).toBe(true);
expect(fs.realpathSync(executablePath)).toBe(executablePath);
});
});
});
describe('Top-level requires', function() {
it('should require top-level Errors', async() => {
const Errors = require(path.join(utils.projectRoot(), '/Errors'));
expect(Errors.TimeoutError).toBe(playwright.errors.TimeoutError);
});
it('should require top-level DeviceDescriptors', async() => {
const Devices = require(path.join(utils.projectRoot(), '/DeviceDescriptors'));
expect(Devices['iPhone 6']).toBe(playwright.devices['iPhone 6']);
});
});
};
| test/launcher.spec.js | 0 | https://github.com/microsoft/playwright/commit/310d4b193b4a7d3944af95424e44e4293392db24 | [
0.0025957587640732527,
0.0005226907087489963,
0.00016711567877791822,
0.00017616921104490757,
0.0007525040418840945
] |
{
"id": 7,
"code_window": [
" fullPage: true\n",
" });\n",
" expect(screenshot).toBeGolden('screenshot-grid-fullpage.png');\n",
" });\n",
" it('should run in parallel in multiple pages', async({page, server, context}) => {\n",
" const N = 2;\n",
" const pages = await Promise.all(Array(N).fill(0).map(async() => {\n",
" const page = await context.newPage();\n",
" await page.goto(server.PREFIX + '/grid.html');\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" it('should restore viewport after fullPage screenshot', async({page, server}) => {\n",
" await page.setViewport({width: 500, height: 500});\n",
" await page.goto(server.PREFIX + '/grid.html');\n",
" const screenshot = await page.screenshot({ fullPage: true });\n",
" expect(screenshot).toBeInstanceOf(Buffer);\n",
" expect(page.viewport().width).toBe(500);\n",
" expect(page.viewport().height).toBe(500);\n",
" });\n"
],
"file_path": "test/screenshot.spec.js",
"type": "add",
"edit_start_line_idx": 93
} | /**
* Copyright 2018 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.
*/
const utils = require('./utils');
module.exports.describe = function({testRunner, expect, playwright, CHROME, WEBKIT}) {
const {describe, xdescribe, fdescribe} = testRunner;
const {it, fit, xit, dit} = testRunner;
const {beforeAll, beforeEach, afterAll, afterEach} = testRunner;
describe('BrowserContext', function() {
it('should have default context', async function({browser, server}) {
expect(browser.browserContexts().length).toBe(1);
const defaultContext = browser.browserContexts()[0];
let error = null;
await defaultContext.close().catch(e => error = e);
expect(browser.defaultContext()).toBe(defaultContext);
expect(error.message).toContain('cannot be closed');
});
it('should create new incognito context', async function({browser, newContext}) {
expect(browser.browserContexts().length).toBe(1);
const context = await newContext();
expect(browser.browserContexts().length).toBe(2);
expect(browser.browserContexts().indexOf(context) !== -1).toBe(true);
await context.close();
expect(browser.browserContexts().length).toBe(1);
});
it('window.open should use parent tab context', async function({newContext, server}) {
const context = await newContext();
const page = await context.newPage();
await page.goto(server.EMPTY_PAGE);
const [popupTarget] = await Promise.all([
utils.waitEvent(page, 'popup'),
page.evaluate(url => window.open(url), server.EMPTY_PAGE)
]);
expect(popupTarget.browserContext()).toBe(context);
});
it('should isolate localStorage and cookies', async function({browser, newContext, server}) {
// Create two incognito contexts.
const context1 = await newContext();
const context2 = await newContext();
expect((await context1.pages()).length).toBe(0);
expect((await context2.pages()).length).toBe(0);
// Create a page in first incognito context.
const page1 = await context1.newPage();
await page1.goto(server.EMPTY_PAGE);
await page1.evaluate(() => {
localStorage.setItem('name', 'page1');
document.cookie = 'name=page1';
});
expect((await context1.pages()).length).toBe(1);
expect((await context2.pages()).length).toBe(0);
// Create a page in second incognito context.
const page2 = await context2.newPage();
await page2.goto(server.EMPTY_PAGE);
await page2.evaluate(() => {
localStorage.setItem('name', 'page2');
document.cookie = 'name=page2';
});
expect((await context1.pages()).length).toBe(1);
expect((await context2.pages()).length).toBe(1);
expect((await context1.pages())[0]).toBe(page1);
expect((await context2.pages())[0]).toBe(page2);
// Make sure pages don't share localstorage or cookies.
expect(await page1.evaluate(() => localStorage.getItem('name'))).toBe('page1');
expect(await page1.evaluate(() => document.cookie)).toBe('name=page1');
expect(await page2.evaluate(() => localStorage.getItem('name'))).toBe('page2');
expect(await page2.evaluate(() => document.cookie)).toBe('name=page2');
// Cleanup contexts.
await Promise.all([
context1.close(),
context2.close()
]);
expect(browser.browserContexts().length).toBe(1);
});
it('should set the default viewport', async({ newPage }) => {
const page = await newPage({ viewport: { width: 456, height: 789 } });
expect(await page.evaluate('window.innerWidth')).toBe(456);
expect(await page.evaluate('window.innerHeight')).toBe(789);
});
it('should take fullPage screenshots when default viewport is null', async({server, newPage}) => {
const page = await newPage({ viewport: null });
await page.goto(server.PREFIX + '/grid.html');
const sizeBefore = await page.evaluate(() => ({ width: document.body.offsetWidth, height: document.body.offsetHeight }));
const screenshot = await page.screenshot({
fullPage: true
});
expect(screenshot).toBeInstanceOf(Buffer);
const sizeAfter = await page.evaluate(() => ({ width: document.body.offsetWidth, height: document.body.offsetHeight }));
expect(sizeBefore.width).toBe(sizeAfter.width);
expect(sizeBefore.height).toBe(sizeAfter.height);
});
});
describe('BrowserContext({setUserAgent})', function() {
it('should work', async({newPage, server}) => {
{
const page = await newPage();
expect(await page.evaluate(() => navigator.userAgent)).toContain('Mozilla');
}
{
const page = await newPage({ userAgent: 'foobar' });
const [request] = await Promise.all([
server.waitForRequest('/empty.html'),
page.goto(server.EMPTY_PAGE),
]);
expect(request.headers['user-agent']).toBe('foobar');
}
});
it('should work for subframes', async({newPage, server}) => {
{
const page = await newPage();
expect(await page.evaluate(() => navigator.userAgent)).toContain('Mozilla');
}
{
const page = await newPage({ userAgent: 'foobar' });
const [request] = await Promise.all([
server.waitForRequest('/empty.html'),
utils.attachFrame(page, 'frame1', server.EMPTY_PAGE),
]);
expect(request.headers['user-agent']).toBe('foobar');
}
});
it('should emulate device user-agent', async({newPage, server}) => {
{
const page = await newPage();
await page.goto(server.PREFIX + '/mobile.html');
expect(await page.evaluate(() => navigator.userAgent)).not.toContain('iPhone');
}
{
const page = await newPage({ userAgent: playwright.devices['iPhone 6'].userAgent });
await page.goto(server.PREFIX + '/mobile.html');
expect(await page.evaluate(() => navigator.userAgent)).toContain('iPhone');
}
});
});
describe('BrowserContext({bypassCSP})', function() {
it('should bypass CSP meta tag', async({newPage, server}) => {
// Make sure CSP prohibits addScriptTag.
{
const page = await newPage();
await page.goto(server.PREFIX + '/csp.html');
await page.addScriptTag({content: 'window.__injected = 42;'}).catch(e => void e);
expect(await page.evaluate(() => window.__injected)).toBe(undefined);
}
// By-pass CSP and try one more time.
{
const page = await newPage({ bypassCSP: true });
await page.goto(server.PREFIX + '/csp.html');
await page.addScriptTag({content: 'window.__injected = 42;'});
expect(await page.evaluate(() => window.__injected)).toBe(42);
}
});
it('should bypass CSP header', async({newPage, server}) => {
// Make sure CSP prohibits addScriptTag.
server.setCSP('/empty.html', 'default-src "self"');
{
const page = await newPage();
await page.goto(server.EMPTY_PAGE);
await page.addScriptTag({content: 'window.__injected = 42;'}).catch(e => void e);
expect(await page.evaluate(() => window.__injected)).toBe(undefined);
}
// By-pass CSP and try one more time.
{
const page = await newPage({ bypassCSP: true });
await page.goto(server.EMPTY_PAGE);
await page.addScriptTag({content: 'window.__injected = 42;'});
expect(await page.evaluate(() => window.__injected)).toBe(42);
}
});
it('should bypass after cross-process navigation', async({newPage, server}) => {
const page = await newPage({ bypassCSP: true });
await page.goto(server.PREFIX + '/csp.html');
await page.addScriptTag({content: 'window.__injected = 42;'});
expect(await page.evaluate(() => window.__injected)).toBe(42);
await page.goto(server.CROSS_PROCESS_PREFIX + '/csp.html');
await page.addScriptTag({content: 'window.__injected = 42;'});
expect(await page.evaluate(() => window.__injected)).toBe(42);
});
it('should bypass CSP in iframes as well', async({newPage, server}) => {
// Make sure CSP prohibits addScriptTag in an iframe.
{
const page = await newPage();
await page.goto(server.EMPTY_PAGE);
const frame = await utils.attachFrame(page, 'frame1', server.PREFIX + '/csp.html');
await frame.addScriptTag({content: 'window.__injected = 42;'}).catch(e => void e);
expect(await frame.evaluate(() => window.__injected)).toBe(undefined);
}
// By-pass CSP and try one more time.
{
const page = await newPage({ bypassCSP: true });
await page.goto(server.EMPTY_PAGE);
const frame = await utils.attachFrame(page, 'frame1', server.PREFIX + '/csp.html');
await frame.addScriptTag({content: 'window.__injected = 42;'}).catch(e => void e);
expect(await frame.evaluate(() => window.__injected)).toBe(42);
}
});
});
describe('BrowserContext({javaScriptEnabled})', function() {
it('should work', async({newPage}) => {
{
const page = await newPage({ javaScriptEnabled: false });
await page.goto('data:text/html, <script>var something = "forbidden"</script>');
let error = null;
await page.evaluate('something').catch(e => error = e);
if (WEBKIT)
expect(error.message).toContain('Can\'t find variable: something');
else
expect(error.message).toContain('something is not defined');
}
{
const page = await newPage();
await page.goto('data:text/html, <script>var something = "forbidden"</script>');
expect(await page.evaluate('something')).toBe('forbidden');
}
});
it('should be able to navigate after disabling javascript', async({newPage, server}) => {
const page = await newPage({ javaScriptEnabled: false });
await page.goto(server.EMPTY_PAGE);
});
});
};
| test/browsercontext.spec.js | 1 | https://github.com/microsoft/playwright/commit/310d4b193b4a7d3944af95424e44e4293392db24 | [
0.01571328565478325,
0.0017087297746911645,
0.00016714994853828102,
0.0006371894851326942,
0.003064917167648673
] |
{
"id": 7,
"code_window": [
" fullPage: true\n",
" });\n",
" expect(screenshot).toBeGolden('screenshot-grid-fullpage.png');\n",
" });\n",
" it('should run in parallel in multiple pages', async({page, server, context}) => {\n",
" const N = 2;\n",
" const pages = await Promise.all(Array(N).fill(0).map(async() => {\n",
" const page = await context.newPage();\n",
" await page.goto(server.PREFIX + '/grid.html');\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" it('should restore viewport after fullPage screenshot', async({page, server}) => {\n",
" await page.setViewport({width: 500, height: 500});\n",
" await page.goto(server.PREFIX + '/grid.html');\n",
" const screenshot = await page.screenshot({ fullPage: true });\n",
" expect(screenshot).toBeInstanceOf(Buffer);\n",
" expect(page.viewport().width).toBe(500);\n",
" expect(page.viewport().height).toBe(500);\n",
" });\n"
],
"file_path": "test/screenshot.spec.js",
"type": "add",
"edit_start_line_idx": 93
} | #!/bin/bash
set -e
set +x
if [[ ("$1" == "-h") || ("$1" == "--help") ]]; then
echo "usage: $(basename $0) [output-absolute-path]"
echo
echo "Generate distributable .zip archive from ./checkout folder that was previously built."
echo
exit 0
fi
if [[ $# != 1 ]]; then
echo "error: missing zip output path"
echo "try '$(basename $0) --help' for details"
exit 1
fi
ZIP_PATH=$1
if [[ $ZIP_PATH != /* ]]; then
echo "ERROR: path $ZIP_PATH is not absolute"
exit 1
fi
if [[ $ZIP_PATH != *.zip ]]; then
echo "ERROR: path $ZIP_PATH must have .zip extension"
exit 1
fi
if [[ -f $ZIP_PATH ]]; then
echo "ERROR: path $ZIP_PATH exists; can't do anything."
exit 1
fi
if ! [[ -d $(dirname $ZIP_PATH) ]]; then
echo "ERROR: folder for path $($ZIP_PATH) does not exist."
exit 1
fi
main() {
cd checkout
set -x
if [[ "$(uname)" == "Darwin" ]]; then
createZipForMac
elif [[ "$(uname)" == "Linux" ]]; then
createZipForLinux
else
echo "ERROR: cannot upload on this platform!" 1>&2
exit 1;
fi
}
createZipForLinux() {
# create a TMP directory to copy all necessary files
local tmpdir=$(mktemp -d -t webkit-deploy-XXXXXXXXXX)
mkdir -p $tmpdir
# copy all relevant binaries
cp -t $tmpdir ./WebKitBuild/Release/bin/MiniBrowser ./WebKitBuild/Release/bin/WebKit*Process
# copy runner
cp -t $tmpdir ../pw_run.sh
# copy protocol
node ../concat_protocol.js > $tmpdir/protocol.json
# copy all relevant shared objects
LD_LIBRARY_PATH="$PWD/WebKitBuild/DependenciesGTK/Root/lib" ldd WebKitBuild/Release/bin/MiniBrowser | grep -o '[^ ]*WebKitBuild/[^ ]*' | xargs cp -t $tmpdir
# we failed to nicely build libgdk_pixbuf - expect it in the env
rm $tmpdir/libgdk_pixbuf*
# tar resulting directory and cleanup TMP.
zip -jr $ZIP_PATH $tmpdir
rm -rf $tmpdir
}
createZipForMac() {
# create a TMP directory to copy all necessary files
local tmpdir=$(mktemp -d)
# copy all relevant files
ditto {./WebKitBuild/Release,$tmpdir}/com.apple.WebKit.Networking.xpc
ditto {./WebKitBuild/Release,$tmpdir}/com.apple.WebKit.Plugin.64.xpc
ditto {./WebKitBuild/Release,$tmpdir}/com.apple.WebKit.WebContent.xpc
ditto {./WebKitBuild/Release,$tmpdir}/JavaScriptCore.framework
ditto {./WebKitBuild/Release,$tmpdir}/libwebrtc.dylib
ditto {./WebKitBuild/Release,$tmpdir}/MiniBrowser.app
ditto {./WebKitBuild/Release,$tmpdir}/PluginProcessShim.dylib
ditto {./WebKitBuild/Release,$tmpdir}/SecItemShim.dylib
ditto {./WebKitBuild/Release,$tmpdir}/WebCore.framework
ditto {./WebKitBuild/Release,$tmpdir}/WebInspectorUI.framework
ditto {./WebKitBuild/Release,$tmpdir}/WebKit.framework
ditto {./WebKitBuild/Release,$tmpdir}/WebKitLegacy.framework
ditto {..,$tmpdir}/pw_run.sh
# copy protocol
node ../concat_protocol.js > $tmpdir/protocol.json
# zip resulting directory and cleanup TMP.
ditto -c -k $tmpdir $ZIP_PATH
rm -rf $tmpdir
}
trap "cd $(pwd -P)" EXIT
cd "$(dirname "$0")"
main "$@"
| browser_patches/webkit/archive.sh | 0 | https://github.com/microsoft/playwright/commit/310d4b193b4a7d3944af95424e44e4293392db24 | [
0.00017902471881825477,
0.0001742081658449024,
0.00016615487402305007,
0.00017534302605781704,
0.0000031222029974742327
] |
{
"id": 7,
"code_window": [
" fullPage: true\n",
" });\n",
" expect(screenshot).toBeGolden('screenshot-grid-fullpage.png');\n",
" });\n",
" it('should run in parallel in multiple pages', async({page, server, context}) => {\n",
" const N = 2;\n",
" const pages = await Promise.all(Array(N).fill(0).map(async() => {\n",
" const page = await context.newPage();\n",
" await page.goto(server.PREFIX + '/grid.html');\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" it('should restore viewport after fullPage screenshot', async({page, server}) => {\n",
" await page.setViewport({width: 500, height: 500});\n",
" await page.goto(server.PREFIX + '/grid.html');\n",
" const screenshot = await page.screenshot({ fullPage: true });\n",
" expect(screenshot).toBeInstanceOf(Buffer);\n",
" expect(page.viewport().width).toBe(500);\n",
" expect(page.viewport().height).toBe(500);\n",
" });\n"
],
"file_path": "test/screenshot.spec.js",
"type": "add",
"edit_start_line_idx": 93
} | /**
* Copyright 2017 Google Inc. 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.
*/
const {TestRunner, Reporter} = require('..');
const runner = new TestRunner();
const reporter = new Reporter(runner);
const {describe, xdescribe, fdescribe} = runner;
const {it, fit, xit} = runner;
const {beforeAll, beforeEach, afterAll, afterEach} = runner;
describe('testsuite', () => {
it('failure', async (state) => {
Promise.reject(new Error('fail!'));
});
it('slow', async () => {
await new Promise(x => setTimeout(x, 1000));
});
});
runner.run();
| utils/testrunner/examples/unhandledpromiserejection.js | 0 | https://github.com/microsoft/playwright/commit/310d4b193b4a7d3944af95424e44e4293392db24 | [
0.0008380049257539213,
0.00033997249556705356,
0.00016909459372982383,
0.00017639523139223456,
0.0002875584177672863
] |
{
"id": 7,
"code_window": [
" fullPage: true\n",
" });\n",
" expect(screenshot).toBeGolden('screenshot-grid-fullpage.png');\n",
" });\n",
" it('should run in parallel in multiple pages', async({page, server, context}) => {\n",
" const N = 2;\n",
" const pages = await Promise.all(Array(N).fill(0).map(async() => {\n",
" const page = await context.newPage();\n",
" await page.goto(server.PREFIX + '/grid.html');\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" it('should restore viewport after fullPage screenshot', async({page, server}) => {\n",
" await page.setViewport({width: 500, height: 500});\n",
" await page.goto(server.PREFIX + '/grid.html');\n",
" const screenshot = await page.screenshot({ fullPage: true });\n",
" expect(screenshot).toBeInstanceOf(Buffer);\n",
" expect(page.viewport().width).toBe(500);\n",
" expect(page.viewport().height).toBe(500);\n",
" });\n"
],
"file_path": "test/screenshot.spec.js",
"type": "add",
"edit_start_line_idx": 93
} | // Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
import * as types from './types';
import * as dom from './dom';
export interface ExecutionContextDelegate {
evaluate(context: ExecutionContext, returnByValue: boolean, pageFunction: string | Function, ...args: any[]): Promise<any>;
getProperties(handle: JSHandle): Promise<Map<string, JSHandle>>;
releaseHandle(handle: JSHandle): Promise<void>;
handleToString(handle: JSHandle, includeType: boolean): string;
handleJSONValue<T>(handle: JSHandle<T>): Promise<T>;
}
export class ExecutionContext {
readonly _delegate: ExecutionContextDelegate;
constructor(delegate: ExecutionContextDelegate) {
this._delegate = delegate;
}
_evaluate(returnByValue: boolean, pageFunction: string | Function, ...args: any[]): Promise<any> {
return this._delegate.evaluate(this, returnByValue, pageFunction, ...args);
}
evaluate: types.Evaluate = async (pageFunction, ...args) => {
return this._evaluate(true /* returnByValue */, pageFunction, ...args);
}
evaluateHandle: types.EvaluateHandle = async (pageFunction, ...args) => {
return this._evaluate(false /* returnByValue */, pageFunction, ...args);
}
_createHandle(remoteObject: any): JSHandle {
return new JSHandle(this, remoteObject);
}
}
export class JSHandle<T = any> {
readonly _context: ExecutionContext;
readonly _remoteObject: any;
_disposed = false;
constructor(context: ExecutionContext, remoteObject: any) {
this._context = context;
this._remoteObject = remoteObject;
}
evaluate: types.EvaluateOn<T> = (pageFunction, ...args) => {
return this._context.evaluate(pageFunction, this, ...args);
}
evaluateHandle: types.EvaluateHandleOn<T> = (pageFunction, ...args) => {
return this._context.evaluateHandle(pageFunction, this, ...args);
}
async getProperty(propertyName: string): Promise<JSHandle | null> {
const objectHandle = await this.evaluateHandle((object, propertyName) => {
const result = {__proto__: null};
result[propertyName] = object[propertyName];
return result;
}, propertyName);
const properties = await objectHandle.getProperties();
const result = properties.get(propertyName) || null;
await objectHandle.dispose();
return result;
}
getProperties(): Promise<Map<string, JSHandle>> {
return this._context._delegate.getProperties(this);
}
jsonValue(): Promise<T> {
return this._context._delegate.handleJSONValue(this);
}
asElement(): dom.ElementHandle | null {
return null;
}
async dispose() {
if (this._disposed)
return;
this._disposed = true;
await this._context._delegate.releaseHandle(this);
}
toString(): string {
return this._context._delegate.handleToString(this, true /* includeType */);
}
}
| src/javascript.ts | 0 | https://github.com/microsoft/playwright/commit/310d4b193b4a7d3944af95424e44e4293392db24 | [
0.00017544117872603238,
0.00017142020806204528,
0.00016375049017369747,
0.000173062871908769,
0.00000397951089325943
] |
{
"id": 0,
"code_window": [
" expect(fn2).toHaveBeenCalledWith('two')\n",
" })\n",
"\n",
" test('isEmitListener', () => {\n",
" const options = { click: null }\n",
" expect(isEmitListener(options, 'onClick')).toBe(true)\n",
" expect(isEmitListener(options, 'onclick')).toBe(false)\n",
" expect(isEmitListener(options, 'onBlick')).toBe(false)\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" const options = {\n",
" click: null,\n",
" 'test-event': null,\n",
" fooBar: null,\n",
" FooBaz: null\n",
" }\n"
],
"file_path": "packages/runtime-core/__tests__/componentEmits.spec.ts",
"type": "replace",
"edit_start_line_idx": 285
} | // Note: emits and listener fallthrough is tested in
// ./rendererAttrsFallthrough.spec.ts.
import { render, defineComponent, h, nodeOps } from '@vue/runtime-test'
import { isEmitListener } from '../src/componentEmits'
describe('component: emit', () => {
test('trigger handlers', () => {
const Foo = defineComponent({
render() {},
created() {
// the `emit` function is bound on component instances
this.$emit('foo')
this.$emit('bar')
this.$emit('!baz')
}
})
const onfoo = jest.fn()
const onBar = jest.fn()
const onBaz = jest.fn()
const Comp = () => h(Foo, { onfoo, onBar, ['on!baz']: onBaz })
render(h(Comp), nodeOps.createElement('div'))
expect(onfoo).not.toHaveBeenCalled()
// only capitalized or special chars are considered event listeners
expect(onBar).toHaveBeenCalled()
expect(onBaz).toHaveBeenCalled()
})
test('trigger camelize event', () => {
const Foo = defineComponent({
render() {},
created() {
this.$emit('test-event')
}
})
const fooSpy = jest.fn()
const Comp = () =>
h(Foo, {
onTestEvent: fooSpy
})
render(h(Comp), nodeOps.createElement('div'))
expect(fooSpy).toHaveBeenCalled()
})
// for v-model:foo-bar usage in DOM templates
test('trigger hyphenated events for update:xxx events', () => {
const Foo = defineComponent({
render() {},
created() {
this.$emit('update:fooProp')
this.$emit('update:barProp')
}
})
const fooSpy = jest.fn()
const barSpy = jest.fn()
const Comp = () =>
h(Foo, {
'onUpdate:fooProp': fooSpy,
'onUpdate:bar-prop': barSpy
})
render(h(Comp), nodeOps.createElement('div'))
expect(fooSpy).toHaveBeenCalled()
expect(barSpy).toHaveBeenCalled()
})
test('should trigger array of listeners', async () => {
const Child = defineComponent({
setup(_, { emit }) {
emit('foo', 1)
return () => h('div')
}
})
const fn1 = jest.fn()
const fn2 = jest.fn()
const App = {
setup() {
return () =>
h(Child, {
onFoo: [fn1, fn2]
})
}
}
render(h(App), nodeOps.createElement('div'))
expect(fn1).toHaveBeenCalledTimes(1)
expect(fn1).toHaveBeenCalledWith(1)
expect(fn2).toHaveBeenCalledTimes(1)
expect(fn1).toHaveBeenCalledWith(1)
})
test('warning for undeclared event (array)', () => {
const Foo = defineComponent({
emits: ['foo'],
render() {},
created() {
// @ts-ignore
this.$emit('bar')
}
})
render(h(Foo), nodeOps.createElement('div'))
expect(
`Component emitted event "bar" but it is neither declared`
).toHaveBeenWarned()
})
test('warning for undeclared event (object)', () => {
const Foo = defineComponent({
emits: {
foo: null
},
render() {},
created() {
// @ts-ignore
this.$emit('bar')
}
})
render(h(Foo), nodeOps.createElement('div'))
expect(
`Component emitted event "bar" but it is neither declared`
).toHaveBeenWarned()
})
test('should not warn if has equivalent onXXX prop', () => {
const Foo = defineComponent({
props: ['onFoo'],
emits: [],
render() {},
created() {
// @ts-ignore
this.$emit('foo')
}
})
render(h(Foo), nodeOps.createElement('div'))
expect(
`Component emitted event "bar" but it is neither declared`
).not.toHaveBeenWarned()
})
test('validator warning', () => {
const Foo = defineComponent({
emits: {
foo: (arg: number) => arg > 0
},
render() {},
created() {
this.$emit('foo', -1)
}
})
render(h(Foo), nodeOps.createElement('div'))
expect(`event validation failed for event "foo"`).toHaveBeenWarned()
})
test('merging from mixins', () => {
const mixin = {
emits: {
foo: (arg: number) => arg > 0
}
}
const Foo = defineComponent({
mixins: [mixin],
render() {},
created() {
this.$emit('foo', -1)
}
})
render(h(Foo), nodeOps.createElement('div'))
expect(`event validation failed for event "foo"`).toHaveBeenWarned()
})
test('.once', () => {
const Foo = defineComponent({
render() {},
emits: {
foo: null
},
created() {
this.$emit('foo')
this.$emit('foo')
}
})
const fn = jest.fn()
render(
h(Foo, {
onFooOnce: fn
}),
nodeOps.createElement('div')
)
expect(fn).toHaveBeenCalledTimes(1)
})
test('.once with normal listener of the same name', () => {
const Foo = defineComponent({
render() {},
emits: {
foo: null
},
created() {
this.$emit('foo')
this.$emit('foo')
}
})
const onFoo = jest.fn()
const onFooOnce = jest.fn()
render(
h(Foo, {
onFoo,
onFooOnce
}),
nodeOps.createElement('div')
)
expect(onFoo).toHaveBeenCalledTimes(2)
expect(onFooOnce).toHaveBeenCalledTimes(1)
})
test('.number modifier should work with v-model on component', () => {
const Foo = defineComponent({
render() {},
created() {
this.$emit('update:modelValue', '1')
this.$emit('update:foo', '2')
}
})
const fn1 = jest.fn()
const fn2 = jest.fn()
const Comp = () =>
h(Foo, {
modelValue: null,
modelModifiers: { number: true },
'onUpdate:modelValue': fn1,
foo: null,
fooModifiers: { number: true },
'onUpdate:foo': fn2
})
render(h(Comp), nodeOps.createElement('div'))
expect(fn1).toHaveBeenCalledTimes(1)
expect(fn1).toHaveBeenCalledWith(1)
expect(fn2).toHaveBeenCalledTimes(1)
expect(fn2).toHaveBeenCalledWith(2)
})
test('.trim modifier should work with v-model on component', () => {
const Foo = defineComponent({
render() {},
created() {
this.$emit('update:modelValue', ' one ')
this.$emit('update:foo', ' two ')
}
})
const fn1 = jest.fn()
const fn2 = jest.fn()
const Comp = () =>
h(Foo, {
modelValue: null,
modelModifiers: { trim: true },
'onUpdate:modelValue': fn1,
foo: null,
fooModifiers: { trim: true },
'onUpdate:foo': fn2
})
render(h(Comp), nodeOps.createElement('div'))
expect(fn1).toHaveBeenCalledTimes(1)
expect(fn1).toHaveBeenCalledWith('one')
expect(fn2).toHaveBeenCalledTimes(1)
expect(fn2).toHaveBeenCalledWith('two')
})
test('isEmitListener', () => {
const options = { click: null }
expect(isEmitListener(options, 'onClick')).toBe(true)
expect(isEmitListener(options, 'onclick')).toBe(false)
expect(isEmitListener(options, 'onBlick')).toBe(false)
// .once listeners
expect(isEmitListener(options, 'onClickOnce')).toBe(true)
expect(isEmitListener(options, 'onclickOnce')).toBe(false)
})
})
| packages/runtime-core/__tests__/componentEmits.spec.ts | 1 | https://github.com/vuejs/core/commit/3532b2b0213268a285cacce9b38f806e6af29a61 | [
0.9984347224235535,
0.0668720230460167,
0.00016625455464236438,
0.0001735821133479476,
0.2489503175020218
] |
{
"id": 0,
"code_window": [
" expect(fn2).toHaveBeenCalledWith('two')\n",
" })\n",
"\n",
" test('isEmitListener', () => {\n",
" const options = { click: null }\n",
" expect(isEmitListener(options, 'onClick')).toBe(true)\n",
" expect(isEmitListener(options, 'onclick')).toBe(false)\n",
" expect(isEmitListener(options, 'onBlick')).toBe(false)\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" const options = {\n",
" click: null,\n",
" 'test-event': null,\n",
" fooBar: null,\n",
" FooBaz: null\n",
" }\n"
],
"file_path": "packages/runtime-core/__tests__/componentEmits.spec.ts",
"type": "replace",
"edit_start_line_idx": 285
} | if (!/yarn\.js$/.test(process.env.npm_execpath || '')) {
console.warn(
'\u001b[33mThis repository requires Yarn 1.x for scripts to work properly.\u001b[39m\n'
)
process.exit(1)
}
| scripts/checkYarn.js | 0 | https://github.com/vuejs/core/commit/3532b2b0213268a285cacce9b38f806e6af29a61 | [
0.00017333310097455978,
0.00017333310097455978,
0.00017333310097455978,
0.00017333310097455978,
0
] |
{
"id": 0,
"code_window": [
" expect(fn2).toHaveBeenCalledWith('two')\n",
" })\n",
"\n",
" test('isEmitListener', () => {\n",
" const options = { click: null }\n",
" expect(isEmitListener(options, 'onClick')).toBe(true)\n",
" expect(isEmitListener(options, 'onclick')).toBe(false)\n",
" expect(isEmitListener(options, 'onBlick')).toBe(false)\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" const options = {\n",
" click: null,\n",
" 'test-event': null,\n",
" fooBar: null,\n",
" FooBaz: null\n",
" }\n"
],
"file_path": "packages/runtime-core/__tests__/componentEmits.spec.ts",
"type": "replace",
"edit_start_line_idx": 285
} | import { createApp, createVNode } from 'vue'
import { renderToString } from '../src/renderToString'
describe('ssr: dynamic component', () => {
test('resolved to component', async () => {
expect(
await renderToString(
createApp({
components: {
one: {
template: `<div><slot/></div>`
}
},
template: `<component :is="'one'"><span>slot</span></component>`
})
)
).toBe(`<div><!--[--><span>slot</span><!--]--></div>`)
})
test('resolve to element', async () => {
expect(
await renderToString(
createApp({
template: `<component :is="'p'"><span>slot</span></component>`
})
)
).toBe(`<p><span>slot</span></p>`)
})
test('resolve to component vnode', async () => {
const Child = {
props: ['id'],
template: `<div>{{ id }}<slot/></div>`
}
expect(
await renderToString(
createApp({
setup() {
return {
vnode: createVNode(Child, { id: 'test' })
}
},
template: `<component :is="vnode"><span>slot</span></component>`
})
)
).toBe(`<div>test<!--[--><span>slot</span><!--]--></div>`)
})
test('resolve to element vnode', async () => {
expect(
await renderToString(
createApp({
setup() {
return {
vnode: createVNode('div', { id: 'test' })
}
},
template: `<component :is="vnode"><span>slot</span></component>`
})
)
).toBe(`<div id="test"><span>slot</span></div>`)
})
})
| packages/server-renderer/__tests__/ssrDynamicComponent.spec.ts | 0 | https://github.com/vuejs/core/commit/3532b2b0213268a285cacce9b38f806e6af29a61 | [
0.0001767508510965854,
0.00017396120529156178,
0.00017141587159130722,
0.00017393610323779285,
0.0000018449019307809067
] |
{
"id": 0,
"code_window": [
" expect(fn2).toHaveBeenCalledWith('two')\n",
" })\n",
"\n",
" test('isEmitListener', () => {\n",
" const options = { click: null }\n",
" expect(isEmitListener(options, 'onClick')).toBe(true)\n",
" expect(isEmitListener(options, 'onclick')).toBe(false)\n",
" expect(isEmitListener(options, 'onBlick')).toBe(false)\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" const options = {\n",
" click: null,\n",
" 'test-event': null,\n",
" fooBar: null,\n",
" FooBaz: null\n",
" }\n"
],
"file_path": "packages/runtime-core/__tests__/componentEmits.spec.ts",
"type": "replace",
"edit_start_line_idx": 285
} | import { compile } from '../src'
const scopeId = 'data-v-xxxxxxx'
describe('ssr: scopeId', () => {
test('basic', () => {
expect(
compile(`<div><span>hello</span></div>`, {
scopeId,
mode: 'module'
}).code
).toMatchInlineSnapshot(`
"import { withScopeId as _withScopeId } from \\"vue\\"
import { ssrRenderAttrs as _ssrRenderAttrs } from \\"@vue/server-renderer\\"
const _withId = /*#__PURE__*/_withScopeId(\\"data-v-xxxxxxx\\")
export const ssrRender = /*#__PURE__*/_withId((_ctx, _push, _parent, _attrs) => {
_push(\`<div\${_ssrRenderAttrs(_attrs)} data-v-xxxxxxx><span data-v-xxxxxxx>hello</span></div>\`)
})"
`)
})
test('inside slots (only text)', () => {
// should have no branching inside slot
expect(
compile(`<foo>foo</foo>`, {
scopeId,
mode: 'module'
}).code
).toMatchInlineSnapshot(`
"import { resolveComponent as _resolveComponent, withCtx as _withCtx, createTextVNode as _createTextVNode, withScopeId as _withScopeId } from \\"vue\\"
import { ssrRenderComponent as _ssrRenderComponent } from \\"@vue/server-renderer\\"
const _withId = /*#__PURE__*/_withScopeId(\\"data-v-xxxxxxx\\")
export const ssrRender = /*#__PURE__*/_withId((_ctx, _push, _parent, _attrs) => {
const _component_foo = _resolveComponent(\\"foo\\")
_push(_ssrRenderComponent(_component_foo, _attrs, {
default: _withId((_, _push, _parent, _scopeId) => {
if (_push) {
_push(\`foo\`)
} else {
return [
_createTextVNode(\\"foo\\")
]
}
}),
_: 1
}, _parent))
})"
`)
})
test('inside slots (with elements)', () => {
expect(
compile(`<foo><span>hello</span></foo>`, {
scopeId,
mode: 'module'
}).code
).toMatchInlineSnapshot(`
"import { resolveComponent as _resolveComponent, withCtx as _withCtx, createVNode as _createVNode, withScopeId as _withScopeId } from \\"vue\\"
import { ssrRenderComponent as _ssrRenderComponent } from \\"@vue/server-renderer\\"
const _withId = /*#__PURE__*/_withScopeId(\\"data-v-xxxxxxx\\")
export const ssrRender = /*#__PURE__*/_withId((_ctx, _push, _parent, _attrs) => {
const _component_foo = _resolveComponent(\\"foo\\")
_push(_ssrRenderComponent(_component_foo, _attrs, {
default: _withId((_, _push, _parent, _scopeId) => {
if (_push) {
_push(\`<span data-v-xxxxxxx\${_scopeId}>hello</span>\`)
} else {
return [
_createVNode(\\"span\\", null, \\"hello\\")
]
}
}),
_: 1
}, _parent))
})"
`)
})
test('nested slots', () => {
expect(
compile(`<foo><span>hello</span><bar><span/></bar></foo>`, {
scopeId,
mode: 'module'
}).code
).toMatchInlineSnapshot(`
"import { resolveComponent as _resolveComponent, withCtx as _withCtx, createVNode as _createVNode, withScopeId as _withScopeId } from \\"vue\\"
import { ssrRenderComponent as _ssrRenderComponent } from \\"@vue/server-renderer\\"
const _withId = /*#__PURE__*/_withScopeId(\\"data-v-xxxxxxx\\")
export const ssrRender = /*#__PURE__*/_withId((_ctx, _push, _parent, _attrs) => {
const _component_foo = _resolveComponent(\\"foo\\")
const _component_bar = _resolveComponent(\\"bar\\")
_push(_ssrRenderComponent(_component_foo, _attrs, {
default: _withId((_, _push, _parent, _scopeId) => {
if (_push) {
_push(\`<span data-v-xxxxxxx\${_scopeId}>hello</span>\`)
_push(_ssrRenderComponent(_component_bar, null, {
default: _withId((_, _push, _parent, _scopeId) => {
if (_push) {
_push(\`<span data-v-xxxxxxx\${_scopeId}></span>\`)
} else {
return [
_createVNode(\\"span\\")
]
}
}),
_: 1
}, _parent))
} else {
return [
_createVNode(\\"span\\", null, \\"hello\\"),
_createVNode(_component_bar, null, {
default: _withId(() => [
_createVNode(\\"span\\")
]),
_: 1
})
]
}
}),
_: 1
}, _parent))
})"
`)
})
})
| packages/compiler-ssr/__tests__/ssrScopeId.spec.ts | 0 | https://github.com/vuejs/core/commit/3532b2b0213268a285cacce9b38f806e6af29a61 | [
0.00017547163588460535,
0.00017303308413829654,
0.0001694538805168122,
0.00017312070121988654,
0.0000016192730072361883
] |
{
"id": 1,
"code_window": [
" // .once listeners\n",
" expect(isEmitListener(options, 'onClickOnce')).toBe(true)\n",
" expect(isEmitListener(options, 'onclickOnce')).toBe(false)\n",
" })\n",
"})"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep"
],
"after_edit": [
" // kebab-case option\n",
" expect(isEmitListener(options, 'onTestEvent')).toBe(true)\n",
" // camelCase option\n",
" expect(isEmitListener(options, 'onFooBar')).toBe(true)\n",
" // PascalCase option\n",
" expect(isEmitListener(options, 'onFooBaz')).toBe(true)\n"
],
"file_path": "packages/runtime-core/__tests__/componentEmits.spec.ts",
"type": "add",
"edit_start_line_idx": 292
} | // Note: emits and listener fallthrough is tested in
// ./rendererAttrsFallthrough.spec.ts.
import { render, defineComponent, h, nodeOps } from '@vue/runtime-test'
import { isEmitListener } from '../src/componentEmits'
describe('component: emit', () => {
test('trigger handlers', () => {
const Foo = defineComponent({
render() {},
created() {
// the `emit` function is bound on component instances
this.$emit('foo')
this.$emit('bar')
this.$emit('!baz')
}
})
const onfoo = jest.fn()
const onBar = jest.fn()
const onBaz = jest.fn()
const Comp = () => h(Foo, { onfoo, onBar, ['on!baz']: onBaz })
render(h(Comp), nodeOps.createElement('div'))
expect(onfoo).not.toHaveBeenCalled()
// only capitalized or special chars are considered event listeners
expect(onBar).toHaveBeenCalled()
expect(onBaz).toHaveBeenCalled()
})
test('trigger camelize event', () => {
const Foo = defineComponent({
render() {},
created() {
this.$emit('test-event')
}
})
const fooSpy = jest.fn()
const Comp = () =>
h(Foo, {
onTestEvent: fooSpy
})
render(h(Comp), nodeOps.createElement('div'))
expect(fooSpy).toHaveBeenCalled()
})
// for v-model:foo-bar usage in DOM templates
test('trigger hyphenated events for update:xxx events', () => {
const Foo = defineComponent({
render() {},
created() {
this.$emit('update:fooProp')
this.$emit('update:barProp')
}
})
const fooSpy = jest.fn()
const barSpy = jest.fn()
const Comp = () =>
h(Foo, {
'onUpdate:fooProp': fooSpy,
'onUpdate:bar-prop': barSpy
})
render(h(Comp), nodeOps.createElement('div'))
expect(fooSpy).toHaveBeenCalled()
expect(barSpy).toHaveBeenCalled()
})
test('should trigger array of listeners', async () => {
const Child = defineComponent({
setup(_, { emit }) {
emit('foo', 1)
return () => h('div')
}
})
const fn1 = jest.fn()
const fn2 = jest.fn()
const App = {
setup() {
return () =>
h(Child, {
onFoo: [fn1, fn2]
})
}
}
render(h(App), nodeOps.createElement('div'))
expect(fn1).toHaveBeenCalledTimes(1)
expect(fn1).toHaveBeenCalledWith(1)
expect(fn2).toHaveBeenCalledTimes(1)
expect(fn1).toHaveBeenCalledWith(1)
})
test('warning for undeclared event (array)', () => {
const Foo = defineComponent({
emits: ['foo'],
render() {},
created() {
// @ts-ignore
this.$emit('bar')
}
})
render(h(Foo), nodeOps.createElement('div'))
expect(
`Component emitted event "bar" but it is neither declared`
).toHaveBeenWarned()
})
test('warning for undeclared event (object)', () => {
const Foo = defineComponent({
emits: {
foo: null
},
render() {},
created() {
// @ts-ignore
this.$emit('bar')
}
})
render(h(Foo), nodeOps.createElement('div'))
expect(
`Component emitted event "bar" but it is neither declared`
).toHaveBeenWarned()
})
test('should not warn if has equivalent onXXX prop', () => {
const Foo = defineComponent({
props: ['onFoo'],
emits: [],
render() {},
created() {
// @ts-ignore
this.$emit('foo')
}
})
render(h(Foo), nodeOps.createElement('div'))
expect(
`Component emitted event "bar" but it is neither declared`
).not.toHaveBeenWarned()
})
test('validator warning', () => {
const Foo = defineComponent({
emits: {
foo: (arg: number) => arg > 0
},
render() {},
created() {
this.$emit('foo', -1)
}
})
render(h(Foo), nodeOps.createElement('div'))
expect(`event validation failed for event "foo"`).toHaveBeenWarned()
})
test('merging from mixins', () => {
const mixin = {
emits: {
foo: (arg: number) => arg > 0
}
}
const Foo = defineComponent({
mixins: [mixin],
render() {},
created() {
this.$emit('foo', -1)
}
})
render(h(Foo), nodeOps.createElement('div'))
expect(`event validation failed for event "foo"`).toHaveBeenWarned()
})
test('.once', () => {
const Foo = defineComponent({
render() {},
emits: {
foo: null
},
created() {
this.$emit('foo')
this.$emit('foo')
}
})
const fn = jest.fn()
render(
h(Foo, {
onFooOnce: fn
}),
nodeOps.createElement('div')
)
expect(fn).toHaveBeenCalledTimes(1)
})
test('.once with normal listener of the same name', () => {
const Foo = defineComponent({
render() {},
emits: {
foo: null
},
created() {
this.$emit('foo')
this.$emit('foo')
}
})
const onFoo = jest.fn()
const onFooOnce = jest.fn()
render(
h(Foo, {
onFoo,
onFooOnce
}),
nodeOps.createElement('div')
)
expect(onFoo).toHaveBeenCalledTimes(2)
expect(onFooOnce).toHaveBeenCalledTimes(1)
})
test('.number modifier should work with v-model on component', () => {
const Foo = defineComponent({
render() {},
created() {
this.$emit('update:modelValue', '1')
this.$emit('update:foo', '2')
}
})
const fn1 = jest.fn()
const fn2 = jest.fn()
const Comp = () =>
h(Foo, {
modelValue: null,
modelModifiers: { number: true },
'onUpdate:modelValue': fn1,
foo: null,
fooModifiers: { number: true },
'onUpdate:foo': fn2
})
render(h(Comp), nodeOps.createElement('div'))
expect(fn1).toHaveBeenCalledTimes(1)
expect(fn1).toHaveBeenCalledWith(1)
expect(fn2).toHaveBeenCalledTimes(1)
expect(fn2).toHaveBeenCalledWith(2)
})
test('.trim modifier should work with v-model on component', () => {
const Foo = defineComponent({
render() {},
created() {
this.$emit('update:modelValue', ' one ')
this.$emit('update:foo', ' two ')
}
})
const fn1 = jest.fn()
const fn2 = jest.fn()
const Comp = () =>
h(Foo, {
modelValue: null,
modelModifiers: { trim: true },
'onUpdate:modelValue': fn1,
foo: null,
fooModifiers: { trim: true },
'onUpdate:foo': fn2
})
render(h(Comp), nodeOps.createElement('div'))
expect(fn1).toHaveBeenCalledTimes(1)
expect(fn1).toHaveBeenCalledWith('one')
expect(fn2).toHaveBeenCalledTimes(1)
expect(fn2).toHaveBeenCalledWith('two')
})
test('isEmitListener', () => {
const options = { click: null }
expect(isEmitListener(options, 'onClick')).toBe(true)
expect(isEmitListener(options, 'onclick')).toBe(false)
expect(isEmitListener(options, 'onBlick')).toBe(false)
// .once listeners
expect(isEmitListener(options, 'onClickOnce')).toBe(true)
expect(isEmitListener(options, 'onclickOnce')).toBe(false)
})
})
| packages/runtime-core/__tests__/componentEmits.spec.ts | 1 | https://github.com/vuejs/core/commit/3532b2b0213268a285cacce9b38f806e6af29a61 | [
0.7324203252792358,
0.024678895249962807,
0.00016599603986833245,
0.0001727040798868984,
0.13142526149749756
] |
{
"id": 1,
"code_window": [
" // .once listeners\n",
" expect(isEmitListener(options, 'onClickOnce')).toBe(true)\n",
" expect(isEmitListener(options, 'onclickOnce')).toBe(false)\n",
" })\n",
"})"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep"
],
"after_edit": [
" // kebab-case option\n",
" expect(isEmitListener(options, 'onTestEvent')).toBe(true)\n",
" // camelCase option\n",
" expect(isEmitListener(options, 'onFooBar')).toBe(true)\n",
" // PascalCase option\n",
" expect(isEmitListener(options, 'onFooBaz')).toBe(true)\n"
],
"file_path": "packages/runtime-core/__tests__/componentEmits.spec.ts",
"type": "add",
"edit_start_line_idx": 292
} | import { isObject, toRawType, def } from '@vue/shared'
import {
mutableHandlers,
readonlyHandlers,
shallowReactiveHandlers,
shallowReadonlyHandlers
} from './baseHandlers'
import {
mutableCollectionHandlers,
readonlyCollectionHandlers,
shallowCollectionHandlers
} from './collectionHandlers'
import { UnwrapRef, Ref } from './ref'
export const enum ReactiveFlags {
SKIP = '__v_skip',
IS_REACTIVE = '__v_isReactive',
IS_READONLY = '__v_isReadonly',
RAW = '__v_raw'
}
export interface Target {
[ReactiveFlags.SKIP]?: boolean
[ReactiveFlags.IS_REACTIVE]?: boolean
[ReactiveFlags.IS_READONLY]?: boolean
[ReactiveFlags.RAW]?: any
}
export const reactiveMap = new WeakMap<Target, any>()
export const readonlyMap = new WeakMap<Target, any>()
const enum TargetType {
INVALID = 0,
COMMON = 1,
COLLECTION = 2
}
function targetTypeMap(rawType: string) {
switch (rawType) {
case 'Object':
case 'Array':
return TargetType.COMMON
case 'Map':
case 'Set':
case 'WeakMap':
case 'WeakSet':
return TargetType.COLLECTION
default:
return TargetType.INVALID
}
}
function getTargetType(value: Target) {
return value[ReactiveFlags.SKIP] || !Object.isExtensible(value)
? TargetType.INVALID
: targetTypeMap(toRawType(value))
}
// only unwrap nested ref
type UnwrapNestedRefs<T> = T extends Ref ? T : UnwrapRef<T>
/**
* Creates a reactive copy of the original object.
*
* The reactive conversion is "deep"—it affects all nested properties. In the
* ES2015 Proxy based implementation, the returned proxy is **not** equal to the
* original object. It is recommended to work exclusively with the reactive
* proxy and avoid relying on the original object.
*
* A reactive object also automatically unwraps refs contained in it, so you
* don't need to use `.value` when accessing and mutating their value:
*
* ```js
* const count = ref(0)
* const obj = reactive({
* count
* })
*
* obj.count++
* obj.count // -> 1
* count.value // -> 1
* ```
*/
export function reactive<T extends object>(target: T): UnwrapNestedRefs<T>
export function reactive(target: object) {
// if trying to observe a readonly proxy, return the readonly version.
if (target && (target as Target)[ReactiveFlags.IS_READONLY]) {
return target
}
return createReactiveObject(
target,
false,
mutableHandlers,
mutableCollectionHandlers
)
}
/**
* Return a shallowly-reactive copy of the original object, where only the root
* level properties are reactive. It also does not auto-unwrap refs (even at the
* root level).
*/
export function shallowReactive<T extends object>(target: T): T {
return createReactiveObject(
target,
false,
shallowReactiveHandlers,
shallowCollectionHandlers
)
}
type Primitive = string | number | boolean | bigint | symbol | undefined | null
type Builtin = Primitive | Function | Date | Error | RegExp
export type DeepReadonly<T> = T extends Builtin
? T
: T extends Map<infer K, infer V>
? ReadonlyMap<DeepReadonly<K>, DeepReadonly<V>>
: T extends ReadonlyMap<infer K, infer V>
? ReadonlyMap<DeepReadonly<K>, DeepReadonly<V>>
: T extends WeakMap<infer K, infer V>
? WeakMap<DeepReadonly<K>, DeepReadonly<V>>
: T extends Set<infer U>
? ReadonlySet<DeepReadonly<U>>
: T extends ReadonlySet<infer U>
? ReadonlySet<DeepReadonly<U>>
: T extends WeakSet<infer U>
? WeakSet<DeepReadonly<U>>
: T extends Promise<infer U>
? Promise<DeepReadonly<U>>
: T extends {}
? { readonly [K in keyof T]: DeepReadonly<T[K]> }
: Readonly<T>
/**
* Creates a readonly copy of the original object. Note the returned copy is not
* made reactive, but `readonly` can be called on an already reactive object.
*/
export function readonly<T extends object>(
target: T
): DeepReadonly<UnwrapNestedRefs<T>> {
return createReactiveObject(
target,
true,
readonlyHandlers,
readonlyCollectionHandlers
)
}
/**
* Returns a reactive-copy of the original object, where only the root level
* properties are readonly, and does NOT unwrap refs nor recursively convert
* returned properties.
* This is used for creating the props proxy object for stateful components.
*/
export function shallowReadonly<T extends object>(
target: T
): Readonly<{ [K in keyof T]: UnwrapNestedRefs<T[K]> }> {
return createReactiveObject(
target,
true,
shallowReadonlyHandlers,
readonlyCollectionHandlers
)
}
function createReactiveObject(
target: Target,
isReadonly: boolean,
baseHandlers: ProxyHandler<any>,
collectionHandlers: ProxyHandler<any>
) {
if (!isObject(target)) {
if (__DEV__) {
console.warn(`value cannot be made reactive: ${String(target)}`)
}
return target
}
// target is already a Proxy, return it.
// exception: calling readonly() on a reactive object
if (
target[ReactiveFlags.RAW] &&
!(isReadonly && target[ReactiveFlags.IS_REACTIVE])
) {
return target
}
// target already has corresponding Proxy
const proxyMap = isReadonly ? readonlyMap : reactiveMap
const existingProxy = proxyMap.get(target)
if (existingProxy) {
return existingProxy
}
// only a whitelist of value types can be observed.
const targetType = getTargetType(target)
if (targetType === TargetType.INVALID) {
return target
}
const proxy = new Proxy(
target,
targetType === TargetType.COLLECTION ? collectionHandlers : baseHandlers
)
proxyMap.set(target, proxy)
return proxy
}
export function isReactive(value: unknown): boolean {
if (isReadonly(value)) {
return isReactive((value as Target)[ReactiveFlags.RAW])
}
return !!(value && (value as Target)[ReactiveFlags.IS_REACTIVE])
}
export function isReadonly(value: unknown): boolean {
return !!(value && (value as Target)[ReactiveFlags.IS_READONLY])
}
export function isProxy(value: unknown): boolean {
return isReactive(value) || isReadonly(value)
}
export function toRaw<T>(observed: T): T {
return (
(observed && toRaw((observed as Target)[ReactiveFlags.RAW])) || observed
)
}
export function markRaw<T extends object>(value: T): T {
def(value, ReactiveFlags.SKIP, true)
return value
}
| packages/reactivity/src/reactive.ts | 0 | https://github.com/vuejs/core/commit/3532b2b0213268a285cacce9b38f806e6af29a61 | [
0.00017812159785535187,
0.00017055925854947418,
0.00016021884221117944,
0.00017088760796468705,
0.000004698547854786739
] |
{
"id": 1,
"code_window": [
" // .once listeners\n",
" expect(isEmitListener(options, 'onClickOnce')).toBe(true)\n",
" expect(isEmitListener(options, 'onclickOnce')).toBe(false)\n",
" })\n",
"})"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep"
],
"after_edit": [
" // kebab-case option\n",
" expect(isEmitListener(options, 'onTestEvent')).toBe(true)\n",
" // camelCase option\n",
" expect(isEmitListener(options, 'onFooBar')).toBe(true)\n",
" // PascalCase option\n",
" expect(isEmitListener(options, 'onFooBaz')).toBe(true)\n"
],
"file_path": "packages/runtime-core/__tests__/componentEmits.spec.ts",
"type": "add",
"edit_start_line_idx": 292
} | import { DirectiveTransform } from '../transform'
import {
createSimpleExpression,
createObjectProperty,
createCompoundExpression,
NodeTypes,
Property,
ElementTypes,
ExpressionNode,
ConstantTypes
} from '../ast'
import { createCompilerError, ErrorCodes } from '../errors'
import {
isMemberExpression,
isSimpleIdentifier,
hasScopeRef,
isStaticExp
} from '../utils'
import { IS_REF } from '../runtimeHelpers'
import { BindingTypes } from '../options'
export const transformModel: DirectiveTransform = (dir, node, context) => {
const { exp, arg } = dir
if (!exp) {
context.onError(
createCompilerError(ErrorCodes.X_V_MODEL_NO_EXPRESSION, dir.loc)
)
return createTransformProps()
}
const rawExp = exp.loc.source
const expString =
exp.type === NodeTypes.SIMPLE_EXPRESSION ? exp.content : rawExp
// im SFC <script setup> inline mode, the exp may have been transformed into
// _unref(exp)
const bindingType = context.bindingMetadata[rawExp]
const maybeRef =
!__BROWSER__ &&
context.inline &&
bindingType &&
bindingType !== BindingTypes.SETUP_CONST
if (!isMemberExpression(expString) && !maybeRef) {
context.onError(
createCompilerError(ErrorCodes.X_V_MODEL_MALFORMED_EXPRESSION, exp.loc)
)
return createTransformProps()
}
if (
!__BROWSER__ &&
context.prefixIdentifiers &&
isSimpleIdentifier(expString) &&
context.identifiers[expString]
) {
context.onError(
createCompilerError(ErrorCodes.X_V_MODEL_ON_SCOPE_VARIABLE, exp.loc)
)
return createTransformProps()
}
const propName = arg ? arg : createSimpleExpression('modelValue', true)
const eventName = arg
? isStaticExp(arg)
? `onUpdate:${arg.content}`
: createCompoundExpression(['"onUpdate:" + ', arg])
: `onUpdate:modelValue`
let assignmentExp: ExpressionNode
const eventArg = context.isTS ? `($event: any)` : `$event`
if (maybeRef) {
if (bindingType === BindingTypes.SETUP_REF) {
// v-model used on known ref.
assignmentExp = createCompoundExpression([
`${eventArg} => (`,
createSimpleExpression(rawExp, false, exp.loc),
`.value = $event)`
])
} else {
// v-model used on a potentially ref binding in <script setup> inline mode.
// the assignment needs to check whether the binding is actually a ref.
const altAssignment =
bindingType === BindingTypes.SETUP_LET ? `${rawExp} = $event` : `null`
assignmentExp = createCompoundExpression([
`${eventArg} => (${context.helperString(IS_REF)}(${rawExp}) ? `,
createSimpleExpression(rawExp, false, exp.loc),
`.value = $event : ${altAssignment})`
])
}
} else {
assignmentExp = createCompoundExpression([
`${eventArg} => (`,
exp,
` = $event)`
])
}
const props = [
// modelValue: foo
createObjectProperty(propName, dir.exp!),
// "onUpdate:modelValue": $event => (foo = $event)
createObjectProperty(eventName, assignmentExp)
]
// cache v-model handler if applicable (when it doesn't refer any scope vars)
if (
!__BROWSER__ &&
context.prefixIdentifiers &&
context.cacheHandlers &&
!hasScopeRef(exp, context.identifiers)
) {
props[1].value = context.cache(props[1].value)
}
// modelModifiers: { foo: true, "bar-baz": true }
if (dir.modifiers.length && node.tagType === ElementTypes.COMPONENT) {
const modifiers = dir.modifiers
.map(m => (isSimpleIdentifier(m) ? m : JSON.stringify(m)) + `: true`)
.join(`, `)
const modifiersKey = arg
? isStaticExp(arg)
? `${arg.content}Modifiers`
: createCompoundExpression([arg, ' + "Modifiers"'])
: `modelModifiers`
props.push(
createObjectProperty(
modifiersKey,
createSimpleExpression(
`{ ${modifiers} }`,
false,
dir.loc,
ConstantTypes.CAN_HOIST
)
)
)
}
return createTransformProps(props)
}
function createTransformProps(props: Property[] = []) {
return { props }
}
| packages/compiler-core/src/transforms/vModel.ts | 0 | https://github.com/vuejs/core/commit/3532b2b0213268a285cacce9b38f806e6af29a61 | [
0.00017797933833207935,
0.00017569227202329785,
0.00017328915419057012,
0.00017572211800143123,
0.000001449094042982324
] |
{
"id": 1,
"code_window": [
" // .once listeners\n",
" expect(isEmitListener(options, 'onClickOnce')).toBe(true)\n",
" expect(isEmitListener(options, 'onclickOnce')).toBe(false)\n",
" })\n",
"})"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep"
],
"after_edit": [
" // kebab-case option\n",
" expect(isEmitListener(options, 'onTestEvent')).toBe(true)\n",
" // camelCase option\n",
" expect(isEmitListener(options, 'onFooBar')).toBe(true)\n",
" // PascalCase option\n",
" expect(isEmitListener(options, 'onFooBaz')).toBe(true)\n"
],
"file_path": "packages/runtime-core/__tests__/componentEmits.spec.ts",
"type": "add",
"edit_start_line_idx": 292
} | import {
baseParse as parse,
transform,
CompilerOptions,
generate
} from '@vue/compiler-core'
import { transformModel } from '../../src/transforms/vModel'
import { transformElement } from '../../../compiler-core/src/transforms/transformElement'
import { DOMErrorCodes } from '../../src/errors'
import {
V_MODEL_CHECKBOX,
V_MODEL_DYNAMIC,
V_MODEL_RADIO,
V_MODEL_SELECT,
V_MODEL_TEXT
} from '../../src/runtimeHelpers'
function transformWithModel(template: string, options: CompilerOptions = {}) {
const ast = parse(template)
transform(ast, {
nodeTransforms: [transformElement],
directiveTransforms: {
model: transformModel
},
...options
})
return ast
}
describe('compiler: transform v-model', () => {
test('simple expression', () => {
const root = transformWithModel('<input v-model="model" />')
expect(root.helpers).toContain(V_MODEL_TEXT)
expect(generate(root).code).toMatchSnapshot()
})
test('simple expression for input (text)', () => {
const root = transformWithModel('<input type="text" v-model="model" />')
expect(root.helpers).toContain(V_MODEL_TEXT)
expect(generate(root).code).toMatchSnapshot()
})
test('simple expression for input (radio)', () => {
const root = transformWithModel('<input type="radio" v-model="model" />')
expect(root.helpers).toContain(V_MODEL_RADIO)
expect(generate(root).code).toMatchSnapshot()
})
test('simple expression for input (checkbox)', () => {
const root = transformWithModel('<input type="checkbox" v-model="model" />')
expect(root.helpers).toContain(V_MODEL_CHECKBOX)
expect(generate(root).code).toMatchSnapshot()
})
test('simple expression for input (dynamic type)', () => {
const root = transformWithModel('<input :type="foo" v-model="model" />')
expect(root.helpers).toContain(V_MODEL_DYNAMIC)
expect(generate(root).code).toMatchSnapshot()
})
test('input w/ dynamic v-bind', () => {
const root = transformWithModel('<input v-bind="obj" v-model="model" />')
expect(root.helpers).toContain(V_MODEL_DYNAMIC)
expect(generate(root).code).toMatchSnapshot()
const root2 = transformWithModel(
'<input v-bind:[key]="val" v-model="model" />'
)
expect(root2.helpers).toContain(V_MODEL_DYNAMIC)
expect(generate(root2).code).toMatchSnapshot()
})
test('simple expression for select', () => {
const root = transformWithModel('<select v-model="model" />')
expect(root.helpers).toContain(V_MODEL_SELECT)
expect(generate(root).code).toMatchSnapshot()
})
test('simple expression for textarea', () => {
const root = transformWithModel('<textarea v-model="model" />')
expect(root.helpers).toContain(V_MODEL_TEXT)
expect(generate(root).code).toMatchSnapshot()
})
describe('errors', () => {
test('plain elements with argument', () => {
const onError = jest.fn()
transformWithModel('<input v-model:value="model" />', { onError })
expect(onError).toHaveBeenCalledTimes(1)
expect(onError).toHaveBeenCalledWith(
expect.objectContaining({
code: DOMErrorCodes.X_V_MODEL_ARG_ON_ELEMENT
})
)
})
test('invalid element', () => {
const onError = jest.fn()
transformWithModel('<span v-model="model" />', { onError })
expect(onError).toHaveBeenCalledTimes(1)
expect(onError).toHaveBeenCalledWith(
expect.objectContaining({
code: DOMErrorCodes.X_V_MODEL_ON_INVALID_ELEMENT
})
)
})
test('should allow usage on custom element', () => {
const onError = jest.fn()
const root = transformWithModel('<my-input v-model="model" />', {
onError,
isCustomElement: tag => tag.startsWith('my-')
})
expect(root.helpers).toContain(V_MODEL_TEXT)
expect(onError).not.toHaveBeenCalled()
expect(generate(root).code).toMatchSnapshot()
})
test('should raise error if used file input element', () => {
const onError = jest.fn()
transformWithModel(`<input type="file" v-model="test"/>`, {
onError
})
expect(onError).toHaveBeenCalledWith(
expect.objectContaining({
code: DOMErrorCodes.X_V_MODEL_ON_FILE_INPUT_ELEMENT
})
)
})
})
describe('modifiers', () => {
test('.number', () => {
const root = transformWithModel('<input v-model.number="model" />')
expect(generate(root).code).toMatchSnapshot()
})
test('.trim', () => {
const root = transformWithModel('<input v-model.trim="model" />')
expect(generate(root).code).toMatchSnapshot()
})
test('.lazy', () => {
const root = transformWithModel('<input v-model.lazy="model" />')
expect(generate(root).code).toMatchSnapshot()
})
})
})
| packages/compiler-dom/__tests__/transforms/vModel.spec.ts | 0 | https://github.com/vuejs/core/commit/3532b2b0213268a285cacce9b38f806e6af29a61 | [
0.00020570708147715777,
0.00017728998500388116,
0.00016894520376808941,
0.00017581127758603543,
0.000007760818334645592
] |
{
"id": 2,
"code_window": [
"): boolean {\n",
" if (!options || !isOn(key)) {\n",
" return false\n",
" }\n",
" key = key.replace(/Once$/, '')\n",
" return (\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
" key = key.slice(2).replace(/Once$/, '')\n"
],
"file_path": "packages/runtime-core/src/componentEmits.ts",
"type": "replace",
"edit_start_line_idx": 203
} | // Note: emits and listener fallthrough is tested in
// ./rendererAttrsFallthrough.spec.ts.
import { render, defineComponent, h, nodeOps } from '@vue/runtime-test'
import { isEmitListener } from '../src/componentEmits'
describe('component: emit', () => {
test('trigger handlers', () => {
const Foo = defineComponent({
render() {},
created() {
// the `emit` function is bound on component instances
this.$emit('foo')
this.$emit('bar')
this.$emit('!baz')
}
})
const onfoo = jest.fn()
const onBar = jest.fn()
const onBaz = jest.fn()
const Comp = () => h(Foo, { onfoo, onBar, ['on!baz']: onBaz })
render(h(Comp), nodeOps.createElement('div'))
expect(onfoo).not.toHaveBeenCalled()
// only capitalized or special chars are considered event listeners
expect(onBar).toHaveBeenCalled()
expect(onBaz).toHaveBeenCalled()
})
test('trigger camelize event', () => {
const Foo = defineComponent({
render() {},
created() {
this.$emit('test-event')
}
})
const fooSpy = jest.fn()
const Comp = () =>
h(Foo, {
onTestEvent: fooSpy
})
render(h(Comp), nodeOps.createElement('div'))
expect(fooSpy).toHaveBeenCalled()
})
// for v-model:foo-bar usage in DOM templates
test('trigger hyphenated events for update:xxx events', () => {
const Foo = defineComponent({
render() {},
created() {
this.$emit('update:fooProp')
this.$emit('update:barProp')
}
})
const fooSpy = jest.fn()
const barSpy = jest.fn()
const Comp = () =>
h(Foo, {
'onUpdate:fooProp': fooSpy,
'onUpdate:bar-prop': barSpy
})
render(h(Comp), nodeOps.createElement('div'))
expect(fooSpy).toHaveBeenCalled()
expect(barSpy).toHaveBeenCalled()
})
test('should trigger array of listeners', async () => {
const Child = defineComponent({
setup(_, { emit }) {
emit('foo', 1)
return () => h('div')
}
})
const fn1 = jest.fn()
const fn2 = jest.fn()
const App = {
setup() {
return () =>
h(Child, {
onFoo: [fn1, fn2]
})
}
}
render(h(App), nodeOps.createElement('div'))
expect(fn1).toHaveBeenCalledTimes(1)
expect(fn1).toHaveBeenCalledWith(1)
expect(fn2).toHaveBeenCalledTimes(1)
expect(fn1).toHaveBeenCalledWith(1)
})
test('warning for undeclared event (array)', () => {
const Foo = defineComponent({
emits: ['foo'],
render() {},
created() {
// @ts-ignore
this.$emit('bar')
}
})
render(h(Foo), nodeOps.createElement('div'))
expect(
`Component emitted event "bar" but it is neither declared`
).toHaveBeenWarned()
})
test('warning for undeclared event (object)', () => {
const Foo = defineComponent({
emits: {
foo: null
},
render() {},
created() {
// @ts-ignore
this.$emit('bar')
}
})
render(h(Foo), nodeOps.createElement('div'))
expect(
`Component emitted event "bar" but it is neither declared`
).toHaveBeenWarned()
})
test('should not warn if has equivalent onXXX prop', () => {
const Foo = defineComponent({
props: ['onFoo'],
emits: [],
render() {},
created() {
// @ts-ignore
this.$emit('foo')
}
})
render(h(Foo), nodeOps.createElement('div'))
expect(
`Component emitted event "bar" but it is neither declared`
).not.toHaveBeenWarned()
})
test('validator warning', () => {
const Foo = defineComponent({
emits: {
foo: (arg: number) => arg > 0
},
render() {},
created() {
this.$emit('foo', -1)
}
})
render(h(Foo), nodeOps.createElement('div'))
expect(`event validation failed for event "foo"`).toHaveBeenWarned()
})
test('merging from mixins', () => {
const mixin = {
emits: {
foo: (arg: number) => arg > 0
}
}
const Foo = defineComponent({
mixins: [mixin],
render() {},
created() {
this.$emit('foo', -1)
}
})
render(h(Foo), nodeOps.createElement('div'))
expect(`event validation failed for event "foo"`).toHaveBeenWarned()
})
test('.once', () => {
const Foo = defineComponent({
render() {},
emits: {
foo: null
},
created() {
this.$emit('foo')
this.$emit('foo')
}
})
const fn = jest.fn()
render(
h(Foo, {
onFooOnce: fn
}),
nodeOps.createElement('div')
)
expect(fn).toHaveBeenCalledTimes(1)
})
test('.once with normal listener of the same name', () => {
const Foo = defineComponent({
render() {},
emits: {
foo: null
},
created() {
this.$emit('foo')
this.$emit('foo')
}
})
const onFoo = jest.fn()
const onFooOnce = jest.fn()
render(
h(Foo, {
onFoo,
onFooOnce
}),
nodeOps.createElement('div')
)
expect(onFoo).toHaveBeenCalledTimes(2)
expect(onFooOnce).toHaveBeenCalledTimes(1)
})
test('.number modifier should work with v-model on component', () => {
const Foo = defineComponent({
render() {},
created() {
this.$emit('update:modelValue', '1')
this.$emit('update:foo', '2')
}
})
const fn1 = jest.fn()
const fn2 = jest.fn()
const Comp = () =>
h(Foo, {
modelValue: null,
modelModifiers: { number: true },
'onUpdate:modelValue': fn1,
foo: null,
fooModifiers: { number: true },
'onUpdate:foo': fn2
})
render(h(Comp), nodeOps.createElement('div'))
expect(fn1).toHaveBeenCalledTimes(1)
expect(fn1).toHaveBeenCalledWith(1)
expect(fn2).toHaveBeenCalledTimes(1)
expect(fn2).toHaveBeenCalledWith(2)
})
test('.trim modifier should work with v-model on component', () => {
const Foo = defineComponent({
render() {},
created() {
this.$emit('update:modelValue', ' one ')
this.$emit('update:foo', ' two ')
}
})
const fn1 = jest.fn()
const fn2 = jest.fn()
const Comp = () =>
h(Foo, {
modelValue: null,
modelModifiers: { trim: true },
'onUpdate:modelValue': fn1,
foo: null,
fooModifiers: { trim: true },
'onUpdate:foo': fn2
})
render(h(Comp), nodeOps.createElement('div'))
expect(fn1).toHaveBeenCalledTimes(1)
expect(fn1).toHaveBeenCalledWith('one')
expect(fn2).toHaveBeenCalledTimes(1)
expect(fn2).toHaveBeenCalledWith('two')
})
test('isEmitListener', () => {
const options = { click: null }
expect(isEmitListener(options, 'onClick')).toBe(true)
expect(isEmitListener(options, 'onclick')).toBe(false)
expect(isEmitListener(options, 'onBlick')).toBe(false)
// .once listeners
expect(isEmitListener(options, 'onClickOnce')).toBe(true)
expect(isEmitListener(options, 'onclickOnce')).toBe(false)
})
})
| packages/runtime-core/__tests__/componentEmits.spec.ts | 1 | https://github.com/vuejs/core/commit/3532b2b0213268a285cacce9b38f806e6af29a61 | [
0.0020151666831225157,
0.0002338608610443771,
0.0001652281207498163,
0.0001720008731354028,
0.0003307962906546891
] |
{
"id": 2,
"code_window": [
"): boolean {\n",
" if (!options || !isOn(key)) {\n",
" return false\n",
" }\n",
" key = key.replace(/Once$/, '')\n",
" return (\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
" key = key.slice(2).replace(/Once$/, '')\n"
],
"file_path": "packages/runtime-core/src/componentEmits.ts",
"type": "replace",
"edit_start_line_idx": 203
} | // SFC scoped style ID management.
// These are only used in esm-bundler builds, but since exports cannot be
// conditional, we can only drop inner implementations in non-bundler builds.
import { withCtx } from './withRenderContext'
export let currentScopeId: string | null = null
const scopeIdStack: string[] = []
/**
* @private
*/
export function pushScopeId(id: string) {
scopeIdStack.push((currentScopeId = id))
}
/**
* @private
*/
export function popScopeId() {
scopeIdStack.pop()
currentScopeId = scopeIdStack[scopeIdStack.length - 1] || null
}
/**
* @private
*/
export function withScopeId(id: string): <T extends Function>(fn: T) => T {
return ((fn: Function) =>
withCtx(function(this: any) {
pushScopeId(id)
const res = fn.apply(this, arguments)
popScopeId()
return res
})) as any
}
| packages/runtime-core/src/helpers/scopeId.ts | 0 | https://github.com/vuejs/core/commit/3532b2b0213268a285cacce9b38f806e6af29a61 | [
0.00017332666902802885,
0.00017232794198207557,
0.00017113529611378908,
0.00017242488684132695,
9.64124410529621e-7
] |
{
"id": 2,
"code_window": [
"): boolean {\n",
" if (!options || !isOn(key)) {\n",
" return false\n",
" }\n",
" key = key.replace(/Once$/, '')\n",
" return (\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
" key = key.slice(2).replace(/Once$/, '')\n"
],
"file_path": "packages/runtime-core/src/componentEmits.ts",
"type": "replace",
"edit_start_line_idx": 203
} | import { ComponentInternalInstance, Data } from './component'
import { nextTick, queueJob } from './scheduler'
import { instanceWatch, WatchOptions, WatchStopHandle } from './apiWatch'
import {
EMPTY_OBJ,
hasOwn,
isGloballyWhitelisted,
NOOP,
extend,
isString
} from '@vue/shared'
import {
ReactiveEffect,
toRaw,
shallowReadonly,
ReactiveFlags,
track,
TrackOpTypes,
ShallowUnwrapRef
} from '@vue/reactivity'
import {
ExtractComputedReturns,
ComponentOptionsBase,
ComputedOptions,
MethodOptions,
ComponentOptionsMixin,
OptionTypesType,
OptionTypesKeys,
resolveMergedOptions,
isInBeforeCreate
} from './componentOptions'
import { EmitsOptions, EmitFn } from './componentEmits'
import { Slots } from './componentSlots'
import {
currentRenderingInstance,
markAttrsAccessed
} from './componentRenderUtils'
import { warn } from './warning'
import { UnionToIntersection } from './helpers/typeUtils'
/**
* Custom properties added to component instances in any way and can be accessed through `this`
*
* @example
* Here is an example of adding a property `$router` to every component instance:
* ```ts
* import { createApp } from 'vue'
* import { Router, createRouter } from 'vue-router'
*
* declare module '@vue/runtime-core' {
* interface ComponentCustomProperties {
* $router: Router
* }
* }
*
* // effectively adding the router to every component instance
* const app = createApp({})
* const router = createRouter()
* app.config.globalProperties.$router = router
*
* const vm = app.mount('#app')
* // we can access the router from the instance
* vm.$router.push('/')
* ```
*/
export interface ComponentCustomProperties {}
type IsDefaultMixinComponent<T> = T extends ComponentOptionsMixin
? ComponentOptionsMixin extends T ? true : false
: false
type MixinToOptionTypes<T> = T extends ComponentOptionsBase<
infer P,
infer B,
infer D,
infer C,
infer M,
infer Mixin,
infer Extends,
any,
any,
infer Defaults
>
? OptionTypesType<P & {}, B & {}, D & {}, C & {}, M & {}, Defaults & {}> &
IntersectionMixin<Mixin> &
IntersectionMixin<Extends>
: never
// ExtractMixin(map type) is used to resolve circularly references
type ExtractMixin<T> = {
Mixin: MixinToOptionTypes<T>
}[T extends ComponentOptionsMixin ? 'Mixin' : never]
type IntersectionMixin<T> = IsDefaultMixinComponent<T> extends true
? OptionTypesType<{}, {}, {}, {}, {}>
: UnionToIntersection<ExtractMixin<T>>
type UnwrapMixinsType<
T,
Type extends OptionTypesKeys
> = T extends OptionTypesType ? T[Type] : never
type EnsureNonVoid<T> = T extends void ? {} : T
export type ComponentPublicInstanceConstructor<
T extends ComponentPublicInstance<
Props,
RawBindings,
D,
C,
M
> = ComponentPublicInstance<any>,
Props = any,
RawBindings = any,
D = any,
C extends ComputedOptions = ComputedOptions,
M extends MethodOptions = MethodOptions
> = {
__isFragment?: never
__isTeleport?: never
__isSuspense?: never
new (...args: any[]): T
}
export type CreateComponentPublicInstance<
P = {},
B = {},
D = {},
C extends ComputedOptions = {},
M extends MethodOptions = {},
Mixin extends ComponentOptionsMixin = ComponentOptionsMixin,
Extends extends ComponentOptionsMixin = ComponentOptionsMixin,
E extends EmitsOptions = {},
PublicProps = P,
Defaults = {},
MakeDefaultsOptional extends boolean = false,
PublicMixin = IntersectionMixin<Mixin> & IntersectionMixin<Extends>,
PublicP = UnwrapMixinsType<PublicMixin, 'P'> & EnsureNonVoid<P>,
PublicB = UnwrapMixinsType<PublicMixin, 'B'> & EnsureNonVoid<B>,
PublicD = UnwrapMixinsType<PublicMixin, 'D'> & EnsureNonVoid<D>,
PublicC extends ComputedOptions = UnwrapMixinsType<PublicMixin, 'C'> &
EnsureNonVoid<C>,
PublicM extends MethodOptions = UnwrapMixinsType<PublicMixin, 'M'> &
EnsureNonVoid<M>,
PublicDefaults = UnwrapMixinsType<PublicMixin, 'Defaults'> &
EnsureNonVoid<Defaults>
> = ComponentPublicInstance<
PublicP,
PublicB,
PublicD,
PublicC,
PublicM,
E,
PublicProps,
PublicDefaults,
MakeDefaultsOptional,
ComponentOptionsBase<P, B, D, C, M, Mixin, Extends, E, string, Defaults>
>
// public properties exposed on the proxy, which is used as the render context
// in templates (as `this` in the render option)
export type ComponentPublicInstance<
P = {}, // props type extracted from props option
B = {}, // raw bindings returned from setup()
D = {}, // return from data()
C extends ComputedOptions = {},
M extends MethodOptions = {},
E extends EmitsOptions = {},
PublicProps = P,
Defaults = {},
MakeDefaultsOptional extends boolean = false,
Options = ComponentOptionsBase<any, any, any, any, any, any, any, any, any>
> = {
$: ComponentInternalInstance
$data: D
$props: MakeDefaultsOptional extends true
? Partial<Defaults> & Omit<P & PublicProps, keyof Defaults>
: P & PublicProps
$attrs: Data
$refs: Data
$slots: Slots
$root: ComponentPublicInstance | null
$parent: ComponentPublicInstance | null
$emit: EmitFn<E>
$el: any
$options: Options
$forceUpdate: ReactiveEffect
$nextTick: typeof nextTick
$watch(
source: string | Function,
cb: Function,
options?: WatchOptions
): WatchStopHandle
} & P &
ShallowUnwrapRef<B> &
D &
ExtractComputedReturns<C> &
M &
ComponentCustomProperties
type PublicPropertiesMap = Record<string, (i: ComponentInternalInstance) => any>
/**
* #2437 In Vue 3, functional components do not have a public instance proxy but
* they exist in the internal parent chain. For code that relies on traversing
* public $parent chains, skip functional ones and go to the parent instead.
*/
const getPublicInstance = (
i: ComponentInternalInstance | null
): ComponentPublicInstance | null =>
i && (i.proxy ? i.proxy : getPublicInstance(i.parent))
const publicPropertiesMap: PublicPropertiesMap = extend(Object.create(null), {
$: i => i,
$el: i => i.vnode.el,
$data: i => i.data,
$props: i => (__DEV__ ? shallowReadonly(i.props) : i.props),
$attrs: i => (__DEV__ ? shallowReadonly(i.attrs) : i.attrs),
$slots: i => (__DEV__ ? shallowReadonly(i.slots) : i.slots),
$refs: i => (__DEV__ ? shallowReadonly(i.refs) : i.refs),
$parent: i => getPublicInstance(i.parent),
$root: i => i.root && i.root.proxy,
$emit: i => i.emit,
$options: i => (__FEATURE_OPTIONS_API__ ? resolveMergedOptions(i) : i.type),
$forceUpdate: i => () => queueJob(i.update),
$nextTick: i => nextTick.bind(i.proxy!),
$watch: i => (__FEATURE_OPTIONS_API__ ? instanceWatch.bind(i) : NOOP)
} as PublicPropertiesMap)
const enum AccessTypes {
SETUP,
DATA,
PROPS,
CONTEXT,
OTHER
}
export interface ComponentRenderContext {
[key: string]: any
_: ComponentInternalInstance
}
export const PublicInstanceProxyHandlers: ProxyHandler<any> = {
get({ _: instance }: ComponentRenderContext, key: string) {
const {
ctx,
setupState,
data,
props,
accessCache,
type,
appContext
} = instance
// let @vue/reactivity know it should never observe Vue public instances.
if (key === ReactiveFlags.SKIP) {
return true
}
// for internal formatters to know that this is a Vue instance
if (__DEV__ && key === '__isVue') {
return true
}
// data / props / ctx
// This getter gets called for every property access on the render context
// during render and is a major hotspot. The most expensive part of this
// is the multiple hasOwn() calls. It's much faster to do a simple property
// access on a plain object, so we use an accessCache object (with null
// prototype) to memoize what access type a key corresponds to.
let normalizedProps
if (key[0] !== '$') {
const n = accessCache![key]
if (n !== undefined) {
switch (n) {
case AccessTypes.SETUP:
return setupState[key]
case AccessTypes.DATA:
return data[key]
case AccessTypes.CONTEXT:
return ctx[key]
case AccessTypes.PROPS:
return props![key]
// default: just fallthrough
}
} else if (setupState !== EMPTY_OBJ && hasOwn(setupState, key)) {
accessCache![key] = AccessTypes.SETUP
return setupState[key]
} else if (data !== EMPTY_OBJ && hasOwn(data, key)) {
accessCache![key] = AccessTypes.DATA
return data[key]
} else if (
// only cache other properties when instance has declared (thus stable)
// props
(normalizedProps = instance.propsOptions[0]) &&
hasOwn(normalizedProps, key)
) {
accessCache![key] = AccessTypes.PROPS
return props![key]
} else if (ctx !== EMPTY_OBJ && hasOwn(ctx, key)) {
accessCache![key] = AccessTypes.CONTEXT
return ctx[key]
} else if (!__FEATURE_OPTIONS_API__ || !isInBeforeCreate) {
accessCache![key] = AccessTypes.OTHER
}
}
const publicGetter = publicPropertiesMap[key]
let cssModule, globalProperties
// public $xxx properties
if (publicGetter) {
if (key === '$attrs') {
track(instance, TrackOpTypes.GET, key)
__DEV__ && markAttrsAccessed()
}
return publicGetter(instance)
} else if (
// css module (injected by vue-loader)
(cssModule = type.__cssModules) &&
(cssModule = cssModule[key])
) {
return cssModule
} else if (ctx !== EMPTY_OBJ && hasOwn(ctx, key)) {
// user may set custom properties to `this` that start with `$`
accessCache![key] = AccessTypes.CONTEXT
return ctx[key]
} else if (
// global properties
((globalProperties = appContext.config.globalProperties),
hasOwn(globalProperties, key))
) {
return globalProperties[key]
} else if (
__DEV__ &&
currentRenderingInstance &&
(!isString(key) ||
// #1091 avoid internal isRef/isVNode checks on component instance leading
// to infinite warning loop
key.indexOf('__v') !== 0)
) {
if (
data !== EMPTY_OBJ &&
(key[0] === '$' || key[0] === '_') &&
hasOwn(data, key)
) {
warn(
`Property ${JSON.stringify(
key
)} must be accessed via $data because it starts with a reserved ` +
`character ("$" or "_") and is not proxied on the render context.`
)
} else {
warn(
`Property ${JSON.stringify(key)} was accessed during render ` +
`but is not defined on instance.`
)
}
}
},
set(
{ _: instance }: ComponentRenderContext,
key: string,
value: any
): boolean {
const { data, setupState, ctx } = instance
if (setupState !== EMPTY_OBJ && hasOwn(setupState, key)) {
setupState[key] = value
} else if (data !== EMPTY_OBJ && hasOwn(data, key)) {
data[key] = value
} else if (key in instance.props) {
__DEV__ &&
warn(
`Attempting to mutate prop "${key}". Props are readonly.`,
instance
)
return false
}
if (key[0] === '$' && key.slice(1) in instance) {
__DEV__ &&
warn(
`Attempting to mutate public property "${key}". ` +
`Properties starting with $ are reserved and readonly.`,
instance
)
return false
} else {
if (__DEV__ && key in instance.appContext.config.globalProperties) {
Object.defineProperty(ctx, key, {
enumerable: true,
configurable: true,
value
})
} else {
ctx[key] = value
}
}
return true
},
has(
{
_: { data, setupState, accessCache, ctx, appContext, propsOptions }
}: ComponentRenderContext,
key: string
) {
let normalizedProps
return (
accessCache![key] !== undefined ||
(data !== EMPTY_OBJ && hasOwn(data, key)) ||
(setupState !== EMPTY_OBJ && hasOwn(setupState, key)) ||
((normalizedProps = propsOptions[0]) && hasOwn(normalizedProps, key)) ||
hasOwn(ctx, key) ||
hasOwn(publicPropertiesMap, key) ||
hasOwn(appContext.config.globalProperties, key)
)
}
}
if (__DEV__ && !__TEST__) {
PublicInstanceProxyHandlers.ownKeys = (target: ComponentRenderContext) => {
warn(
`Avoid app logic that relies on enumerating keys on a component instance. ` +
`The keys will be empty in production mode to avoid performance overhead.`
)
return Reflect.ownKeys(target)
}
}
export const RuntimeCompiledPublicInstanceProxyHandlers = extend(
{},
PublicInstanceProxyHandlers,
{
get(target: ComponentRenderContext, key: string) {
// fast path for unscopables when using `with` block
if ((key as any) === Symbol.unscopables) {
return
}
return PublicInstanceProxyHandlers.get!(target, key, target)
},
has(_: ComponentRenderContext, key: string) {
const has = key[0] !== '_' && !isGloballyWhitelisted(key)
if (__DEV__ && !has && PublicInstanceProxyHandlers.has!(_, key)) {
warn(
`Property ${JSON.stringify(
key
)} should not start with _ which is a reserved prefix for Vue internals.`
)
}
return has
}
}
)
// In dev mode, the proxy target exposes the same properties as seen on `this`
// for easier console inspection. In prod mode it will be an empty object so
// these properties definitions can be skipped.
export function createRenderContext(instance: ComponentInternalInstance) {
const target: Record<string, any> = {}
// expose internal instance for proxy handlers
Object.defineProperty(target, `_`, {
configurable: true,
enumerable: false,
get: () => instance
})
// expose public properties
Object.keys(publicPropertiesMap).forEach(key => {
Object.defineProperty(target, key, {
configurable: true,
enumerable: false,
get: () => publicPropertiesMap[key](instance),
// intercepted by the proxy so no need for implementation,
// but needed to prevent set errors
set: NOOP
})
})
// expose global properties
const { globalProperties } = instance.appContext.config
Object.keys(globalProperties).forEach(key => {
Object.defineProperty(target, key, {
configurable: true,
enumerable: false,
get: () => globalProperties[key],
set: NOOP
})
})
return target as ComponentRenderContext
}
// dev only
export function exposePropsOnRenderContext(
instance: ComponentInternalInstance
) {
const {
ctx,
propsOptions: [propsOptions]
} = instance
if (propsOptions) {
Object.keys(propsOptions).forEach(key => {
Object.defineProperty(ctx, key, {
enumerable: true,
configurable: true,
get: () => instance.props[key],
set: NOOP
})
})
}
}
// dev only
export function exposeSetupStateOnRenderContext(
instance: ComponentInternalInstance
) {
const { ctx, setupState } = instance
Object.keys(toRaw(setupState)).forEach(key => {
if (key[0] === '$' || key[0] === '_') {
warn(
`setup() return property ${JSON.stringify(
key
)} should not start with "$" or "_" ` +
`which are reserved prefixes for Vue internals.`
)
return
}
Object.defineProperty(ctx, key, {
enumerable: true,
configurable: true,
get: () => setupState[key],
set: NOOP
})
})
}
| packages/runtime-core/src/componentPublicInstance.ts | 0 | https://github.com/vuejs/core/commit/3532b2b0213268a285cacce9b38f806e6af29a61 | [
0.994528591632843,
0.40647754073143005,
0.00016422208864241838,
0.003087510820478201,
0.4667271673679352
] |
{
"id": 2,
"code_window": [
"): boolean {\n",
" if (!options || !isOn(key)) {\n",
" return false\n",
" }\n",
" key = key.replace(/Once$/, '')\n",
" return (\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
" key = key.slice(2).replace(/Once$/, '')\n"
],
"file_path": "packages/runtime-core/src/componentEmits.ts",
"type": "replace",
"edit_start_line_idx": 203
} | 'use strict'
if (process.env.NODE_ENV === 'production') {
module.exports = require('./dist/server-renderer.cjs.prod.js')
} else {
module.exports = require('./dist/server-renderer.cjs.js')
}
| packages/server-renderer/index.js | 0 | https://github.com/vuejs/core/commit/3532b2b0213268a285cacce9b38f806e6af29a61 | [
0.0001722201268421486,
0.0001722201268421486,
0.0001722201268421486,
0.0001722201268421486,
0
] |
{
"id": 3,
"code_window": [
" return (\n",
" hasOwn(options, key[2].toLowerCase() + key.slice(3)) ||\n",
" hasOwn(options, key.slice(2))\n",
" )\n",
"}"
],
"labels": [
"keep",
"replace",
"replace",
"keep",
"keep"
],
"after_edit": [
" hasOwn(options, key[0].toLowerCase() + key.slice(1)) ||\n",
" hasOwn(options, hyphenate(key)) ||\n",
" hasOwn(options, key)\n"
],
"file_path": "packages/runtime-core/src/componentEmits.ts",
"type": "replace",
"edit_start_line_idx": 205
} | import {
camelize,
EMPTY_OBJ,
toHandlerKey,
extend,
hasOwn,
hyphenate,
isArray,
isFunction,
isOn,
toNumber
} from '@vue/shared'
import {
ComponentInternalInstance,
ComponentOptions,
ConcreteComponent,
formatComponentName
} from './component'
import { callWithAsyncErrorHandling, ErrorCodes } from './errorHandling'
import { warn } from './warning'
import { UnionToIntersection } from './helpers/typeUtils'
import { devtoolsComponentEmit } from './devtools'
import { AppContext } from './apiCreateApp'
export type ObjectEmitsOptions = Record<
string,
((...args: any[]) => any) | null
>
export type EmitsOptions = ObjectEmitsOptions | string[]
export type EmitFn<
Options = ObjectEmitsOptions,
Event extends keyof Options = keyof Options
> = Options extends Array<infer V>
? (event: V, ...args: any[]) => void
: {} extends Options // if the emit is empty object (usually the default value for emit) should be converted to function
? (event: string, ...args: any[]) => void
: UnionToIntersection<
{
[key in Event]: Options[key] extends ((...args: infer Args) => any)
? (event: key, ...args: Args) => void
: (event: key, ...args: any[]) => void
}[Event]
>
export function emit(
instance: ComponentInternalInstance,
event: string,
...rawArgs: any[]
) {
const props = instance.vnode.props || EMPTY_OBJ
if (__DEV__) {
const {
emitsOptions,
propsOptions: [propsOptions]
} = instance
if (emitsOptions) {
if (!(event in emitsOptions)) {
if (!propsOptions || !(toHandlerKey(event) in propsOptions)) {
warn(
`Component emitted event "${event}" but it is neither declared in ` +
`the emits option nor as an "${toHandlerKey(event)}" prop.`
)
}
} else {
const validator = emitsOptions[event]
if (isFunction(validator)) {
const isValid = validator(...rawArgs)
if (!isValid) {
warn(
`Invalid event arguments: event validation failed for event "${event}".`
)
}
}
}
}
}
let args = rawArgs
const isModelListener = event.startsWith('update:')
// for v-model update:xxx events, apply modifiers on args
const modelArg = isModelListener && event.slice(7)
if (modelArg && modelArg in props) {
const modifiersKey = `${
modelArg === 'modelValue' ? 'model' : modelArg
}Modifiers`
const { number, trim } = props[modifiersKey] || EMPTY_OBJ
if (trim) {
args = rawArgs.map(a => a.trim())
} else if (number) {
args = rawArgs.map(toNumber)
}
}
if (__DEV__ || __FEATURE_PROD_DEVTOOLS__) {
devtoolsComponentEmit(instance, event, args)
}
if (__DEV__) {
const lowerCaseEvent = event.toLowerCase()
if (lowerCaseEvent !== event && props[toHandlerKey(lowerCaseEvent)]) {
warn(
`Event "${lowerCaseEvent}" is emitted in component ` +
`${formatComponentName(
instance,
instance.type
)} but the handler is registered for "${event}". ` +
`Note that HTML attributes are case-insensitive and you cannot use ` +
`v-on to listen to camelCase events when using in-DOM templates. ` +
`You should probably use "${hyphenate(event)}" instead of "${event}".`
)
}
}
// convert handler name to camelCase. See issue #2249
let handlerName = toHandlerKey(camelize(event))
let handler = props[handlerName]
// for v-model update:xxx events, also trigger kebab-case equivalent
// for props passed via kebab-case
if (!handler && isModelListener) {
handlerName = toHandlerKey(hyphenate(event))
handler = props[handlerName]
}
if (handler) {
callWithAsyncErrorHandling(
handler,
instance,
ErrorCodes.COMPONENT_EVENT_HANDLER,
args
)
}
const onceHandler = props[handlerName + `Once`]
if (onceHandler) {
if (!instance.emitted) {
;(instance.emitted = {} as Record<string, boolean>)[handlerName] = true
} else if (instance.emitted[handlerName]) {
return
}
callWithAsyncErrorHandling(
onceHandler,
instance,
ErrorCodes.COMPONENT_EVENT_HANDLER,
args
)
}
}
export function normalizeEmitsOptions(
comp: ConcreteComponent,
appContext: AppContext,
asMixin = false
): ObjectEmitsOptions | null {
if (!appContext.deopt && comp.__emits !== undefined) {
return comp.__emits
}
const raw = comp.emits
let normalized: ObjectEmitsOptions = {}
// apply mixin/extends props
let hasExtends = false
if (__FEATURE_OPTIONS_API__ && !isFunction(comp)) {
const extendEmits = (raw: ComponentOptions) => {
hasExtends = true
extend(normalized, normalizeEmitsOptions(raw, appContext, true))
}
if (!asMixin && appContext.mixins.length) {
appContext.mixins.forEach(extendEmits)
}
if (comp.extends) {
extendEmits(comp.extends)
}
if (comp.mixins) {
comp.mixins.forEach(extendEmits)
}
}
if (!raw && !hasExtends) {
return (comp.__emits = null)
}
if (isArray(raw)) {
raw.forEach(key => (normalized[key] = null))
} else {
extend(normalized, raw)
}
return (comp.__emits = normalized)
}
// Check if an incoming prop key is a declared emit event listener.
// e.g. With `emits: { click: null }`, props named `onClick` and `onclick` are
// both considered matched listeners.
export function isEmitListener(
options: ObjectEmitsOptions | null,
key: string
): boolean {
if (!options || !isOn(key)) {
return false
}
key = key.replace(/Once$/, '')
return (
hasOwn(options, key[2].toLowerCase() + key.slice(3)) ||
hasOwn(options, key.slice(2))
)
}
| packages/runtime-core/src/componentEmits.ts | 1 | https://github.com/vuejs/core/commit/3532b2b0213268a285cacce9b38f806e6af29a61 | [
0.8994400501251221,
0.043422549962997437,
0.0001637714303797111,
0.00017122931603807956,
0.19141614437103271
] |
{
"id": 3,
"code_window": [
" return (\n",
" hasOwn(options, key[2].toLowerCase() + key.slice(3)) ||\n",
" hasOwn(options, key.slice(2))\n",
" )\n",
"}"
],
"labels": [
"keep",
"replace",
"replace",
"keep",
"keep"
],
"after_edit": [
" hasOwn(options, key[0].toLowerCase() + key.slice(1)) ||\n",
" hasOwn(options, hyphenate(key)) ||\n",
" hasOwn(options, key)\n"
],
"file_path": "packages/runtime-core/src/componentEmits.ts",
"type": "replace",
"edit_start_line_idx": 205
} | {
"name": "@vue/runtime-test",
"version": "3.0.3",
"description": "@vue/runtime-test",
"private": true,
"main": "index.js",
"module": "dist/runtime-test.esm-bundler.js",
"types": "dist/runtime-test.d.ts",
"files": [
"index.js",
"dist"
],
"repository": {
"type": "git",
"url": "git+https://github.com/vuejs/vue-next.git",
"directory": "packages/runtime-test"
},
"keywords": [
"vue"
],
"author": "Evan You",
"license": "MIT",
"bugs": {
"url": "https://github.com/vuejs/vue-next/issues"
},
"homepage": "https://github.com/vuejs/vue-next/tree/master/packages/runtime-test#readme",
"dependencies": {
"@vue/shared": "3.0.3",
"@vue/runtime-core": "3.0.3"
}
}
| packages/runtime-test/package.json | 0 | https://github.com/vuejs/core/commit/3532b2b0213268a285cacce9b38f806e6af29a61 | [
0.00017603219021111727,
0.00017473175830673426,
0.00017301409388892353,
0.0001749403600115329,
0.0000012006880751869176
] |
{
"id": 3,
"code_window": [
" return (\n",
" hasOwn(options, key[2].toLowerCase() + key.slice(3)) ||\n",
" hasOwn(options, key.slice(2))\n",
" )\n",
"}"
],
"labels": [
"keep",
"replace",
"replace",
"keep",
"keep"
],
"after_edit": [
" hasOwn(options, key[0].toLowerCase() + key.slice(1)) ||\n",
" hasOwn(options, hyphenate(key)) ||\n",
" hasOwn(options, key)\n"
],
"file_path": "packages/runtime-core/src/componentEmits.ts",
"type": "replace",
"edit_start_line_idx": 205
} | import {
effect,
stop,
isRef,
Ref,
ComputedRef,
ReactiveEffectOptions,
isReactive
} from '@vue/reactivity'
import { SchedulerJob, queuePreFlushCb } from './scheduler'
import {
EMPTY_OBJ,
isObject,
isArray,
isFunction,
isString,
hasChanged,
NOOP,
remove,
isMap,
isSet
} from '@vue/shared'
import {
currentInstance,
ComponentInternalInstance,
isInSSRComponentSetup,
recordInstanceBoundEffect
} from './component'
import {
ErrorCodes,
callWithErrorHandling,
callWithAsyncErrorHandling
} from './errorHandling'
import { queuePostRenderEffect } from './renderer'
import { warn } from './warning'
export type WatchEffect = (onInvalidate: InvalidateCbRegistrator) => void
export type WatchSource<T = any> = Ref<T> | ComputedRef<T> | (() => T)
export type WatchCallback<V = any, OV = any> = (
value: V,
oldValue: OV,
onInvalidate: InvalidateCbRegistrator
) => any
type MapSources<T, Immediate> = {
[K in keyof T]: T[K] extends WatchSource<infer V>
? Immediate extends true ? (V | undefined) : V
: T[K] extends object
? Immediate extends true ? (T[K] | undefined) : T[K]
: never
}
type InvalidateCbRegistrator = (cb: () => void) => void
export interface WatchOptionsBase {
flush?: 'pre' | 'post' | 'sync'
onTrack?: ReactiveEffectOptions['onTrack']
onTrigger?: ReactiveEffectOptions['onTrigger']
}
export interface WatchOptions<Immediate = boolean> extends WatchOptionsBase {
immediate?: Immediate
deep?: boolean
}
export type WatchStopHandle = () => void
// Simple effect.
export function watchEffect(
effect: WatchEffect,
options?: WatchOptionsBase
): WatchStopHandle {
return doWatch(effect, null, options)
}
// initial value for watchers to trigger on undefined initial values
const INITIAL_WATCHER_VALUE = {}
// overload #1: array of multiple sources + cb
// Readonly constraint helps the callback to correctly infer value types based
// on position in the source array. Otherwise the values will get a union type
// of all possible value types.
export function watch<
T extends Readonly<Array<WatchSource<unknown> | object>>,
Immediate extends Readonly<boolean> = false
>(
sources: T,
cb: WatchCallback<MapSources<T, false>, MapSources<T, Immediate>>,
options?: WatchOptions<Immediate>
): WatchStopHandle
// overload #2: single source + cb
export function watch<T, Immediate extends Readonly<boolean> = false>(
source: WatchSource<T>,
cb: WatchCallback<T, Immediate extends true ? (T | undefined) : T>,
options?: WatchOptions<Immediate>
): WatchStopHandle
// overload #3: watching reactive object w/ cb
export function watch<
T extends object,
Immediate extends Readonly<boolean> = false
>(
source: T,
cb: WatchCallback<T, Immediate extends true ? (T | undefined) : T>,
options?: WatchOptions<Immediate>
): WatchStopHandle
// implementation
export function watch<T = any, Immediate extends Readonly<boolean> = false>(
source: T | WatchSource<T>,
cb: any,
options?: WatchOptions<Immediate>
): WatchStopHandle {
if (__DEV__ && !isFunction(cb)) {
warn(
`\`watch(fn, options?)\` signature has been moved to a separate API. ` +
`Use \`watchEffect(fn, options?)\` instead. \`watch\` now only ` +
`supports \`watch(source, cb, options?) signature.`
)
}
return doWatch(source as any, cb, options)
}
function doWatch(
source: WatchSource | WatchSource[] | WatchEffect | object,
cb: WatchCallback | null,
{ immediate, deep, flush, onTrack, onTrigger }: WatchOptions = EMPTY_OBJ,
instance = currentInstance
): WatchStopHandle {
if (__DEV__ && !cb) {
if (immediate !== undefined) {
warn(
`watch() "immediate" option is only respected when using the ` +
`watch(source, callback, options?) signature.`
)
}
if (deep !== undefined) {
warn(
`watch() "deep" option is only respected when using the ` +
`watch(source, callback, options?) signature.`
)
}
}
const warnInvalidSource = (s: unknown) => {
warn(
`Invalid watch source: `,
s,
`A watch source can only be a getter/effect function, a ref, ` +
`a reactive object, or an array of these types.`
)
}
let getter: () => any
let forceTrigger = false
if (isRef(source)) {
getter = () => (source as Ref).value
forceTrigger = !!(source as Ref)._shallow
} else if (isReactive(source)) {
getter = () => source
deep = true
} else if (isArray(source)) {
getter = () =>
source.map(s => {
if (isRef(s)) {
return s.value
} else if (isReactive(s)) {
return traverse(s)
} else if (isFunction(s)) {
return callWithErrorHandling(s, instance, ErrorCodes.WATCH_GETTER)
} else {
__DEV__ && warnInvalidSource(s)
}
})
} else if (isFunction(source)) {
if (cb) {
// getter with cb
getter = () =>
callWithErrorHandling(source, instance, ErrorCodes.WATCH_GETTER)
} else {
// no cb -> simple effect
getter = () => {
if (instance && instance.isUnmounted) {
return
}
if (cleanup) {
cleanup()
}
return callWithErrorHandling(
source,
instance,
ErrorCodes.WATCH_CALLBACK,
[onInvalidate]
)
}
}
} else {
getter = NOOP
__DEV__ && warnInvalidSource(source)
}
if (cb && deep) {
const baseGetter = getter
getter = () => traverse(baseGetter())
}
let cleanup: () => void
const onInvalidate: InvalidateCbRegistrator = (fn: () => void) => {
cleanup = runner.options.onStop = () => {
callWithErrorHandling(fn, instance, ErrorCodes.WATCH_CLEANUP)
}
}
// in SSR there is no need to setup an actual effect, and it should be noop
// unless it's eager
if (__NODE_JS__ && isInSSRComponentSetup) {
if (!cb) {
getter()
} else if (immediate) {
callWithAsyncErrorHandling(cb, instance, ErrorCodes.WATCH_CALLBACK, [
getter(),
undefined,
onInvalidate
])
}
return NOOP
}
let oldValue = isArray(source) ? [] : INITIAL_WATCHER_VALUE
const job: SchedulerJob = () => {
if (!runner.active) {
return
}
if (cb) {
// watch(source, cb)
const newValue = runner()
if (deep || forceTrigger || hasChanged(newValue, oldValue)) {
// cleanup before running cb again
if (cleanup) {
cleanup()
}
callWithAsyncErrorHandling(cb, instance, ErrorCodes.WATCH_CALLBACK, [
newValue,
// pass undefined as the old value when it's changed for the first time
oldValue === INITIAL_WATCHER_VALUE ? undefined : oldValue,
onInvalidate
])
oldValue = newValue
}
} else {
// watchEffect
runner()
}
}
// important: mark the job as a watcher callback so that scheduler knows
// it is allowed to self-trigger (#1727)
job.allowRecurse = !!cb
let scheduler: ReactiveEffectOptions['scheduler']
if (flush === 'sync') {
scheduler = job
} else if (flush === 'post') {
scheduler = () => queuePostRenderEffect(job, instance && instance.suspense)
} else {
// default: 'pre'
scheduler = () => {
if (!instance || instance.isMounted) {
queuePreFlushCb(job)
} else {
// with 'pre' option, the first call must happen before
// the component is mounted so it is called synchronously.
job()
}
}
}
const runner = effect(getter, {
lazy: true,
onTrack,
onTrigger,
scheduler
})
recordInstanceBoundEffect(runner, instance)
// initial run
if (cb) {
if (immediate) {
job()
} else {
oldValue = runner()
}
} else if (flush === 'post') {
queuePostRenderEffect(runner, instance && instance.suspense)
} else {
runner()
}
return () => {
stop(runner)
if (instance) {
remove(instance.effects!, runner)
}
}
}
// this.$watch
export function instanceWatch(
this: ComponentInternalInstance,
source: string | Function,
cb: WatchCallback,
options?: WatchOptions
): WatchStopHandle {
const publicThis = this.proxy as any
const getter = isString(source)
? () => publicThis[source]
: source.bind(publicThis)
return doWatch(getter, cb.bind(publicThis), options, this)
}
function traverse(value: unknown, seen: Set<unknown> = new Set()) {
if (!isObject(value) || seen.has(value)) {
return value
}
seen.add(value)
if (isRef(value)) {
traverse(value.value, seen)
} else if (isArray(value)) {
for (let i = 0; i < value.length; i++) {
traverse(value[i], seen)
}
} else if (isSet(value) || isMap(value)) {
value.forEach((v: any) => {
traverse(v, seen)
})
} else {
for (const key in value) {
traverse(value[key], seen)
}
}
return value
}
| packages/runtime-core/src/apiWatch.ts | 0 | https://github.com/vuejs/core/commit/3532b2b0213268a285cacce9b38f806e6af29a61 | [
0.0002466870646458119,
0.00018319614173378795,
0.00016415368008892983,
0.00017286765796598047,
0.000021987621948937885
] |
{
"id": 3,
"code_window": [
" return (\n",
" hasOwn(options, key[2].toLowerCase() + key.slice(3)) ||\n",
" hasOwn(options, key.slice(2))\n",
" )\n",
"}"
],
"labels": [
"keep",
"replace",
"replace",
"keep",
"keep"
],
"after_edit": [
" hasOwn(options, key[0].toLowerCase() + key.slice(1)) ||\n",
" hasOwn(options, hyphenate(key)) ||\n",
" hasOwn(options, key)\n"
],
"file_path": "packages/runtime-core/src/componentEmits.ts",
"type": "replace",
"edit_start_line_idx": 205
} | import {
h,
nodeOps,
render,
serializeInner,
triggerEvent,
TestElement,
nextTick,
renderToString,
ref,
defineComponent
} from '@vue/runtime-test'
describe('api: options', () => {
test('data', async () => {
const Comp = defineComponent({
data() {
return {
foo: 1
}
},
render() {
return h(
'div',
{
onClick: () => {
this.foo++
}
},
this.foo
)
}
})
const root = nodeOps.createElement('div')
render(h(Comp), root)
expect(serializeInner(root)).toBe(`<div>1</div>`)
triggerEvent(root.children[0] as TestElement, 'click')
await nextTick()
expect(serializeInner(root)).toBe(`<div>2</div>`)
})
test('computed', async () => {
const Comp = defineComponent({
data() {
return {
foo: 1
}
},
computed: {
bar(): number {
return this.foo + 1
},
baz: (vm): number => vm.bar + 1
},
render() {
return h(
'div',
{
onClick: () => {
this.foo++
}
},
this.bar + this.baz
)
}
})
const root = nodeOps.createElement('div')
render(h(Comp), root)
expect(serializeInner(root)).toBe(`<div>5</div>`)
triggerEvent(root.children[0] as TestElement, 'click')
await nextTick()
expect(serializeInner(root)).toBe(`<div>7</div>`)
})
test('methods', async () => {
const Comp = defineComponent({
data() {
return {
foo: 1
}
},
methods: {
inc() {
this.foo++
}
},
render() {
return h(
'div',
{
onClick: this.inc
},
this.foo
)
}
})
const root = nodeOps.createElement('div')
render(h(Comp), root)
expect(serializeInner(root)).toBe(`<div>1</div>`)
triggerEvent(root.children[0] as TestElement, 'click')
await nextTick()
expect(serializeInner(root)).toBe(`<div>2</div>`)
})
test('watch', async () => {
function returnThis(this: any) {
return this
}
const spyA = jest.fn(returnThis)
const spyB = jest.fn(returnThis)
const spyC = jest.fn(returnThis)
const spyD = jest.fn(returnThis)
const spyE = jest.fn(returnThis)
let ctx: any
const Comp = {
data() {
return {
foo: 1,
bar: 2,
baz: {
qux: 3
},
qux: 4,
dot: {
path: 5
}
}
},
watch: {
// string method name
foo: 'onFooChange',
// direct function
bar: spyB,
baz: {
handler: spyC,
deep: true
},
qux: {
handler: 'onQuxChange'
},
'dot.path': spyE
},
methods: {
onFooChange: spyA,
onQuxChange: spyD
},
render() {
ctx = this
}
}
const root = nodeOps.createElement('div')
render(h(Comp), root)
function assertCall(spy: jest.Mock, callIndex: number, args: any[]) {
expect(spy.mock.calls[callIndex].slice(0, 2)).toMatchObject(args)
expect(spy).toHaveReturnedWith(ctx)
}
ctx.foo++
await nextTick()
expect(spyA).toHaveBeenCalledTimes(1)
assertCall(spyA, 0, [2, 1])
ctx.bar++
await nextTick()
expect(spyB).toHaveBeenCalledTimes(1)
assertCall(spyB, 0, [3, 2])
ctx.baz.qux++
await nextTick()
expect(spyC).toHaveBeenCalledTimes(1)
// new and old objects have same identity
assertCall(spyC, 0, [{ qux: 4 }, { qux: 4 }])
ctx.qux++
await nextTick()
expect(spyD).toHaveBeenCalledTimes(1)
assertCall(spyD, 0, [5, 4])
ctx.dot.path++
await nextTick()
expect(spyE).toHaveBeenCalledTimes(1)
assertCall(spyE, 0, [6, 5])
})
test('watch array', async () => {
function returnThis(this: any) {
return this
}
const spyA = jest.fn(returnThis)
const spyB = jest.fn(returnThis)
const spyC = jest.fn(returnThis)
let ctx: any
const Comp = {
data() {
return {
foo: 1,
bar: 2,
baz: {
qux: 3
}
}
},
watch: {
// string method name
foo: ['onFooChange'],
// direct function
bar: [spyB],
baz: [
{
handler: spyC,
deep: true
}
]
},
methods: {
onFooChange: spyA
},
render() {
ctx = this
}
}
const root = nodeOps.createElement('div')
render(h(Comp), root)
function assertCall(spy: jest.Mock, callIndex: number, args: any[]) {
expect(spy.mock.calls[callIndex].slice(0, 2)).toMatchObject(args)
expect(spy).toHaveReturnedWith(ctx)
}
ctx.foo++
await nextTick()
expect(spyA).toHaveBeenCalledTimes(1)
assertCall(spyA, 0, [2, 1])
ctx.bar++
await nextTick()
expect(spyB).toHaveBeenCalledTimes(1)
assertCall(spyB, 0, [3, 2])
ctx.baz.qux++
await nextTick()
expect(spyC).toHaveBeenCalledTimes(1)
// new and old objects have same identity
assertCall(spyC, 0, [{ qux: 4 }, { qux: 4 }])
})
test('provide/inject', () => {
const Root = defineComponent({
data() {
return {
a: 1
}
},
provide() {
return {
a: this.a
}
},
render() {
return [
h(ChildA),
h(ChildB),
h(ChildC),
h(ChildD),
h(ChildE),
h(ChildF),
h(ChildG),
h(ChildH)
]
}
})
const defineChild = (injectOptions: any, injectedKey = 'b') =>
({
inject: injectOptions,
render() {
return this[injectedKey]
}
} as any)
const ChildA = defineChild(['a'], 'a')
const ChildB = defineChild({ b: 'a' })
const ChildC = defineChild({
b: {
from: 'a'
}
})
const ChildD = defineChild(
{
a: {
default: () => 0
}
},
'a'
)
const ChildE = defineChild({
b: {
from: 'c',
default: 2
}
})
const ChildF = defineChild({
b: {
from: 'c',
default: () => 3
}
})
const ChildG = defineChild({
b: {
default: 4
}
})
const ChildH = defineChild({
b: {
default: () => 5
}
})
expect(renderToString(h(Root))).toBe(`11112345`)
})
test('provide accessing data in extends', () => {
const Base = defineComponent({
data() {
return {
a: 1
}
},
provide() {
return {
a: this.a
}
}
})
const Child = {
inject: ['a'],
render() {
return (this as any).a
}
}
const Root = defineComponent({
extends: Base,
render() {
return h(Child)
}
})
expect(renderToString(h(Root))).toBe(`1`)
})
test('lifecycle', async () => {
const count = ref(0)
const root = nodeOps.createElement('div')
const calls: string[] = []
const Root = {
beforeCreate() {
calls.push('root beforeCreate')
},
created() {
calls.push('root created')
},
beforeMount() {
calls.push('root onBeforeMount')
},
mounted() {
calls.push('root onMounted')
},
beforeUpdate() {
calls.push('root onBeforeUpdate')
},
updated() {
calls.push('root onUpdated')
},
beforeUnmount() {
calls.push('root onBeforeUnmount')
},
unmounted() {
calls.push('root onUnmounted')
},
render() {
return h(Mid, { count: count.value })
}
}
const Mid = {
beforeCreate() {
calls.push('mid beforeCreate')
},
created() {
calls.push('mid created')
},
beforeMount() {
calls.push('mid onBeforeMount')
},
mounted() {
calls.push('mid onMounted')
},
beforeUpdate() {
calls.push('mid onBeforeUpdate')
},
updated() {
calls.push('mid onUpdated')
},
beforeUnmount() {
calls.push('mid onBeforeUnmount')
},
unmounted() {
calls.push('mid onUnmounted')
},
render(this: any) {
return h(Child, { count: this.$props.count })
}
}
const Child = {
beforeCreate() {
calls.push('child beforeCreate')
},
created() {
calls.push('child created')
},
beforeMount() {
calls.push('child onBeforeMount')
},
mounted() {
calls.push('child onMounted')
},
beforeUpdate() {
calls.push('child onBeforeUpdate')
},
updated() {
calls.push('child onUpdated')
},
beforeUnmount() {
calls.push('child onBeforeUnmount')
},
unmounted() {
calls.push('child onUnmounted')
},
render(this: any) {
return h('div', this.$props.count)
}
}
// mount
render(h(Root), root)
expect(calls).toEqual([
'root beforeCreate',
'root created',
'root onBeforeMount',
'mid beforeCreate',
'mid created',
'mid onBeforeMount',
'child beforeCreate',
'child created',
'child onBeforeMount',
'child onMounted',
'mid onMounted',
'root onMounted'
])
calls.length = 0
// update
count.value++
await nextTick()
expect(calls).toEqual([
'root onBeforeUpdate',
'mid onBeforeUpdate',
'child onBeforeUpdate',
'child onUpdated',
'mid onUpdated',
'root onUpdated'
])
calls.length = 0
// unmount
render(null, root)
expect(calls).toEqual([
'root onBeforeUnmount',
'mid onBeforeUnmount',
'child onBeforeUnmount',
'child onUnmounted',
'mid onUnmounted',
'root onUnmounted'
])
})
test('mixins', () => {
const calls: string[] = []
const mixinA = {
data() {
return {
a: 1
}
},
created(this: any) {
calls.push('mixinA created')
expect(this.a).toBe(1)
expect(this.b).toBe(2)
expect(this.c).toBe(4)
},
mounted() {
calls.push('mixinA mounted')
}
}
const mixinB = {
props: {
bP: {
type: String
}
},
data() {
return {
b: 2
}
},
created(this: any) {
calls.push('mixinB created')
expect(this.a).toBe(1)
expect(this.b).toBe(2)
expect(this.bP).toBeUndefined()
expect(this.c).toBe(4)
expect(this.cP1).toBeUndefined()
},
mounted() {
calls.push('mixinB mounted')
}
}
const mixinC = defineComponent({
props: ['cP1', 'cP2'],
data() {
return {
c: 3
}
},
created() {
calls.push('mixinC created')
// component data() should overwrite mixin field with same key
expect(this.c).toBe(4)
expect(this.cP1).toBeUndefined()
},
mounted() {
calls.push('mixinC mounted')
}
})
const Comp = defineComponent({
props: {
aaa: String
},
mixins: [defineComponent(mixinA), defineComponent(mixinB), mixinC],
data() {
return {
c: 4,
z: 4
}
},
created() {
calls.push('comp created')
expect(this.a).toBe(1)
expect(this.b).toBe(2)
expect(this.bP).toBeUndefined()
expect(this.c).toBe(4)
expect(this.cP2).toBeUndefined()
expect(this.z).toBe(4)
},
mounted() {
calls.push('comp mounted')
},
render() {
return `${this.a}${this.b}${this.c}`
}
})
expect(renderToString(h(Comp))).toBe(`124`)
expect(calls).toEqual([
'mixinA created',
'mixinB created',
'mixinC created',
'comp created',
'mixinA mounted',
'mixinB mounted',
'mixinC mounted',
'comp mounted'
])
})
test('render from mixin', () => {
const Comp = {
mixins: [
{
render: () => 'from mixin'
}
]
}
expect(renderToString(h(Comp))).toBe('from mixin')
})
test('extends', () => {
const calls: string[] = []
const Base = {
data() {
return {
a: 1,
b: 1
}
},
methods: {
sayA() {}
},
mounted(this: any) {
expect(this.a).toBe(1)
expect(this.b).toBe(2)
calls.push('base')
}
}
const Comp = defineComponent({
extends: defineComponent(Base),
data() {
return {
b: 2
}
},
mounted() {
calls.push('comp')
},
render() {
return `${this.a}${this.b}`
}
})
expect(renderToString(h(Comp))).toBe(`12`)
expect(calls).toEqual(['base', 'comp'])
})
test('extends with mixins', () => {
const calls: string[] = []
const Base = {
data() {
return {
a: 1,
x: 'base'
}
},
methods: {
sayA() {}
},
mounted(this: any) {
expect(this.a).toBe(1)
expect(this.b).toBeTruthy()
expect(this.c).toBe(2)
calls.push('base')
}
}
const Mixin = {
data() {
return {
b: true,
x: 'mixin'
}
},
mounted(this: any) {
expect(this.a).toBe(1)
expect(this.b).toBeTruthy()
expect(this.c).toBe(2)
calls.push('mixin')
}
}
const Comp = defineComponent({
extends: defineComponent(Base),
mixins: [defineComponent(Mixin)],
data() {
return {
c: 2
}
},
mounted() {
calls.push('comp')
},
render() {
return `${this.a}${this.b}${this.c}${this.x}`
}
})
expect(renderToString(h(Comp))).toBe(`1true2mixin`)
expect(calls).toEqual(['base', 'mixin', 'comp'])
})
test('beforeCreate/created in extends and mixins', () => {
const calls: string[] = []
const BaseA = {
beforeCreate() {
calls.push('beforeCreateA')
},
created() {
calls.push('createdA')
}
}
const BaseB = {
extends: BaseA,
beforeCreate() {
calls.push('beforeCreateB')
},
created() {
calls.push('createdB')
}
}
const MixinA = {
beforeCreate() {
calls.push('beforeCreateC')
},
created() {
calls.push('createdC')
}
}
const MixinB = {
mixins: [MixinA],
beforeCreate() {
calls.push('beforeCreateD')
},
created() {
calls.push('createdD')
}
}
const Comp = {
extends: BaseB,
mixins: [MixinB],
beforeCreate() {
calls.push('selfBeforeCreate')
},
created() {
calls.push('selfCreated')
},
render() {}
}
renderToString(h(Comp))
expect(calls).toEqual([
'beforeCreateA',
'beforeCreateB',
'beforeCreateC',
'beforeCreateD',
'selfBeforeCreate',
'createdA',
'createdB',
'createdC',
'createdD',
'selfCreated'
])
})
test('flatten merged options', async () => {
const MixinBase = {
msg1: 'base'
}
const ExtendsBase = {
msg2: 'base'
}
const Mixin = {
mixins: [MixinBase]
}
const Extends = {
extends: ExtendsBase
}
const Comp = defineComponent({
extends: defineComponent(Extends),
mixins: [defineComponent(Mixin)],
render() {
return `${this.$options.msg1},${this.$options.msg2}`
}
})
expect(renderToString(h(Comp))).toBe('base,base')
})
test('options defined in component have higher priority', async () => {
const Mixin = {
msg1: 'base'
}
const Extends = {
msg2: 'base'
}
const Comp = defineComponent({
msg1: 'local',
msg2: 'local',
extends: defineComponent(Extends),
mixins: [defineComponent(Mixin)],
render() {
return `${this.$options.msg1},${this.$options.msg2}`
}
})
expect(renderToString(h(Comp))).toBe('local,local')
})
test('accessing setup() state from options', async () => {
const Comp = defineComponent({
setup() {
return {
count: ref(0)
}
},
data() {
return {
plusOne: (this as any).count + 1
}
},
computed: {
plusTwo(): number {
return this.count + 2
}
},
methods: {
inc() {
this.count++
}
},
render() {
return h(
'div',
{
onClick: this.inc
},
`${this.count},${this.plusOne},${this.plusTwo}`
)
}
})
const root = nodeOps.createElement('div')
render(h(Comp), root)
expect(serializeInner(root)).toBe(`<div>0,1,2</div>`)
triggerEvent(root.children[0] as TestElement, 'click')
await nextTick()
expect(serializeInner(root)).toBe(`<div>1,1,3</div>`)
})
// #1016
test('watcher initialization should be deferred in mixins', async () => {
const mixin1 = {
data() {
return {
mixin1Data: 'mixin1'
}
},
methods: {}
}
const watchSpy = jest.fn()
const mixin2 = {
watch: {
mixin3Data: watchSpy
}
}
const mixin3 = {
data() {
return {
mixin3Data: 'mixin3'
}
},
methods: {}
}
let vm: any
const Comp = {
mixins: [mixin1, mixin2, mixin3],
render() {},
created() {
vm = this
}
}
const root = nodeOps.createElement('div')
render(h(Comp), root)
// should have no warnings
vm.mixin3Data = 'hello'
await nextTick()
expect(watchSpy.mock.calls[0].slice(0, 2)).toEqual(['hello', 'mixin3'])
})
test('injection from closest ancestor', () => {
const Root = defineComponent({
provide: {
a: 'root'
},
render() {
return [h(Mid), ' ', h(MidWithProvide), ' ', h(MidWithMixinProvide)]
}
})
const Mid = {
render() {
return h(Child)
}
} as any
const MidWithProvide = {
provide: {
a: 'midWithProvide'
},
render() {
return h(Child)
}
} as any
const mixin = {
provide: {
a: 'midWithMixinProvide'
}
}
const MidWithMixinProvide = {
mixins: [mixin],
render() {
return h(Child)
}
} as any
const Child = {
inject: ['a'],
render() {
return this.a
}
} as any
expect(renderToString(h(Root))).toBe(
'root midWithProvide midWithMixinProvide'
)
})
describe('warnings', () => {
test('Expected a function as watch handler', () => {
const Comp = {
watch: {
foo: 'notExistingMethod',
foo2: {
handler: 'notExistingMethod2'
}
},
render() {}
}
const root = nodeOps.createElement('div')
render(h(Comp), root)
expect(
'Invalid watch handler specified by key "notExistingMethod"'
).toHaveBeenWarned()
expect(
'Invalid watch handler specified by key "notExistingMethod2"'
).toHaveBeenWarned()
})
test('Invalid watch option', () => {
const Comp = {
watch: { foo: true },
render() {}
}
const root = nodeOps.createElement('div')
// @ts-ignore
render(h(Comp), root)
expect('Invalid watch option: "foo"').toHaveBeenWarned()
})
test('computed with setter and no getter', () => {
const Comp = {
computed: {
foo: {
set() {}
}
},
render() {}
}
const root = nodeOps.createElement('div')
render(h(Comp), root)
expect('Computed property "foo" has no getter.').toHaveBeenWarned()
})
test('assigning to computed with no setter', () => {
let instance: any
const Comp = {
computed: {
foo: {
get() {}
}
},
mounted() {
instance = this
},
render() {}
}
const root = nodeOps.createElement('div')
render(h(Comp), root)
instance.foo = 1
expect(
'Write operation failed: computed property "foo" is readonly'
).toHaveBeenWarned()
})
test('inject property is already declared in props', () => {
const Comp = {
data() {
return {
a: 1
}
},
provide() {
return {
a: this.a
}
},
render() {
return [h(ChildA)]
}
} as any
const ChildA = {
props: { a: Number },
inject: ['a'],
render() {
return this.a
}
} as any
const root = nodeOps.createElement('div')
render(h(Comp), root)
expect(
`Inject property "a" is already defined in Props.`
).toHaveBeenWarned()
})
test('methods property is not a function', () => {
const Comp = {
methods: {
foo: 1
},
render() {}
}
const root = nodeOps.createElement('div')
render(h(Comp), root)
expect(
`Method "foo" has type "number" in the component definition. ` +
`Did you reference the function correctly?`
).toHaveBeenWarned()
})
test('methods property is already declared in props', () => {
const Comp = {
props: {
foo: Number
},
methods: {
foo() {}
},
render() {}
}
const root = nodeOps.createElement('div')
render(h(Comp), root)
expect(
`Methods property "foo" is already defined in Props.`
).toHaveBeenWarned()
})
test('methods property is already declared in inject', () => {
const Comp = {
data() {
return {
a: 1
}
},
provide() {
return {
a: this.a
}
},
render() {
return [h(ChildA)]
}
} as any
const ChildA = {
methods: {
a: () => null
},
inject: ['a'],
render() {
return this.a
}
} as any
const root = nodeOps.createElement('div')
render(h(Comp), root)
expect(
`Methods property "a" is already defined in Inject.`
).toHaveBeenWarned()
})
test('data property is already declared in props', () => {
const Comp = {
props: { foo: Number },
data: () => ({
foo: 1
}),
render() {}
}
const root = nodeOps.createElement('div')
render(h(Comp), root)
expect(
`Data property "foo" is already defined in Props.`
).toHaveBeenWarned()
})
test('data property is already declared in inject', () => {
const Comp = {
data() {
return {
a: 1
}
},
provide() {
return {
a: this.a
}
},
render() {
return [h(ChildA)]
}
} as any
const ChildA = {
data() {
return {
a: 1
}
},
inject: ['a'],
render() {
return this.a
}
} as any
const root = nodeOps.createElement('div')
render(h(Comp), root)
expect(
`Data property "a" is already defined in Inject.`
).toHaveBeenWarned()
})
test('data property is already declared in methods', () => {
const Comp = {
data: () => ({
foo: 1
}),
methods: {
foo() {}
},
render() {}
}
const root = nodeOps.createElement('div')
render(h(Comp), root)
expect(
`Data property "foo" is already defined in Methods.`
).toHaveBeenWarned()
})
test('computed property is already declared in props', () => {
const Comp = {
props: { foo: Number },
computed: {
foo() {}
},
render() {}
}
const root = nodeOps.createElement('div')
render(h(Comp), root)
expect(
`Computed property "foo" is already defined in Props.`
).toHaveBeenWarned()
})
test('computed property is already declared in inject', () => {
const Comp = {
data() {
return {
a: 1
}
},
provide() {
return {
a: this.a
}
},
render() {
return [h(ChildA)]
}
} as any
const ChildA = {
computed: {
a: {
get() {},
set() {}
}
},
inject: ['a'],
render() {
return this.a
}
} as any
const root = nodeOps.createElement('div')
render(h(Comp), root)
expect(
`Computed property "a" is already defined in Inject.`
).toHaveBeenWarned()
})
test('computed property is already declared in methods', () => {
const Comp = {
computed: {
foo() {}
},
methods: {
foo() {}
},
render() {}
}
const root = nodeOps.createElement('div')
render(h(Comp), root)
expect(
`Computed property "foo" is already defined in Methods.`
).toHaveBeenWarned()
})
test('computed property is already declared in data', () => {
const Comp = {
data: () => ({
foo: 1
}),
computed: {
foo() {}
},
render() {}
}
const root = nodeOps.createElement('div')
render(h(Comp), root)
expect(
`Computed property "foo" is already defined in Data.`
).toHaveBeenWarned()
})
})
})
| packages/runtime-core/__tests__/apiOptions.spec.ts | 0 | https://github.com/vuejs/core/commit/3532b2b0213268a285cacce9b38f806e6af29a61 | [
0.00023431044246535748,
0.0001724301982903853,
0.00016159663209691644,
0.00017153211229015142,
0.00000825104143586941
] |
{
"id": 0,
"code_window": [
" },\n",
" \"aio-local\": {\n",
" \"master\": {\n",
" \"uncompressed\": {\n",
" \"runtime-es2015\": 2987,\n",
" \"main-es2015\": 451406,\n",
" \"polyfills-es2015\": 52630\n",
" }\n",
" }\n",
" },\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" \"main-es2015\": 450883,\n"
],
"file_path": "goldens/size-tracking/aio-payloads.json",
"type": "replace",
"edit_start_line_idx": 14
} | {
"aio": {
"master": {
"uncompressed": {
"runtime-es2015": 2987,
"main-es2015": 453213,
"polyfills-es2015": 52685
}
}
},
"aio-local": {
"master": {
"uncompressed": {
"runtime-es2015": 2987,
"main-es2015": 451406,
"polyfills-es2015": 52630
}
}
},
"aio-local-viewengine": {
"master": {
"uncompressed": {
"runtime-es2015": 3097,
"main-es2015": 429710,
"polyfills-es2015": 52195
}
}
}
}
| goldens/size-tracking/aio-payloads.json | 1 | https://github.com/angular/angular/commit/2038568f3e631cb15e9149945692e98ad2c8729d | [
0.9965169429779053,
0.33368536829948425,
0.00019904112559743226,
0.004340050742030144,
0.4686957597732544
] |
{
"id": 0,
"code_window": [
" },\n",
" \"aio-local\": {\n",
" \"master\": {\n",
" \"uncompressed\": {\n",
" \"runtime-es2015\": 2987,\n",
" \"main-es2015\": 451406,\n",
" \"polyfills-es2015\": 52630\n",
" }\n",
" }\n",
" },\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" \"main-es2015\": 450883,\n"
],
"file_path": "goldens/size-tracking/aio-payloads.json",
"type": "replace",
"edit_start_line_idx": 14
} | // #docplaster
// #docregion
import { Component } from '@angular/core';
import { Hero } from './hero';
// #enddocregion
import { HeroService } from './hero.service.1';
/*
// #docregion
import { HeroService } from './hero.service';
// #enddocregion
*/
// #docregion
@Component({
selector: 'app-hero-list',
template: `
<div *ngFor="let hero of heroes">
{{hero.id}} - {{hero.name}}
</div>
`
})
export class HeroListComponent {
heroes: Hero[];
// #docregion ctor
constructor(heroService: HeroService) {
this.heroes = heroService.getHeroes();
}
// #enddocregion ctor
}
| aio/content/examples/dependency-injection/src/app/heroes/hero-list.component.2.ts | 0 | https://github.com/angular/angular/commit/2038568f3e631cb15e9149945692e98ad2c8729d | [
0.00017637510609347373,
0.00017508577730040997,
0.00017294417193625122,
0.00017551191558595747,
0.0000013106575806887122
] |
{
"id": 0,
"code_window": [
" },\n",
" \"aio-local\": {\n",
" \"master\": {\n",
" \"uncompressed\": {\n",
" \"runtime-es2015\": 2987,\n",
" \"main-es2015\": 451406,\n",
" \"polyfills-es2015\": 52630\n",
" }\n",
" }\n",
" },\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" \"main-es2015\": 450883,\n"
],
"file_path": "goldens/size-tracking/aio-payloads.json",
"type": "replace",
"edit_start_line_idx": 14
} | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* @fileoverview
* @suppress {missingRequire}
*/
import {ADD_EVENT_LISTENER_STR, attachOriginToPatched, FALSE_STR, isNode, ObjectGetPrototypeOf, REMOVE_EVENT_LISTENER_STR, TRUE_STR, ZONE_SYMBOL_PREFIX, zoneSymbol} from './utils';
/** @internal **/
interface EventTaskData extends TaskData {
// use global callback or not
readonly useG?: boolean;
}
let passiveSupported = false;
if (typeof window !== 'undefined') {
try {
const options = Object.defineProperty({}, 'passive', {
get: function() {
passiveSupported = true;
}
});
window.addEventListener('test', options, options);
window.removeEventListener('test', options, options);
} catch (err) {
passiveSupported = false;
}
}
// an identifier to tell ZoneTask do not create a new invoke closure
const OPTIMIZED_ZONE_EVENT_TASK_DATA: EventTaskData = {
useG: true
};
export const zoneSymbolEventNames: any = {};
export const globalSources: any = {};
const EVENT_NAME_SYMBOL_REGX = new RegExp('^' + ZONE_SYMBOL_PREFIX + '(\\w+)(true|false)$');
const IMMEDIATE_PROPAGATION_SYMBOL = zoneSymbol('propagationStopped');
function prepareEventNames(eventName: string, eventNameToString?: (eventName: string) => string) {
const falseEventName = (eventNameToString ? eventNameToString(eventName) : eventName) + FALSE_STR;
const trueEventName = (eventNameToString ? eventNameToString(eventName) : eventName) + TRUE_STR;
const symbol = ZONE_SYMBOL_PREFIX + falseEventName;
const symbolCapture = ZONE_SYMBOL_PREFIX + trueEventName;
zoneSymbolEventNames[eventName] = {};
zoneSymbolEventNames[eventName][FALSE_STR] = symbol;
zoneSymbolEventNames[eventName][TRUE_STR] = symbolCapture;
}
export interface PatchEventTargetOptions {
// validateHandler
vh?: (nativeDelegate: any, delegate: any, target: any, args: any) => boolean;
// addEventListener function name
add?: string;
// removeEventListener function name
rm?: string;
// prependEventListener function name
prepend?: string;
// listeners function name
listeners?: string;
// removeAllListeners function name
rmAll?: string;
// useGlobalCallback flag
useG?: boolean;
// check duplicate flag when addEventListener
chkDup?: boolean;
// return target flag when addEventListener
rt?: boolean;
// event compare handler
diff?: (task: any, delegate: any) => boolean;
// support passive or not
supportPassive?: boolean;
// get string from eventName (in nodejs, eventName maybe Symbol)
eventNameToString?: (eventName: any) => string;
// transfer eventName
transferEventName?: (eventName: string) => string;
}
export function patchEventTarget(
_global: any, apis: any[], patchOptions?: PatchEventTargetOptions) {
const ADD_EVENT_LISTENER = (patchOptions && patchOptions.add) || ADD_EVENT_LISTENER_STR;
const REMOVE_EVENT_LISTENER = (patchOptions && patchOptions.rm) || REMOVE_EVENT_LISTENER_STR;
const LISTENERS_EVENT_LISTENER = (patchOptions && patchOptions.listeners) || 'eventListeners';
const REMOVE_ALL_LISTENERS_EVENT_LISTENER =
(patchOptions && patchOptions.rmAll) || 'removeAllListeners';
const zoneSymbolAddEventListener = zoneSymbol(ADD_EVENT_LISTENER);
const ADD_EVENT_LISTENER_SOURCE = '.' + ADD_EVENT_LISTENER + ':';
const PREPEND_EVENT_LISTENER = 'prependListener';
const PREPEND_EVENT_LISTENER_SOURCE = '.' + PREPEND_EVENT_LISTENER + ':';
const invokeTask = function(task: any, target: any, event: Event) {
// for better performance, check isRemoved which is set
// by removeEventListener
if (task.isRemoved) {
return;
}
const delegate = task.callback;
if (typeof delegate === 'object' && delegate.handleEvent) {
// create the bind version of handleEvent when invoke
task.callback = (event: Event) => delegate.handleEvent(event);
task.originalDelegate = delegate;
}
// invoke static task.invoke
task.invoke(task, target, [event]);
const options = task.options;
if (options && typeof options === 'object' && options.once) {
// if options.once is true, after invoke once remove listener here
// only browser need to do this, nodejs eventEmitter will cal removeListener
// inside EventEmitter.once
const delegate = task.originalDelegate ? task.originalDelegate : task.callback;
target[REMOVE_EVENT_LISTENER].call(target, event.type, delegate, options);
}
};
// global shared zoneAwareCallback to handle all event callback with capture = false
const globalZoneAwareCallback = function(this: unknown, event: Event) {
// https://github.com/angular/zone.js/issues/911, in IE, sometimes
// event will be undefined, so we need to use window.event
event = event || _global.event;
if (!event) {
return;
}
// event.target is needed for Samsung TV and SourceBuffer
// || global is needed https://github.com/angular/zone.js/issues/190
const target: any = this || event.target || _global;
const tasks = target[zoneSymbolEventNames[event.type][FALSE_STR]];
if (tasks) {
// invoke all tasks which attached to current target with given event.type and capture = false
// for performance concern, if task.length === 1, just invoke
if (tasks.length === 1) {
invokeTask(tasks[0], target, event);
} else {
// https://github.com/angular/zone.js/issues/836
// copy the tasks array before invoke, to avoid
// the callback will remove itself or other listener
const copyTasks = tasks.slice();
for (let i = 0; i < copyTasks.length; i++) {
if (event && (event as any)[IMMEDIATE_PROPAGATION_SYMBOL] === true) {
break;
}
invokeTask(copyTasks[i], target, event);
}
}
}
};
// global shared zoneAwareCallback to handle all event callback with capture = true
const globalZoneAwareCaptureCallback = function(this: unknown, event: Event) {
// https://github.com/angular/zone.js/issues/911, in IE, sometimes
// event will be undefined, so we need to use window.event
event = event || _global.event;
if (!event) {
return;
}
// event.target is needed for Samsung TV and SourceBuffer
// || global is needed https://github.com/angular/zone.js/issues/190
const target: any = this || event.target || _global;
const tasks = target[zoneSymbolEventNames[event.type][TRUE_STR]];
if (tasks) {
// invoke all tasks which attached to current target with given event.type and capture = false
// for performance concern, if task.length === 1, just invoke
if (tasks.length === 1) {
invokeTask(tasks[0], target, event);
} else {
// https://github.com/angular/zone.js/issues/836
// copy the tasks array before invoke, to avoid
// the callback will remove itself or other listener
const copyTasks = tasks.slice();
for (let i = 0; i < copyTasks.length; i++) {
if (event && (event as any)[IMMEDIATE_PROPAGATION_SYMBOL] === true) {
break;
}
invokeTask(copyTasks[i], target, event);
}
}
}
};
function patchEventTargetMethods(obj: any, patchOptions?: PatchEventTargetOptions) {
if (!obj) {
return false;
}
let useGlobalCallback = true;
if (patchOptions && patchOptions.useG !== undefined) {
useGlobalCallback = patchOptions.useG;
}
const validateHandler = patchOptions && patchOptions.vh;
let checkDuplicate = true;
if (patchOptions && patchOptions.chkDup !== undefined) {
checkDuplicate = patchOptions.chkDup;
}
let returnTarget = false;
if (patchOptions && patchOptions.rt !== undefined) {
returnTarget = patchOptions.rt;
}
let proto = obj;
while (proto && !proto.hasOwnProperty(ADD_EVENT_LISTENER)) {
proto = ObjectGetPrototypeOf(proto);
}
if (!proto && obj[ADD_EVENT_LISTENER]) {
// somehow we did not find it, but we can see it. This happens on IE for Window properties.
proto = obj;
}
if (!proto) {
return false;
}
if (proto[zoneSymbolAddEventListener]) {
return false;
}
const eventNameToString = patchOptions && patchOptions.eventNameToString;
// a shared global taskData to pass data for scheduleEventTask
// so we do not need to create a new object just for pass some data
const taskData: any = {};
const nativeAddEventListener = proto[zoneSymbolAddEventListener] = proto[ADD_EVENT_LISTENER];
const nativeRemoveEventListener = proto[zoneSymbol(REMOVE_EVENT_LISTENER)] =
proto[REMOVE_EVENT_LISTENER];
const nativeListeners = proto[zoneSymbol(LISTENERS_EVENT_LISTENER)] =
proto[LISTENERS_EVENT_LISTENER];
const nativeRemoveAllListeners = proto[zoneSymbol(REMOVE_ALL_LISTENERS_EVENT_LISTENER)] =
proto[REMOVE_ALL_LISTENERS_EVENT_LISTENER];
let nativePrependEventListener: any;
if (patchOptions && patchOptions.prepend) {
nativePrependEventListener = proto[zoneSymbol(patchOptions.prepend)] =
proto[patchOptions.prepend];
}
/**
* This util function will build an option object with passive option
* to handle all possible input from the user.
*/
function buildEventListenerOptions(options: any, passive: boolean) {
if (!passiveSupported && typeof options === 'object' && options) {
// doesn't support passive but user want to pass an object as options.
// this will not work on some old browser, so we just pass a boolean
// as useCapture parameter
return !!options.capture;
}
if (!passiveSupported || !passive) {
return options;
}
if (typeof options === 'boolean') {
return {capture: options, passive: true};
}
if (!options) {
return {passive: true};
}
if (typeof options === 'object' && options.passive !== false) {
return {...options, passive: true};
}
return options;
}
const customScheduleGlobal = function(task: Task) {
// if there is already a task for the eventName + capture,
// just return, because we use the shared globalZoneAwareCallback here.
if (taskData.isExisting) {
return;
}
return nativeAddEventListener.call(
taskData.target, taskData.eventName,
taskData.capture ? globalZoneAwareCaptureCallback : globalZoneAwareCallback,
taskData.options);
};
const customCancelGlobal = function(task: any) {
// if task is not marked as isRemoved, this call is directly
// from Zone.prototype.cancelTask, we should remove the task
// from tasksList of target first
if (!task.isRemoved) {
const symbolEventNames = zoneSymbolEventNames[task.eventName];
let symbolEventName;
if (symbolEventNames) {
symbolEventName = symbolEventNames[task.capture ? TRUE_STR : FALSE_STR];
}
const existingTasks = symbolEventName && task.target[symbolEventName];
if (existingTasks) {
for (let i = 0; i < existingTasks.length; i++) {
const existingTask = existingTasks[i];
if (existingTask === task) {
existingTasks.splice(i, 1);
// set isRemoved to data for faster invokeTask check
task.isRemoved = true;
if (existingTasks.length === 0) {
// all tasks for the eventName + capture have gone,
// remove globalZoneAwareCallback and remove the task cache from target
task.allRemoved = true;
task.target[symbolEventName] = null;
}
break;
}
}
}
}
// if all tasks for the eventName + capture have gone,
// we will really remove the global event callback,
// if not, return
if (!task.allRemoved) {
return;
}
return nativeRemoveEventListener.call(
task.target, task.eventName,
task.capture ? globalZoneAwareCaptureCallback : globalZoneAwareCallback, task.options);
};
const customScheduleNonGlobal = function(task: Task) {
return nativeAddEventListener.call(
taskData.target, taskData.eventName, task.invoke, taskData.options);
};
const customSchedulePrepend = function(task: Task) {
return nativePrependEventListener.call(
taskData.target, taskData.eventName, task.invoke, taskData.options);
};
const customCancelNonGlobal = function(task: any) {
return nativeRemoveEventListener.call(task.target, task.eventName, task.invoke, task.options);
};
const customSchedule = useGlobalCallback ? customScheduleGlobal : customScheduleNonGlobal;
const customCancel = useGlobalCallback ? customCancelGlobal : customCancelNonGlobal;
const compareTaskCallbackVsDelegate = function(task: any, delegate: any) {
const typeOfDelegate = typeof delegate;
return (typeOfDelegate === 'function' && task.callback === delegate) ||
(typeOfDelegate === 'object' && task.originalDelegate === delegate);
};
const compare =
(patchOptions && patchOptions.diff) ? patchOptions.diff : compareTaskCallbackVsDelegate;
const blackListedEvents: string[] = (Zone as any)[zoneSymbol('BLACK_LISTED_EVENTS')];
const passiveEvents: string[] = _global[zoneSymbol('PASSIVE_EVENTS')];
const makeAddListener = function(
nativeListener: any, addSource: string, customScheduleFn: any, customCancelFn: any,
returnTarget = false, prepend = false) {
return function(this: unknown) {
const target = this || _global;
let eventName = arguments[0];
if (patchOptions && patchOptions.transferEventName) {
eventName = patchOptions.transferEventName(eventName);
}
let delegate = arguments[1];
if (!delegate) {
return nativeListener.apply(this, arguments);
}
if (isNode && eventName === 'uncaughtException') {
// don't patch uncaughtException of nodejs to prevent endless loop
return nativeListener.apply(this, arguments);
}
// don't create the bind delegate function for handleEvent
// case here to improve addEventListener performance
// we will create the bind delegate when invoke
let isHandleEvent = false;
if (typeof delegate !== 'function') {
if (!delegate.handleEvent) {
return nativeListener.apply(this, arguments);
}
isHandleEvent = true;
}
if (validateHandler && !validateHandler(nativeListener, delegate, target, arguments)) {
return;
}
const passive =
passiveSupported && !!passiveEvents && passiveEvents.indexOf(eventName) !== -1;
const options = buildEventListenerOptions(arguments[2], passive);
if (blackListedEvents) {
// check black list
for (let i = 0; i < blackListedEvents.length; i++) {
if (eventName === blackListedEvents[i]) {
if (passive) {
return nativeListener.call(target, eventName, delegate, options);
} else {
return nativeListener.apply(this, arguments);
}
}
}
}
const capture = !options ? false : typeof options === 'boolean' ? true : options.capture;
const once = options && typeof options === 'object' ? options.once : false;
const zone = Zone.current;
let symbolEventNames = zoneSymbolEventNames[eventName];
if (!symbolEventNames) {
prepareEventNames(eventName, eventNameToString);
symbolEventNames = zoneSymbolEventNames[eventName];
}
const symbolEventName = symbolEventNames[capture ? TRUE_STR : FALSE_STR];
let existingTasks = target[symbolEventName];
let isExisting = false;
if (existingTasks) {
// already have task registered
isExisting = true;
if (checkDuplicate) {
for (let i = 0; i < existingTasks.length; i++) {
if (compare(existingTasks[i], delegate)) {
// same callback, same capture, same event name, just return
return;
}
}
}
} else {
existingTasks = target[symbolEventName] = [];
}
let source;
const constructorName = target.constructor['name'];
const targetSource = globalSources[constructorName];
if (targetSource) {
source = targetSource[eventName];
}
if (!source) {
source = constructorName + addSource +
(eventNameToString ? eventNameToString(eventName) : eventName);
}
// do not create a new object as task.data to pass those things
// just use the global shared one
taskData.options = options;
if (once) {
// if addEventListener with once options, we don't pass it to
// native addEventListener, instead we keep the once setting
// and handle ourselves.
taskData.options.once = false;
}
taskData.target = target;
taskData.capture = capture;
taskData.eventName = eventName;
taskData.isExisting = isExisting;
const data = useGlobalCallback ? OPTIMIZED_ZONE_EVENT_TASK_DATA : undefined;
// keep taskData into data to allow onScheduleEventTask to access the task information
if (data) {
(data as any).taskData = taskData;
}
const task: any =
zone.scheduleEventTask(source, delegate, data, customScheduleFn, customCancelFn);
// should clear taskData.target to avoid memory leak
// issue, https://github.com/angular/angular/issues/20442
taskData.target = null;
// need to clear up taskData because it is a global object
if (data) {
(data as any).taskData = null;
}
// have to save those information to task in case
// application may call task.zone.cancelTask() directly
if (once) {
options.once = true;
}
if (!(!passiveSupported && typeof task.options === 'boolean')) {
// if not support passive, and we pass an option object
// to addEventListener, we should save the options to task
task.options = options;
}
task.target = target;
task.capture = capture;
task.eventName = eventName;
if (isHandleEvent) {
// save original delegate for compare to check duplicate
(task as any).originalDelegate = delegate;
}
if (!prepend) {
existingTasks.push(task);
} else {
existingTasks.unshift(task);
}
if (returnTarget) {
return target;
}
};
};
proto[ADD_EVENT_LISTENER] = makeAddListener(
nativeAddEventListener, ADD_EVENT_LISTENER_SOURCE, customSchedule, customCancel,
returnTarget);
if (nativePrependEventListener) {
proto[PREPEND_EVENT_LISTENER] = makeAddListener(
nativePrependEventListener, PREPEND_EVENT_LISTENER_SOURCE, customSchedulePrepend,
customCancel, returnTarget, true);
}
proto[REMOVE_EVENT_LISTENER] = function() {
const target = this || _global;
let eventName = arguments[0];
if (patchOptions && patchOptions.transferEventName) {
eventName = patchOptions.transferEventName(eventName);
}
const options = arguments[2];
const capture = !options ? false : typeof options === 'boolean' ? true : options.capture;
const delegate = arguments[1];
if (!delegate) {
return nativeRemoveEventListener.apply(this, arguments);
}
if (validateHandler &&
!validateHandler(nativeRemoveEventListener, delegate, target, arguments)) {
return;
}
const symbolEventNames = zoneSymbolEventNames[eventName];
let symbolEventName;
if (symbolEventNames) {
symbolEventName = symbolEventNames[capture ? TRUE_STR : FALSE_STR];
}
const existingTasks = symbolEventName && target[symbolEventName];
if (existingTasks) {
for (let i = 0; i < existingTasks.length; i++) {
const existingTask = existingTasks[i];
if (compare(existingTask, delegate)) {
existingTasks.splice(i, 1);
// set isRemoved to data for faster invokeTask check
(existingTask as any).isRemoved = true;
if (existingTasks.length === 0) {
// all tasks for the eventName + capture have gone,
// remove globalZoneAwareCallback and remove the task cache from target
(existingTask as any).allRemoved = true;
target[symbolEventName] = null;
// in the target, we have an event listener which is added by on_property
// such as target.onclick = function() {}, so we need to clear this internal
// property too if all delegates all removed
if (typeof eventName === 'string') {
const onPropertySymbol = ZONE_SYMBOL_PREFIX + 'ON_PROPERTY' + eventName;
target[onPropertySymbol] = null;
}
}
existingTask.zone.cancelTask(existingTask);
if (returnTarget) {
return target;
}
return;
}
}
}
// issue 930, didn't find the event name or callback
// from zone kept existingTasks, the callback maybe
// added outside of zone, we need to call native removeEventListener
// to try to remove it.
return nativeRemoveEventListener.apply(this, arguments);
};
proto[LISTENERS_EVENT_LISTENER] = function() {
const target = this || _global;
let eventName = arguments[0];
if (patchOptions && patchOptions.transferEventName) {
eventName = patchOptions.transferEventName(eventName);
}
const listeners: any[] = [];
const tasks =
findEventTasks(target, eventNameToString ? eventNameToString(eventName) : eventName);
for (let i = 0; i < tasks.length; i++) {
const task: any = tasks[i];
let delegate = task.originalDelegate ? task.originalDelegate : task.callback;
listeners.push(delegate);
}
return listeners;
};
proto[REMOVE_ALL_LISTENERS_EVENT_LISTENER] = function() {
const target = this || _global;
let eventName = arguments[0];
if (!eventName) {
const keys = Object.keys(target);
for (let i = 0; i < keys.length; i++) {
const prop = keys[i];
const match = EVENT_NAME_SYMBOL_REGX.exec(prop);
let evtName = match && match[1];
// in nodejs EventEmitter, removeListener event is
// used for monitoring the removeListener call,
// so just keep removeListener eventListener until
// all other eventListeners are removed
if (evtName && evtName !== 'removeListener') {
this[REMOVE_ALL_LISTENERS_EVENT_LISTENER].call(this, evtName);
}
}
// remove removeListener listener finally
this[REMOVE_ALL_LISTENERS_EVENT_LISTENER].call(this, 'removeListener');
} else {
if (patchOptions && patchOptions.transferEventName) {
eventName = patchOptions.transferEventName(eventName);
}
const symbolEventNames = zoneSymbolEventNames[eventName];
if (symbolEventNames) {
const symbolEventName = symbolEventNames[FALSE_STR];
const symbolCaptureEventName = symbolEventNames[TRUE_STR];
const tasks = target[symbolEventName];
const captureTasks = target[symbolCaptureEventName];
if (tasks) {
const removeTasks = tasks.slice();
for (let i = 0; i < removeTasks.length; i++) {
const task = removeTasks[i];
let delegate = task.originalDelegate ? task.originalDelegate : task.callback;
this[REMOVE_EVENT_LISTENER].call(this, eventName, delegate, task.options);
}
}
if (captureTasks) {
const removeTasks = captureTasks.slice();
for (let i = 0; i < removeTasks.length; i++) {
const task = removeTasks[i];
let delegate = task.originalDelegate ? task.originalDelegate : task.callback;
this[REMOVE_EVENT_LISTENER].call(this, eventName, delegate, task.options);
}
}
}
}
if (returnTarget) {
return this;
}
};
// for native toString patch
attachOriginToPatched(proto[ADD_EVENT_LISTENER], nativeAddEventListener);
attachOriginToPatched(proto[REMOVE_EVENT_LISTENER], nativeRemoveEventListener);
if (nativeRemoveAllListeners) {
attachOriginToPatched(proto[REMOVE_ALL_LISTENERS_EVENT_LISTENER], nativeRemoveAllListeners);
}
if (nativeListeners) {
attachOriginToPatched(proto[LISTENERS_EVENT_LISTENER], nativeListeners);
}
return true;
}
let results: any[] = [];
for (let i = 0; i < apis.length; i++) {
results[i] = patchEventTargetMethods(apis[i], patchOptions);
}
return results;
}
export function findEventTasks(target: any, eventName: string): Task[] {
if (!eventName) {
const foundTasks: any[] = [];
for (let prop in target) {
const match = EVENT_NAME_SYMBOL_REGX.exec(prop);
let evtName = match && match[1];
if (evtName && (!eventName || evtName === eventName)) {
const tasks: any = target[prop];
if (tasks) {
for (let i = 0; i < tasks.length; i++) {
foundTasks.push(tasks[i]);
}
}
}
}
return foundTasks;
}
let symbolEventName = zoneSymbolEventNames[eventName];
if (!symbolEventName) {
prepareEventNames(eventName);
symbolEventName = zoneSymbolEventNames[eventName];
}
const captureFalseTasks = target[symbolEventName[FALSE_STR]];
const captureTrueTasks = target[symbolEventName[TRUE_STR]];
if (!captureFalseTasks) {
return captureTrueTasks ? captureTrueTasks.slice() : [];
} else {
return captureTrueTasks ? captureFalseTasks.concat(captureTrueTasks) :
captureFalseTasks.slice();
}
}
export function patchEventPrototype(global: any, api: _ZonePrivate) {
const Event = global['Event'];
if (Event && Event.prototype) {
api.patchMethod(
Event.prototype, 'stopImmediatePropagation',
(delegate: Function) => function(self: any, args: any[]) {
self[IMMEDIATE_PROPAGATION_SYMBOL] = true;
// we need to call the native stopImmediatePropagation
// in case in some hybrid application, some part of
// application will be controlled by zone, some are not
delegate && delegate.apply(self, args);
});
}
}
| packages/zone.js/lib/common/events.ts | 0 | https://github.com/angular/angular/commit/2038568f3e631cb15e9149945692e98ad2c8729d | [
0.000341875507729128,
0.00017475808272138238,
0.00016541490913368762,
0.00017330404079984874,
0.000020031149688293226
] |
{
"id": 0,
"code_window": [
" },\n",
" \"aio-local\": {\n",
" \"master\": {\n",
" \"uncompressed\": {\n",
" \"runtime-es2015\": 2987,\n",
" \"main-es2015\": 451406,\n",
" \"polyfills-es2015\": 52630\n",
" }\n",
" }\n",
" },\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" \"main-es2015\": 450883,\n"
],
"file_path": "goldens/size-tracking/aio-payloads.json",
"type": "replace",
"edit_start_line_idx": 14
} | {
"name": "@angular/common/http/testing"
}
| packages/common/http/testing/package.json | 0 | https://github.com/angular/angular/commit/2038568f3e631cb15e9149945692e98ad2c8729d | [
0.00017169705824926496,
0.00017169705824926496,
0.00017169705824926496,
0.00017169705824926496,
0
] |
{
"id": 1,
"code_window": [
" \"master\": {\n",
" \"uncompressed\": {\n",
" \"runtime-es2015\": 3097,\n",
" \"main-es2015\": 429710,\n",
" \"polyfills-es2015\": 52195\n",
" }\n",
" }\n",
" }\n",
"}"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" \"main-es2015\": 429200,\n"
],
"file_path": "goldens/size-tracking/aio-payloads.json",
"type": "replace",
"edit_start_line_idx": 23
} | {
"aio": {
"master": {
"uncompressed": {
"runtime-es2015": 2987,
"main-es2015": 453213,
"polyfills-es2015": 52685
}
}
},
"aio-local": {
"master": {
"uncompressed": {
"runtime-es2015": 2987,
"main-es2015": 451406,
"polyfills-es2015": 52630
}
}
},
"aio-local-viewengine": {
"master": {
"uncompressed": {
"runtime-es2015": 3097,
"main-es2015": 429710,
"polyfills-es2015": 52195
}
}
}
}
| goldens/size-tracking/aio-payloads.json | 1 | https://github.com/angular/angular/commit/2038568f3e631cb15e9149945692e98ad2c8729d | [
0.9967144727706909,
0.33235710859298706,
0.00016701914137229323,
0.0001898098853416741,
0.4697715938091278
] |
{
"id": 1,
"code_window": [
" \"master\": {\n",
" \"uncompressed\": {\n",
" \"runtime-es2015\": 3097,\n",
" \"main-es2015\": 429710,\n",
" \"polyfills-es2015\": 52195\n",
" }\n",
" }\n",
" }\n",
"}"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" \"main-es2015\": 429200,\n"
],
"file_path": "goldens/size-tracking/aio-payloads.json",
"type": "replace",
"edit_start_line_idx": 23
} | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
// THIS CODE IS GENERATED - DO NOT MODIFY
// See angular/tools/gulp-tasks/cldr/extract.js
const u = undefined;
export default [];
| packages/common/locales/extra/kln.ts | 0 | https://github.com/angular/angular/commit/2038568f3e631cb15e9149945692e98ad2c8729d | [
0.00017655716510489583,
0.00017634991672821343,
0.00017614268290344626,
0.00017634991672821343,
2.0724110072478652e-7
] |
{
"id": 1,
"code_window": [
" \"master\": {\n",
" \"uncompressed\": {\n",
" \"runtime-es2015\": 3097,\n",
" \"main-es2015\": 429710,\n",
" \"polyfills-es2015\": 52195\n",
" }\n",
" }\n",
" }\n",
"}"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" \"main-es2015\": 429200,\n"
],
"file_path": "goldens/size-tracking/aio-payloads.json",
"type": "replace",
"edit_start_line_idx": 23
} | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import '../../dist/zone-node';
const testClosureFunction = () => {
const logs: string[] = [];
// call all Zone exposed functions
const testZoneSpec: ZoneSpec = {
name: 'closure',
properties: {},
onFork:
(parentZoneDelegate: ZoneDelegate, currentZone: Zone, targetZone: Zone,
zoneSpec: ZoneSpec) => {
return parentZoneDelegate.fork(targetZone, zoneSpec);
},
onIntercept:
(parentZoneDelegate: ZoneDelegate, currentZone: Zone, targetZone: Zone, delegate: Function,
source: string) => {
return parentZoneDelegate.intercept(targetZone, delegate, source);
},
onInvoke: function(
parentZoneDelegate: ZoneDelegate, currentZone: Zone, targetZone: Zone, delegate: Function,
applyThis?: any, applyArgs?: any[], source?: string) {
return parentZoneDelegate.invoke(targetZone, delegate, applyThis, applyArgs, source);
},
onHandleError: function(
parentZoneDelegate: ZoneDelegate, currentZone: Zone, targetZone: Zone, error: any) {
return parentZoneDelegate.handleError(targetZone, error);
},
onScheduleTask: function(
parentZoneDelegate: ZoneDelegate, currentZone: Zone, targetZone: Zone, task: Task) {
return parentZoneDelegate.scheduleTask(targetZone, task);
},
onInvokeTask: function(
parentZoneDelegate: ZoneDelegate, currentZone: Zone, targetZone: Zone, task: Task,
applyThis?: any, applyArgs?: any[]) {
return parentZoneDelegate.invokeTask(targetZone, task, applyThis, applyArgs);
},
onCancelTask: function(
parentZoneDelegate: ZoneDelegate, currentZone: Zone, targetZone: Zone, task: Task) {
return parentZoneDelegate.cancelTask(targetZone, task);
},
onHasTask: function(
delegate: ZoneDelegate, current: Zone, target: Zone, hasTaskState: HasTaskState) {
return delegate.hasTask(target, hasTaskState);
}
};
Zone.__load_patch('test_closure_load_patch', function() {});
Zone.__symbol__('test_symbol');
const testZone: Zone = Zone.current.fork(testZoneSpec);
testZone.runGuarded(() => {
testZone.run(() => {
const properties = testZoneSpec.properties;
properties!['key'] = 'value';
const keyZone = Zone.current.getZoneWith('key');
logs.push('current' + Zone.current.name);
logs.push('parent' + Zone.current.parent!.name);
logs.push('getZoneWith' + keyZone!.name);
logs.push('get' + keyZone!.get('key'));
logs.push('root' + Zone.root.name);
Object.keys((Zone as any).prototype).forEach(key => {
logs.push(key);
});
Object.keys(testZoneSpec).forEach(key => {
logs.push(key);
});
const task = Zone.current.scheduleMicroTask('testTask', () => {}, undefined, () => {});
Object.keys(task).forEach(key => {
logs.push(key);
});
});
});
const expectedResult = [
'currentclosure',
'parent<root>',
'getZoneWithclosure',
'getvalue',
'root<root>',
'parent',
'name',
'get',
'getZoneWith',
'fork',
'wrap',
'run',
'runGuarded',
'runTask',
'scheduleTask',
'scheduleMicroTask',
'scheduleMacroTask',
'scheduleEventTask',
'cancelTask',
'_updateTaskCount',
'name',
'properties',
'onFork',
'onIntercept',
'onInvoke',
'onHandleError',
'onScheduleTask',
'onInvokeTask',
'onCancelTask',
'onHasTask',
'_zone',
'runCount',
'_zoneDelegates',
'_state',
'type',
'source',
'data',
'scheduleFn',
'cancelFn',
'callback',
'invoke'
];
let result: boolean = true;
for (let i = 0; i < expectedResult.length; i++) {
if (expectedResult[i] !== logs[i]) {
console.log('Not Equals', expectedResult[i], logs[i]);
result = false;
}
}
process['exit'](result ? 0 : 1);
};
process['on']('uncaughtException', (err: any) => {
process['exit'](1);
});
testClosureFunction();
| packages/zone.js/test/closure/zone.closure.ts | 0 | https://github.com/angular/angular/commit/2038568f3e631cb15e9149945692e98ad2c8729d | [
0.00017685284547042102,
0.00017472087347414345,
0.00017153621593024582,
0.00017476615903433412,
0.000001520944238109223
] |
{
"id": 1,
"code_window": [
" \"master\": {\n",
" \"uncompressed\": {\n",
" \"runtime-es2015\": 3097,\n",
" \"main-es2015\": 429710,\n",
" \"polyfills-es2015\": 52195\n",
" }\n",
" }\n",
" }\n",
"}"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" \"main-es2015\": 429200,\n"
],
"file_path": "goldens/size-tracking/aio-payloads.json",
"type": "replace",
"edit_start_line_idx": 23
} | .heroes {
margin: 0 0 2em 0;
list-style-type: none;
padding: 0;
width: 15em;
}
.heroes li {
position: relative;
height: 2.3em;
overflow:hidden;
margin: .5em;
}
.heroes li > .inner {
cursor: pointer;
background-color: #EEE;
padding: .3em 0;
height: 1.6em;
border-radius: 4px;
width: 19em;
}
.heroes li:hover > .inner {
color: #607D8B;
background-color: #DDD;
transform: translateX(.1em);
}
.heroes a {
color: #888;
text-decoration: none;
position: relative;
display: block;
width: 250px;
}
.heroes a:hover {
color:#607D8B;
}
.heroes .badge {
display: inline-block;
font-size: small;
color: white;
padding: 0.8em 0.7em 0 0.7em;
background-color: #607D8B;
line-height: 1em;
position: relative;
left: -1px;
top: -4px;
height: 1.8em;
min-width: 16px;
text-align: right;
margin-right: .8em;
border-radius: 4px 0 0 4px;
}
.button {
background-color: #eee;
border: none;
padding: 5px 10px;
border-radius: 4px;
cursor: pointer;
cursor: hand;
font-family: Arial;
}
button:hover {
background-color: #cfd8dc;
}
button.delete {
position: relative;
left: 24em;
top: -32px;
background-color: gray !important;
color: white;
display: inherit;
padding: 5px 8px;
width: 2em;
}
input {
font-size: 100%;
margin-bottom: 2px;
width: 11em;
}
.heroes input {
position: relative;
top: -3px;
width: 12em;
}
| aio/content/examples/animations/src/app/hero-list-page.component.css | 0 | https://github.com/angular/angular/commit/2038568f3e631cb15e9149945692e98ad2c8729d | [
0.00017679872689768672,
0.00017488477169536054,
0.00017171997751574963,
0.00017523685528431088,
0.0000016262076769635314
] |
{
"id": 2,
"code_window": [
" \"master\": {\n",
" \"uncompressed\": {\n",
" \"runtime-es2015\": 1485,\n",
" \"main-es2015\": 136302,\n",
" \"polyfills-es2015\": 37248\n",
" }\n",
" }\n",
" },\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" \"main-es2015\": 135533,\n"
],
"file_path": "goldens/size-tracking/integration-payloads.json",
"type": "replace",
"edit_start_line_idx": 32
} | {
"cli-hello-world": {
"master": {
"uncompressed": {
"runtime-es2015": 1485,
"main-es2015": 141151,
"polyfills-es2015": 36571
}
}
},
"cli-hello-world-ivy-minimal": {
"master": {
"uncompressed": {
"runtime-es2015": 1485,
"main-es2015": 16959,
"polyfills-es2015": 36938
}
}
},
"cli-hello-world-ivy-compat": {
"master": {
"uncompressed": {
"runtime-es2015": 1485,
"main-es2015": 147314,
"polyfills-es2015": 36571
}
}
},
"cli-hello-world-ivy-i18n": {
"master": {
"uncompressed": {
"runtime-es2015": 1485,
"main-es2015": 136302,
"polyfills-es2015": 37248
}
}
},
"cli-hello-world-lazy": {
"master": {
"uncompressed": {
"runtime-es2015": 2289,
"main-es2015": 246085,
"polyfills-es2015": 36938,
"5-es2015": 751
}
}
},
"cli-hello-world-lazy-rollup": {
"master": {
"uncompressed": {
"runtime-es2015": 2289,
"main-es2015": 221268,
"polyfills-es2015": 36938,
"5-es2015": 779
}
}
},
"hello_world__closure": {
"master": {
"uncompressed": {
"bundle": "TODO(i): temporarily increase the payload size limit from 105779 - this is due to a closure issue related to ESM reexports that still needs to be investigated",
"bundle": "TODO(i): we should define ngDevMode to false in Closure, but --define only works in the global scope.",
"bundle": "TODO(i): (FW-2164) TS 3.9 new class shape seems to have broken Closure in big ways. The size went from 169991 to 252338",
"bundle": "TODO(i): after removal of tsickle from ngc-wrapped / ng_package, we had to switch to SIMPLE optimizations which increased the size from 252338 to 1198917, see PR#37221 and PR#37317 for more info",
"bundle": 1210239
}
}
}
}
| goldens/size-tracking/integration-payloads.json | 1 | https://github.com/angular/angular/commit/2038568f3e631cb15e9149945692e98ad2c8729d | [
0.9964794516563416,
0.22828450798988342,
0.00017317435413133353,
0.0009799369145184755,
0.35572701692581177
] |
{
"id": 2,
"code_window": [
" \"master\": {\n",
" \"uncompressed\": {\n",
" \"runtime-es2015\": 1485,\n",
" \"main-es2015\": 136302,\n",
" \"polyfills-es2015\": 37248\n",
" }\n",
" }\n",
" },\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" \"main-es2015\": 135533,\n"
],
"file_path": "goldens/size-tracking/integration-payloads.json",
"type": "replace",
"edit_start_line_idx": 32
} | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {CompileDiDependencyMetadata, CompileEntryComponentMetadata, CompileProviderMetadata, CompileTokenMetadata} from '../compile_metadata';
import {CompileReflector} from '../compile_reflector';
import {DepFlags, NodeFlags} from '../core';
import {createTokenForExternalReference, Identifiers} from '../identifiers';
import {LifecycleHooks} from '../lifecycle_reflector';
import * as o from '../output/output_ast';
import {convertValueToOutputAst} from '../output/value_util';
import {ProviderAst, ProviderAstType} from '../template_parser/template_ast';
import {OutputContext} from '../util';
export function providerDef(ctx: OutputContext, providerAst: ProviderAst): {
providerExpr: o.Expression,
flags: NodeFlags,
depsExpr: o.Expression,
tokenExpr: o.Expression
} {
let flags = NodeFlags.None;
if (!providerAst.eager) {
flags |= NodeFlags.LazyProvider;
}
if (providerAst.providerType === ProviderAstType.PrivateService) {
flags |= NodeFlags.PrivateProvider;
}
if (providerAst.isModule) {
flags |= NodeFlags.TypeModuleProvider;
}
providerAst.lifecycleHooks.forEach((lifecycleHook) => {
// for regular providers, we only support ngOnDestroy
if (lifecycleHook === LifecycleHooks.OnDestroy ||
providerAst.providerType === ProviderAstType.Directive ||
providerAst.providerType === ProviderAstType.Component) {
flags |= lifecycleHookToNodeFlag(lifecycleHook);
}
});
const {providerExpr, flags: providerFlags, depsExpr} = providerAst.multiProvider ?
multiProviderDef(ctx, flags, providerAst.providers) :
singleProviderDef(ctx, flags, providerAst.providerType, providerAst.providers[0]);
return {
providerExpr,
flags: providerFlags,
depsExpr,
tokenExpr: tokenExpr(ctx, providerAst.token),
};
}
function multiProviderDef(
ctx: OutputContext, flags: NodeFlags, providers: CompileProviderMetadata[]):
{providerExpr: o.Expression, flags: NodeFlags, depsExpr: o.Expression} {
const allDepDefs: o.Expression[] = [];
const allParams: o.FnParam[] = [];
const exprs = providers.map((provider, providerIndex) => {
let expr: o.Expression;
if (provider.useClass) {
const depExprs = convertDeps(providerIndex, provider.deps || provider.useClass.diDeps);
expr = ctx.importExpr(provider.useClass.reference).instantiate(depExprs);
} else if (provider.useFactory) {
const depExprs = convertDeps(providerIndex, provider.deps || provider.useFactory.diDeps);
expr = ctx.importExpr(provider.useFactory.reference).callFn(depExprs);
} else if (provider.useExisting) {
const depExprs = convertDeps(providerIndex, [{token: provider.useExisting}]);
expr = depExprs[0];
} else {
expr = convertValueToOutputAst(ctx, provider.useValue);
}
return expr;
});
const providerExpr =
o.fn(allParams, [new o.ReturnStatement(o.literalArr(exprs))], o.INFERRED_TYPE);
return {
providerExpr,
flags: flags | NodeFlags.TypeFactoryProvider,
depsExpr: o.literalArr(allDepDefs)
};
function convertDeps(providerIndex: number, deps: CompileDiDependencyMetadata[]) {
return deps.map((dep, depIndex) => {
const paramName = `p${providerIndex}_${depIndex}`;
allParams.push(new o.FnParam(paramName, o.DYNAMIC_TYPE));
allDepDefs.push(depDef(ctx, dep));
return o.variable(paramName);
});
}
}
function singleProviderDef(
ctx: OutputContext, flags: NodeFlags, providerType: ProviderAstType,
providerMeta: CompileProviderMetadata):
{providerExpr: o.Expression, flags: NodeFlags, depsExpr: o.Expression} {
let providerExpr: o.Expression;
let deps: CompileDiDependencyMetadata[];
if (providerType === ProviderAstType.Directive || providerType === ProviderAstType.Component) {
providerExpr = ctx.importExpr(providerMeta.useClass!.reference);
flags |= NodeFlags.TypeDirective;
deps = providerMeta.deps || providerMeta.useClass!.diDeps;
} else {
if (providerMeta.useClass) {
providerExpr = ctx.importExpr(providerMeta.useClass.reference);
flags |= NodeFlags.TypeClassProvider;
deps = providerMeta.deps || providerMeta.useClass.diDeps;
} else if (providerMeta.useFactory) {
providerExpr = ctx.importExpr(providerMeta.useFactory.reference);
flags |= NodeFlags.TypeFactoryProvider;
deps = providerMeta.deps || providerMeta.useFactory.diDeps;
} else if (providerMeta.useExisting) {
providerExpr = o.NULL_EXPR;
flags |= NodeFlags.TypeUseExistingProvider;
deps = [{token: providerMeta.useExisting}];
} else {
providerExpr = convertValueToOutputAst(ctx, providerMeta.useValue);
flags |= NodeFlags.TypeValueProvider;
deps = [];
}
}
const depsExpr = o.literalArr(deps.map(dep => depDef(ctx, dep)));
return {providerExpr, flags, depsExpr};
}
function tokenExpr(ctx: OutputContext, tokenMeta: CompileTokenMetadata): o.Expression {
return tokenMeta.identifier ? ctx.importExpr(tokenMeta.identifier.reference) :
o.literal(tokenMeta.value);
}
export function depDef(ctx: OutputContext, dep: CompileDiDependencyMetadata): o.Expression {
// Note: the following fields have already been normalized out by provider_analyzer:
// - isAttribute, isHost
const expr = dep.isValue ? convertValueToOutputAst(ctx, dep.value) : tokenExpr(ctx, dep.token!);
let flags = DepFlags.None;
if (dep.isSkipSelf) {
flags |= DepFlags.SkipSelf;
}
if (dep.isOptional) {
flags |= DepFlags.Optional;
}
if (dep.isSelf) {
flags |= DepFlags.Self;
}
if (dep.isValue) {
flags |= DepFlags.Value;
}
return flags === DepFlags.None ? expr : o.literalArr([o.literal(flags), expr]);
}
export function lifecycleHookToNodeFlag(lifecycleHook: LifecycleHooks): NodeFlags {
let nodeFlag = NodeFlags.None;
switch (lifecycleHook) {
case LifecycleHooks.AfterContentChecked:
nodeFlag = NodeFlags.AfterContentChecked;
break;
case LifecycleHooks.AfterContentInit:
nodeFlag = NodeFlags.AfterContentInit;
break;
case LifecycleHooks.AfterViewChecked:
nodeFlag = NodeFlags.AfterViewChecked;
break;
case LifecycleHooks.AfterViewInit:
nodeFlag = NodeFlags.AfterViewInit;
break;
case LifecycleHooks.DoCheck:
nodeFlag = NodeFlags.DoCheck;
break;
case LifecycleHooks.OnChanges:
nodeFlag = NodeFlags.OnChanges;
break;
case LifecycleHooks.OnDestroy:
nodeFlag = NodeFlags.OnDestroy;
break;
case LifecycleHooks.OnInit:
nodeFlag = NodeFlags.OnInit;
break;
}
return nodeFlag;
}
export function componentFactoryResolverProviderDef(
reflector: CompileReflector, ctx: OutputContext, flags: NodeFlags,
entryComponents: CompileEntryComponentMetadata[]): {
providerExpr: o.Expression,
flags: NodeFlags,
depsExpr: o.Expression,
tokenExpr: o.Expression
} {
const entryComponentFactories =
entryComponents.map((entryComponent) => ctx.importExpr(entryComponent.componentFactory));
const token = createTokenForExternalReference(reflector, Identifiers.ComponentFactoryResolver);
const classMeta = {
diDeps: [
{isValue: true, value: o.literalArr(entryComponentFactories)},
{token: token, isSkipSelf: true, isOptional: true},
{token: createTokenForExternalReference(reflector, Identifiers.NgModuleRef)},
],
lifecycleHooks: [],
reference: reflector.resolveExternalReference(Identifiers.CodegenComponentFactoryResolver)
};
const {providerExpr, flags: providerFlags, depsExpr} =
singleProviderDef(ctx, flags, ProviderAstType.PrivateService, {
token,
multi: false,
useClass: classMeta,
});
return {providerExpr, flags: providerFlags, depsExpr, tokenExpr: tokenExpr(ctx, token)};
}
| packages/compiler/src/view_compiler/provider_compiler.ts | 0 | https://github.com/angular/angular/commit/2038568f3e631cb15e9149945692e98ad2c8729d | [
0.0001775318814907223,
0.00017239707813132554,
0.00016221756231971085,
0.00017343081708531827,
0.00000394803873859928
] |
{
"id": 2,
"code_window": [
" \"master\": {\n",
" \"uncompressed\": {\n",
" \"runtime-es2015\": 1485,\n",
" \"main-es2015\": 136302,\n",
" \"polyfills-es2015\": 37248\n",
" }\n",
" }\n",
" },\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" \"main-es2015\": 135533,\n"
],
"file_path": "goldens/size-tracking/integration-payloads.json",
"type": "replace",
"edit_start_line_idx": 32
} | :host {
background:red;
padding:1em;
display:block;
font-size:20px;
color:white;
}
.inner-container {
width:432px;
font-weight:bold;
}
| modules/playground/src/relative_assets/app/style.css | 0 | https://github.com/angular/angular/commit/2038568f3e631cb15e9149945692e98ad2c8729d | [
0.00017570468480698764,
0.00017546751769259572,
0.00017523036513011903,
0.00017546751769259572,
2.3715983843430877e-7
] |
{
"id": 2,
"code_window": [
" \"master\": {\n",
" \"uncompressed\": {\n",
" \"runtime-es2015\": 1485,\n",
" \"main-es2015\": 136302,\n",
" \"polyfills-es2015\": 37248\n",
" }\n",
" }\n",
" },\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" \"main-es2015\": 135533,\n"
],
"file_path": "goldens/size-tracking/integration-payloads.json",
"type": "replace",
"edit_start_line_idx": 32
} | aio/content/examples/interpolation/src/app/app.component.css | 0 | https://github.com/angular/angular/commit/2038568f3e631cb15e9149945692e98ad2c8729d | [
0.0001766053173923865,
0.0001766053173923865,
0.0001766053173923865,
0.0001766053173923865,
0
] |
|
{
"id": 3,
"code_window": [
" \"master\": {\n",
" \"uncompressed\": {\n",
" \"runtime-es2015\": 2289,\n",
" \"main-es2015\": 246085,\n",
" \"polyfills-es2015\": 36938,\n",
" \"5-es2015\": 751\n",
" }\n",
" }\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" \"main-es2015\": 245488,\n"
],
"file_path": "goldens/size-tracking/integration-payloads.json",
"type": "replace",
"edit_start_line_idx": 41
} | {
"aio": {
"master": {
"uncompressed": {
"runtime-es2015": 2987,
"main-es2015": 453213,
"polyfills-es2015": 52685
}
}
},
"aio-local": {
"master": {
"uncompressed": {
"runtime-es2015": 2987,
"main-es2015": 451406,
"polyfills-es2015": 52630
}
}
},
"aio-local-viewengine": {
"master": {
"uncompressed": {
"runtime-es2015": 3097,
"main-es2015": 429710,
"polyfills-es2015": 52195
}
}
}
}
| goldens/size-tracking/aio-payloads.json | 1 | https://github.com/angular/angular/commit/2038568f3e631cb15e9149945692e98ad2c8729d | [
0.00024397516972385347,
0.0002374447649344802,
0.00022526121756527573,
0.00024309790751431137,
0.000008622509994893335
] |
{
"id": 3,
"code_window": [
" \"master\": {\n",
" \"uncompressed\": {\n",
" \"runtime-es2015\": 2289,\n",
" \"main-es2015\": 246085,\n",
" \"polyfills-es2015\": 36938,\n",
" \"5-es2015\": 751\n",
" }\n",
" }\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" \"main-es2015\": 245488,\n"
],
"file_path": "goldens/size-tracking/integration-payloads.json",
"type": "replace",
"edit_start_line_idx": 41
} | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import * as ts from 'typescript';
import {absoluteFrom, getFileSystem, getSourceFileOrError} from '../../../src/ngtsc/file_system';
import {runInEachFileSystem, TestFile} from '../../../src/ngtsc/file_system/testing';
import {MockLogger} from '../../../src/ngtsc/logging/testing';
import {ClassMemberKind, isNamedVariableDeclaration} from '../../../src/ngtsc/reflection';
import {getDeclaration} from '../../../src/ngtsc/testing';
import {loadFakeCore, loadTestFiles, loadTsLib} from '../../../test/helpers';
import {Esm2015ReflectionHost} from '../../src/host/esm2015_host';
import {convertToDirectTsLibImport, convertToInlineTsLib, makeTestBundleProgram} from '../helpers/utils';
import {expectTypeValueReferencesForParameters} from './util';
runInEachFileSystem(() => {
describe('Fesm2015ReflectionHost [import helper style]', () => {
let _: typeof absoluteFrom;
let FILES: {[label: string]: TestFile[]};
beforeEach(() => {
_ = absoluteFrom;
const NAMESPACED_IMPORT_FILES = [
{
name: _('/some_directive.js'),
contents: `
import * as tslib_1 from 'tslib';
import { Directive, Inject, InjectionToken, Input } from '@angular/core';
const INJECTED_TOKEN = new InjectionToken('injected');
class ViewContainerRef {
}
class TemplateRef {
}
let SomeDirective = class SomeDirective {
constructor(_viewContainer, _template, injected) {
this.instanceProperty = 'instance';
this.input1 = '';
this.input2 = 0;
}
instanceMethod() { }
static staticMethod() { }
};
SomeDirective.staticProperty = 'static';
tslib_1.__decorate([
Input(),
tslib_1.__metadata("design:type", String)
], SomeDirective.prototype, "input1", void 0);
tslib_1.__decorate([
Input(),
tslib_1.__metadata("design:type", Number)
], SomeDirective.prototype, "input2", void 0);
SomeDirective = tslib_1.__decorate([
Directive({ selector: '[someDirective]' }),
tslib_1.__param(2, Inject(INJECTED_TOKEN)),
tslib_1.__metadata("design:paramtypes", [ViewContainerRef,
TemplateRef, String])
], SomeDirective);
export { SomeDirective };
`,
},
{
name: _('/some_directive_ctor_parameters.js'),
contents: `
import * as tslib_1 from 'tslib';
import { Directive, Inject, InjectionToken, Input } from '@angular/core';
const INJECTED_TOKEN = new InjectionToken('injected');
class ViewContainerRef {
}
class TemplateRef {
}
let SomeDirective = class SomeDirective {
constructor(_viewContainer, _template, injected) {
this.input1 = '';
}
};
SomeDirective.ctorParameters = () => [
{ type: ViewContainerRef, },
{ type: TemplateRef, },
{ type: undefined, decorators: [{ type: Inject, args: [INJECTED_TOKEN,] },] },
];
tslib_1.__decorate([
Input(),
], SomeDirective.prototype, "input1", void 0);
SomeDirective = tslib_1.__decorate([
Directive({ selector: '[someDirective]' }),
tslib_1.__param(2, Inject(INJECTED_TOKEN)),
], SomeDirective);
export { SomeDirective };
`,
},
{
name: _('/some_directive_ctor_parameters_iife.js'),
contents: `
import * as tslib_1 from 'tslib';
import { Directive, Inject, InjectionToken, Input } from '@angular/core';
const INJECTED_TOKEN = new InjectionToken('injected');
let ViewContainerRef = /** class */ (() => { class ViewContainerRef {} return ViewContainerRef; })();
let TemplateRef = /** class */ (() => { class TemplateRef {} return TemplateRef; })();
let SomeDirective = /** @class */ (() => {
let SomeDirective = class SomeDirective {
constructor(_viewContainer, _template, injected) {
this.input1 = '';
}
};
SomeDirective.ctorParameters = () => [
{ type: ViewContainerRef, },
{ type: TemplateRef, },
{ type: undefined, decorators: [{ type: Inject, args: [INJECTED_TOKEN,] },] },
];
tslib_1.__decorate([
Input(),
], SomeDirective.prototype, "input1", void 0);
SomeDirective = tslib_1.__decorate([
Directive({ selector: '[someDirective]' }),
tslib_1.__param(2, Inject(INJECTED_TOKEN)),
], SomeDirective);
})();
export { SomeDirective };
`,
},
{
name: _('/node_modules/@angular/core/some_directive.js'),
contents: `
import * as tslib_1 from 'tslib';
import { Directive, Input } from './directives';
let SomeDirective = class SomeDirective {
constructor() { this.input1 = ''; }
};
tslib_1.__decorate([
Input(),
tslib_1.__metadata("design:type", String)
], SomeDirective.prototype, "input1", void 0);
SomeDirective = tslib_1.__decorate([
Directive({ selector: '[someDirective]' }),
], SomeDirective);
export { SomeDirective };
`,
},
{
name: _('/ngmodule.js'),
contents: `
import * as tslib_1 from 'tslib';
import { NgModule } from './directives';
var HttpClientXsrfModule_1;
let HttpClientXsrfModule = HttpClientXsrfModule_1 = class HttpClientXsrfModule {
static withOptions(options = {}) {
return {
ngModule: HttpClientXsrfModule_1,
providers: [],
};
}
};
HttpClientXsrfModule.staticProperty = 'static';
HttpClientXsrfModule = HttpClientXsrfModule_1 = tslib_1.__decorate([
NgModule({
providers: [],
})
], HttpClientXsrfModule);
let missingValue;
let nonDecoratedVar;
nonDecoratedVar = 43;
export { HttpClientXsrfModule };
`
},
];
const DIRECT_IMPORT_FILES = convertToDirectTsLibImport(NAMESPACED_IMPORT_FILES);
const INLINE_FILES = convertToInlineTsLib(NAMESPACED_IMPORT_FILES);
const INLINE_SUFFIXED_FILES = convertToInlineTsLib(NAMESPACED_IMPORT_FILES, '$2');
FILES = {
'namespaced': NAMESPACED_IMPORT_FILES,
'direct import': DIRECT_IMPORT_FILES,
'inline': INLINE_FILES,
'inline suffixed': INLINE_SUFFIXED_FILES,
};
});
['namespaced', 'direct import', 'inline', 'inline suffixed'].forEach(label => {
describe(`[${label}]`, () => {
beforeEach(() => {
const fs = getFileSystem();
loadTsLib(fs);
loadFakeCore(fs);
loadTestFiles(FILES[label]);
});
describe('getDecoratorsOfDeclaration()', () => {
it('should find the decorators on a class', () => {
const bundle = makeTestBundleProgram(_('/some_directive.js'));
const host = new Esm2015ReflectionHost(new MockLogger(), false, bundle);
const classNode = getDeclaration(
bundle.program, _('/some_directive.js'), 'SomeDirective',
isNamedVariableDeclaration);
const decorators = host.getDecoratorsOfDeclaration(classNode)!;
expect(decorators).toBeDefined();
expect(decorators.length).toEqual(1);
const decorator = decorators[0];
expect(decorator.name).toEqual('Directive');
expect(decorator.identifier!.getText()).toEqual('Directive');
expect(decorator.import).toEqual({name: 'Directive', from: '@angular/core'});
expect(decorator.args!.map(arg => arg.getText())).toEqual([
'{ selector: \'[someDirective]\' }',
]);
});
it('should find the decorators on a class when mixing `ctorParameters` and `__decorate`',
() => {
const bundle = makeTestBundleProgram(_('/some_directive_ctor_parameters.js'));
const host = new Esm2015ReflectionHost(new MockLogger(), false, bundle);
const classNode = getDeclaration(
bundle.program, _('/some_directive_ctor_parameters.js'), 'SomeDirective',
isNamedVariableDeclaration);
const decorators = host.getDecoratorsOfDeclaration(classNode)!;
expect(decorators).toBeDefined();
expect(decorators.length).toEqual(1);
const decorator = decorators[0];
expect(decorator.name).toEqual('Directive');
expect(decorator.identifier!.getText()).toEqual('Directive');
expect(decorator.import).toEqual({name: 'Directive', from: '@angular/core'});
expect(decorator.args!.map(arg => arg.getText())).toEqual([
'{ selector: \'[someDirective]\' }',
]);
});
it('should find the decorators on an IIFE wrapped class when mixing `ctorParameters` and `__decorate`',
() => {
const bundle = makeTestBundleProgram(_('/some_directive_ctor_parameters_iife.js'));
const host = new Esm2015ReflectionHost(new MockLogger(), false, bundle);
const classNode = getDeclaration(
bundle.program, _('/some_directive_ctor_parameters_iife.js'), 'SomeDirective',
isNamedVariableDeclaration);
const decorators = host.getDecoratorsOfDeclaration(classNode)!;
expect(decorators).toBeDefined();
expect(decorators.length).toEqual(1);
const decorator = decorators[0];
expect(decorator.name).toEqual('Directive');
expect(decorator.identifier!.getText()).toEqual('Directive');
expect(decorator.import).toEqual({name: 'Directive', from: '@angular/core'});
expect(decorator.args!.map(arg => arg.getText())).toEqual([
'{ selector: \'[someDirective]\' }',
]);
});
it('should support decorators being used inside @angular/core', () => {
const bundle =
makeTestBundleProgram(_('/node_modules/@angular/core/some_directive.js'));
const host = new Esm2015ReflectionHost(new MockLogger(), true, bundle);
const classNode = getDeclaration(
bundle.program, _('/node_modules/@angular/core/some_directive.js'), 'SomeDirective',
isNamedVariableDeclaration);
const decorators = host.getDecoratorsOfDeclaration(classNode)!;
expect(decorators).toBeDefined();
expect(decorators.length).toEqual(1);
const decorator = decorators[0];
expect(decorator.name).toEqual('Directive');
expect(decorator.identifier!.getText()).toEqual('Directive');
expect(decorator.import).toEqual({name: 'Directive', from: './directives'});
expect(decorator.args!.map(arg => arg.getText())).toEqual([
'{ selector: \'[someDirective]\' }',
]);
});
});
describe('getMembersOfClass()', () => {
it('should find decorated members on a class', () => {
const bundle = makeTestBundleProgram(_('/some_directive.js'));
const host = new Esm2015ReflectionHost(new MockLogger(), false, bundle);
const classNode = getDeclaration(
bundle.program, _('/some_directive.js'), 'SomeDirective',
isNamedVariableDeclaration);
const members = host.getMembersOfClass(classNode);
const input1 = members.find(member => member.name === 'input1')!;
expect(input1.kind).toEqual(ClassMemberKind.Property);
expect(input1.isStatic).toEqual(false);
expect(input1.decorators!.map(d => d.name)).toEqual(['Input']);
const input2 = members.find(member => member.name === 'input2')!;
expect(input2.kind).toEqual(ClassMemberKind.Property);
expect(input2.isStatic).toEqual(false);
expect(input1.decorators!.map(d => d.name)).toEqual(['Input']);
});
it('should find decorated members on a class when mixing `ctorParameters` and `__decorate`',
() => {
const bundle = makeTestBundleProgram(_('/some_directive_ctor_parameters.js'));
const host = new Esm2015ReflectionHost(new MockLogger(), false, bundle);
const classNode = getDeclaration(
bundle.program, _('/some_directive_ctor_parameters.js'), 'SomeDirective',
isNamedVariableDeclaration);
const members = host.getMembersOfClass(classNode);
const input1 = members.find(member => member.name === 'input1')!;
expect(input1.kind).toEqual(ClassMemberKind.Property);
expect(input1.isStatic).toEqual(false);
expect(input1.decorators!.map(d => d.name)).toEqual(['Input']);
});
it('should find decorated members on an IIFE wrapped class when mixing `ctorParameters` and `__decorate`',
() => {
const bundle = makeTestBundleProgram(_('/some_directive_ctor_parameters_iife.js'));
const host = new Esm2015ReflectionHost(new MockLogger(), false, bundle);
const classNode = getDeclaration(
bundle.program, _('/some_directive_ctor_parameters_iife.js'), 'SomeDirective',
isNamedVariableDeclaration);
const members = host.getMembersOfClass(classNode);
const input1 = members.find(member => member.name === 'input1')!;
expect(input1.kind).toEqual(ClassMemberKind.Property);
expect(input1.isStatic).toEqual(false);
expect(input1.decorators!.map(d => d.name)).toEqual(['Input']);
});
it('should find non decorated properties on a class', () => {
const bundle = makeTestBundleProgram(_('/some_directive.js'));
const host = new Esm2015ReflectionHost(new MockLogger(), false, bundle);
const classNode = getDeclaration(
bundle.program, _('/some_directive.js'), 'SomeDirective',
isNamedVariableDeclaration);
const members = host.getMembersOfClass(classNode);
const instanceProperty = members.find(member => member.name === 'instanceProperty')!;
expect(instanceProperty.kind).toEqual(ClassMemberKind.Property);
expect(instanceProperty.isStatic).toEqual(false);
expect(ts.isBinaryExpression(instanceProperty.implementation!)).toEqual(true);
expect(instanceProperty.value!.getText()).toEqual(`'instance'`);
});
it('should find static methods on a class', () => {
const bundle = makeTestBundleProgram(_('/some_directive.js'));
const host = new Esm2015ReflectionHost(new MockLogger(), false, bundle);
const classNode = getDeclaration(
bundle.program, _('/some_directive.js'), 'SomeDirective',
isNamedVariableDeclaration);
const members = host.getMembersOfClass(classNode);
const staticMethod = members.find(member => member.name === 'staticMethod')!;
expect(staticMethod.kind).toEqual(ClassMemberKind.Method);
expect(staticMethod.isStatic).toEqual(true);
expect(ts.isMethodDeclaration(staticMethod.implementation!)).toEqual(true);
});
it('should find static properties on a class', () => {
const bundle = makeTestBundleProgram(_('/some_directive.js'));
const host = new Esm2015ReflectionHost(new MockLogger(), false, bundle);
const classNode = getDeclaration(
bundle.program, _('/some_directive.js'), 'SomeDirective',
isNamedVariableDeclaration);
const members = host.getMembersOfClass(classNode);
const staticProperty = members.find(member => member.name === 'staticProperty')!;
expect(staticProperty.kind).toEqual(ClassMemberKind.Property);
expect(staticProperty.isStatic).toEqual(true);
expect(ts.isPropertyAccessExpression(staticProperty.implementation!)).toEqual(true);
expect(staticProperty.value!.getText()).toEqual(`'static'`);
});
it('should find static properties on a class that has an intermediate variable assignment',
() => {
const bundle = makeTestBundleProgram(_('/ngmodule.js'));
const host = new Esm2015ReflectionHost(new MockLogger(), false, bundle);
const classNode = getDeclaration(
bundle.program, _('/ngmodule.js'), 'HttpClientXsrfModule',
isNamedVariableDeclaration);
const members = host.getMembersOfClass(classNode);
const staticProperty = members.find(member => member.name === 'staticProperty')!;
expect(staticProperty.kind).toEqual(ClassMemberKind.Property);
expect(staticProperty.isStatic).toEqual(true);
expect(ts.isPropertyAccessExpression(staticProperty.implementation!)).toEqual(true);
expect(staticProperty.value!.getText()).toEqual(`'static'`);
});
it('should support decorators being used inside @angular/core', () => {
const bundle =
makeTestBundleProgram(_('/node_modules/@angular/core/some_directive.js'));
const host = new Esm2015ReflectionHost(new MockLogger(), true, bundle);
const classNode = getDeclaration(
bundle.program, _('/node_modules/@angular/core/some_directive.js'), 'SomeDirective',
isNamedVariableDeclaration);
const members = host.getMembersOfClass(classNode);
const input1 = members.find(member => member.name === 'input1')!;
expect(input1.kind).toEqual(ClassMemberKind.Property);
expect(input1.isStatic).toEqual(false);
expect(input1.decorators!.map(d => d.name)).toEqual(['Input']);
});
});
describe('getConstructorParameters', () => {
it('should find the decorated constructor parameters', () => {
const bundle = makeTestBundleProgram(_('/some_directive.js'));
const host = new Esm2015ReflectionHost(new MockLogger(), false, bundle);
const classNode = getDeclaration(
bundle.program, _('/some_directive.js'), 'SomeDirective',
isNamedVariableDeclaration);
const parameters = host.getConstructorParameters(classNode);
expect(parameters).toBeDefined();
expect(parameters!.map(parameter => parameter.name)).toEqual([
'_viewContainer', '_template', 'injected'
]);
expectTypeValueReferencesForParameters(parameters!, [
'ViewContainerRef',
'TemplateRef',
'String',
]);
});
it('should find the decorated constructor parameters when mixing `ctorParameters` and `__decorate`',
() => {
const bundle = makeTestBundleProgram(_('/some_directive_ctor_parameters.js'));
const host = new Esm2015ReflectionHost(new MockLogger(), false, bundle);
const classNode = getDeclaration(
bundle.program, _('/some_directive_ctor_parameters.js'), 'SomeDirective',
isNamedVariableDeclaration);
const parameters = host.getConstructorParameters(classNode);
expect(parameters).toBeDefined();
expect(parameters!.map(parameter => parameter.name)).toEqual([
'_viewContainer', '_template', 'injected'
]);
expectTypeValueReferencesForParameters(parameters!, [
'ViewContainerRef',
'TemplateRef',
null,
]);
const decorators = parameters![2].decorators!;
expect(decorators.length).toEqual(1);
expect(decorators[0].name).toBe('Inject');
expect(decorators[0].import!.from).toBe('@angular/core');
expect(decorators[0].import!.name).toBe('Inject');
});
});
it('should find the decorated constructor parameters on an IIFE wrapped class when mixing `ctorParameters` and `__decorate`',
() => {
const bundle = makeTestBundleProgram(_('/some_directive_ctor_parameters_iife.js'));
const host = new Esm2015ReflectionHost(new MockLogger(), false, bundle);
const classNode = getDeclaration(
bundle.program, _('/some_directive_ctor_parameters_iife.js'), 'SomeDirective',
isNamedVariableDeclaration);
const parameters = host.getConstructorParameters(classNode);
expect(parameters).toBeDefined();
expect(parameters!.map(parameter => parameter.name)).toEqual([
'_viewContainer', '_template', 'injected'
]);
expectTypeValueReferencesForParameters(parameters!, [
'ViewContainerRef',
'TemplateRef',
null,
]);
const decorators = parameters![2].decorators!;
expect(decorators.length).toEqual(1);
expect(decorators[0].name).toBe('Inject');
expect(decorators[0].import!.from).toBe('@angular/core');
expect(decorators[0].import!.name).toBe('Inject');
});
describe('getDeclarationOfIdentifier', () => {
it('should return the declaration of a locally defined identifier', () => {
const bundle = makeTestBundleProgram(_('/some_directive.js'));
const host = new Esm2015ReflectionHost(new MockLogger(), false, bundle);
const classNode = getDeclaration(
bundle.program, _('/some_directive.js'), 'SomeDirective',
isNamedVariableDeclaration);
const ctrDecorators = host.getConstructorParameters(classNode)!;
const identifierOfViewContainerRef = (ctrDecorators[0].typeValueReference! as {
local: true,
expression: ts.Identifier,
defaultImportStatement: null,
}).expression;
const expectedDeclarationNode = getDeclaration(
bundle.program, _('/some_directive.js'), 'ViewContainerRef', ts.isClassDeclaration);
const actualDeclaration = host.getDeclarationOfIdentifier(identifierOfViewContainerRef);
expect(actualDeclaration).not.toBe(null);
expect(actualDeclaration!.node).toBe(expectedDeclarationNode);
expect(actualDeclaration!.viaModule).toBe(null);
});
it('should return the declaration of an externally defined identifier', () => {
const bundle = makeTestBundleProgram(_('/some_directive.js'));
const host = new Esm2015ReflectionHost(new MockLogger(), false, bundle);
const classNode = getDeclaration(
bundle.program, _('/some_directive.js'), 'SomeDirective',
isNamedVariableDeclaration);
const classDecorators = host.getDecoratorsOfDeclaration(classNode)!;
const decoratorNode = classDecorators[0].node!;
const identifierOfDirective =
ts.isCallExpression(decoratorNode) && ts.isIdentifier(decoratorNode.expression) ?
decoratorNode.expression :
null;
const expectedDeclarationNode = getDeclaration(
bundle.program, _('/node_modules/@angular/core/index.d.ts'), 'Directive',
isNamedVariableDeclaration);
const actualDeclaration = host.getDeclarationOfIdentifier(identifierOfDirective!);
expect(actualDeclaration).not.toBe(null);
expect(actualDeclaration!.node).toBe(expectedDeclarationNode);
expect(actualDeclaration!.viaModule).toBe('@angular/core');
});
});
describe('getVariableValue', () => {
it('should find the "actual" declaration of an aliased variable identifier', () => {
const bundle = makeTestBundleProgram(_('/ngmodule.js'));
const host = new Esm2015ReflectionHost(new MockLogger(), false, bundle);
const ngModuleRef = findVariableDeclaration(
getSourceFileOrError(bundle.program, _('/ngmodule.js')), 'HttpClientXsrfModule_1');
const value = host.getVariableValue(ngModuleRef!);
expect(value).not.toBe(null);
if (!value || !ts.isClassExpression(value)) {
throw new Error(
`Expected value to be a class expression: ${value && value.getText()}.`);
}
expect(value.name!.text).toBe('HttpClientXsrfModule');
});
it('should return null if the variable has no assignment', () => {
const bundle = makeTestBundleProgram(_('/ngmodule.js'));
const host = new Esm2015ReflectionHost(new MockLogger(), false, bundle);
const missingValue = findVariableDeclaration(
getSourceFileOrError(bundle.program, _('/ngmodule.js')), 'missingValue');
const value = host.getVariableValue(missingValue!);
expect(value).toBe(null);
});
it('should return null if the variable is not assigned from a call to __decorate', () => {
const bundle = makeTestBundleProgram(_('/ngmodule.js'));
const host = new Esm2015ReflectionHost(new MockLogger(), false, bundle);
const nonDecoratedVar = findVariableDeclaration(
getSourceFileOrError(bundle.program, _('/ngmodule.js')), 'nonDecoratedVar');
const value = host.getVariableValue(nonDecoratedVar!);
expect(value).toBe(null);
});
});
describe('getEndOfClass()', () => {
it('should return the last statement related to the class', () => {
const bundle = makeTestBundleProgram(_('/ngmodule.js'));
const host = new Esm2015ReflectionHost(new MockLogger(), false, bundle);
const classSymbol =
host.findClassSymbols(bundle.program.getSourceFile(_('/ngmodule.js'))!)[0];
const endOfClass = host.getEndOfClass(classSymbol);
expect(endOfClass.getText())
.toMatch(
/HttpClientXsrfModule = HttpClientXsrfModule_1 = .*__decorate.*\(\[\n\s*NgModule\(\{\n\s*providers: \[],\n\s*}\)\n\s*], HttpClientXsrfModule\);/);
});
});
});
});
function findVariableDeclaration(
node: ts.Node|undefined, variableName: string): ts.VariableDeclaration|undefined {
if (!node) {
return;
}
if (ts.isVariableDeclaration(node) && ts.isIdentifier(node.name) &&
node.name.text === variableName) {
return node;
}
return node.forEachChild(node => findVariableDeclaration(node, variableName));
}
});
});
| packages/compiler-cli/ngcc/test/host/esm2015_host_import_helper_spec.ts | 0 | https://github.com/angular/angular/commit/2038568f3e631cb15e9149945692e98ad2c8729d | [
0.00021788485173601657,
0.00017430515435989946,
0.00016631670587230474,
0.000174080123542808,
0.0000064964001467160415
] |
{
"id": 3,
"code_window": [
" \"master\": {\n",
" \"uncompressed\": {\n",
" \"runtime-es2015\": 2289,\n",
" \"main-es2015\": 246085,\n",
" \"polyfills-es2015\": 36938,\n",
" \"5-es2015\": 751\n",
" }\n",
" }\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" \"main-es2015\": 245488,\n"
],
"file_path": "goldens/size-tracking/integration-payloads.json",
"type": "replace",
"edit_start_line_idx": 41
} | import { Component } from '@angular/core';
@Component({
selector: 'app-page-not-found',
templateUrl: './page-not-found.component.html',
styleUrls: ['./page-not-found.component.css']
})
export class PageNotFoundComponent {
}
| aio/content/examples/router-tutorial/src/app/page-not-found/page-not-found.component.ts | 0 | https://github.com/angular/angular/commit/2038568f3e631cb15e9149945692e98ad2c8729d | [
0.00017550979100633413,
0.00017304127686657012,
0.0001705727627268061,
0.00017304127686657012,
0.000002468514139764011
] |
{
"id": 3,
"code_window": [
" \"master\": {\n",
" \"uncompressed\": {\n",
" \"runtime-es2015\": 2289,\n",
" \"main-es2015\": 246085,\n",
" \"polyfills-es2015\": 36938,\n",
" \"5-es2015\": 751\n",
" }\n",
" }\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" \"main-es2015\": 245488,\n"
],
"file_path": "goldens/size-tracking/integration-payloads.json",
"type": "replace",
"edit_start_line_idx": 41
} | // This file can be replaced during build by using the `fileReplacements` array.
// `ng build --prod` replaces `environment.ts` with `environment.prod.ts`.
// The list of file replacements can be found in `angular.json`.
export const environment = {
production: false
};
/*
* For easier debugging in development mode, you can import the following file
* to ignore zone related error stack frames such as `zone.run`, `zoneDelegate.invokeTask`.
*
* This import should be commented out in production mode because it will have a negative impact
* on performance if an error is thrown.
*/
// import 'zone.js/dist/zone-error'; // Included with Angular CLI.
| integration/cli-hello-world-ivy-i18n/src/environments/environment.ts | 0 | https://github.com/angular/angular/commit/2038568f3e631cb15e9149945692e98ad2c8729d | [
0.00017243092588614672,
0.0001705715840216726,
0.00016871225670911372,
0.0001705715840216726,
0.0000018593345885165036
] |
{
"id": 0,
"code_window": [
"\n",
" const [targetNotification, setTargetNotification] = useState<Notification>()\n",
"\n",
" if (!notifications) return <></>\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
" if (!notifications || !Array.isArray(notifications)) return <></>\n"
],
"file_path": "studio/components/layouts/ProjectLayout/LayoutHeader/NotificationsPopover/index.tsx",
"type": "replace",
"edit_start_line_idx": 35
} | import * as Tooltip from '@radix-ui/react-tooltip'
import {
ActionType,
Notification,
NotificationStatus,
} from '@supabase/shared-types/out/notifications'
import { useQueryClient } from '@tanstack/react-query'
import dayjs from 'dayjs'
import { useRouter } from 'next/router'
import { Fragment, useState } from 'react'
import ConfirmModal from 'components/ui/Dialogs/ConfirmDialog'
import { useNotificationsQuery } from 'data/notifications/notifications-query'
import { getProjectDetail } from 'data/projects/project-detail-query'
import { invalidateProjectsQuery, setProjectPostgrestStatus } from 'data/projects/projects-query'
import { useStore } from 'hooks'
import { delete_, patch, post } from 'lib/common/fetch'
import { API_URL } from 'lib/constants'
import { Project } from 'types'
import { Alert, Button, IconArrowRight, IconBell, Popover } from 'ui'
import NotificationRow from './NotificationRow'
const NotificationsPopover = () => {
const queryClient = useQueryClient()
const router = useRouter()
const { meta, ui } = useStore()
const { data: notifications, refetch } = useNotificationsQuery()
const [projectToRestart, setProjectToRestart] = useState<Project>()
const [projectToApplyMigration, setProjectToApplyMigration] = useState<Project>()
const [projectToRollbackMigration, setProjectToRollbackMigration] = useState<Project>()
const [projectToFinalizeMigration, setProjectToFinalizeMigration] = useState<Project>()
const [targetNotification, setTargetNotification] = useState<Notification>()
if (!notifications) return <></>
const hasNewNotifications = notifications?.some(
(notification) => notification.notification_status === NotificationStatus.New
)
const onOpenChange = async (open: boolean) => {
// TODO(alaister): move this to a mutation
if (!open) {
// Mark notifications as seen
const notificationIds = notifications
.filter((notification) => notification.notification_status === NotificationStatus.New)
.map((notification) => notification.id)
if (notificationIds.length > 0) {
const { error } = await patch(`${API_URL}/notifications`, { ids: notificationIds })
if (error) console.error('Failed to update notifications', error)
refetch()
}
}
}
const onConfirmProjectRestart = async () => {
if (!projectToRestart || !targetNotification) return
const { id } = targetNotification
const { ref, region } = projectToRestart
const serviceNamesByActionName: Record<string, string> = {
[ActionType.PgBouncerRestart]: 'pgbouncer',
[ActionType.SchedulePostgresRestart]: 'postgresql',
[ActionType.MigratePostgresSchema]: 'postgresql',
}
const services: string[] = targetNotification.meta.actions_available
.map((action) => action.action_type)
.filter((actionName) => Object.keys(serviceNamesByActionName).indexOf(actionName) !== -1)
.map((actionName) => serviceNamesByActionName[actionName])
const { error } = await post(`${API_URL}/projects/${ref}/restart-services`, {
restartRequest: {
region,
source_notification_id: id,
services: services,
},
})
if (error) {
ui.setNotification({
category: 'error',
message: `Failed to restart project: ${error.message}`,
error,
})
} else {
setProjectPostgrestStatus(queryClient, ref, 'OFFLINE')
ui.setNotification({ category: 'success', message: `Restarting services` })
router.push(`/project/${ref}`)
}
setProjectToRestart(undefined)
setTargetNotification(undefined)
}
// [Joshen/Qiao] These are all very specific to the upcoming security patch
// https://github.com/supabase/supabase/discussions/9314
// We probably need to revisit this again when we're planning to push out the next wave of
// notifications. Ideally, we should allow these to be more flexible and configurable
// Perhaps the URLs could come from the notification themselves if the actions
// require an external API call, then we just need one method instead of individual ones like this
const onConfirmProjectApplyMigration = async () => {
if (!projectToApplyMigration) return
const res = await post(`${API_URL}/database/${projectToApplyMigration.ref}/owner-reassign`, {})
if (!res.error) {
const project = await getProjectDetail({ ref: projectToApplyMigration.ref })
if (project) {
meta.setProjectDetails(project)
}
ui.setNotification({
category: 'success',
message: `Successfully applied migration for project "${projectToApplyMigration.name}"`,
})
} else {
ui.setNotification({
error: res.error,
category: 'error',
message: `Failed to apply migration: ${res.error.message}`,
})
}
setProjectToApplyMigration(undefined)
}
const onConfirmProjectRollbackMigration = async () => {
if (!projectToRollbackMigration) return
const res = await delete_(
`${API_URL}/database/${projectToRollbackMigration.ref}/owner-reassign`,
{}
)
if (!res.error) {
const project = await getProjectDetail({ ref: projectToRollbackMigration.ref })
if (project) {
meta.setProjectDetails(project)
}
ui.setNotification({
category: 'success',
message: `Successfully rolled back migration for project "${projectToRollbackMigration.name}"`,
})
} else {
ui.setNotification({
error: res.error,
category: 'error',
message: `Failed to roll back migration: ${res.error.message}`,
})
}
setProjectToRollbackMigration(undefined)
}
const onConfirmProjectFinalizeMigration = async () => {
if (!projectToFinalizeMigration) return
const res = await patch(
`${API_URL}/database/${projectToFinalizeMigration.ref}/owner-reassign`,
{}
)
if (!res.error) {
const project = await getProjectDetail({ ref: projectToFinalizeMigration.ref })
if (project) {
meta.setProjectDetails(project)
}
ui.setNotification({
category: 'success',
message: `Successfully finalized migration for project "${projectToFinalizeMigration.name}"`,
})
} else {
ui.setNotification({
error: res.error,
category: 'error',
message: `Failed to finalize migration: ${res.error.message}`,
})
}
setProjectToFinalizeMigration(undefined)
}
return (
<>
<Popover
size="content"
align="end"
side="bottom"
sideOffset={8}
onOpenChange={onOpenChange}
overlay={
<div className="w-[400px] lg:w-[700px]">
<div className="flex items-center justify-between border-b border-gray-500 bg-gray-400 px-4 py-2">
<p className="text-sm">Notifications</p>
{/* Area for improvement: Paginate notifications and show in a side panel */}
{/* <p className="text-scale-1000 hover:text-scale-1200 cursor-pointer text-sm transition">
See all{' '}
{notifications.length > MAX_NOTIFICATIONS_TO_SHOW && `(${notifications.length})`}
</p> */}
</div>
<div className="max-h-[380px] overflow-y-auto py-2">
{notifications.length === 0 ? (
<div className="py-2 px-4">
<p className="text-sm text-scale-1000">No notifications available</p>
</div>
) : (
<>
{notifications.map((notification, i: number) => (
<Fragment key={notification.id}>
<NotificationRow
notification={notification}
onSelectRestartProject={(project, notification) => {
setProjectToRestart(project)
setTargetNotification(notification)
}}
onSelectApplyMigration={(project, notification) => {
setProjectToApplyMigration(project)
setTargetNotification(notification)
}}
onSelectRollbackMigration={(project, notification) => {
setProjectToRollbackMigration(project)
setTargetNotification(notification)
}}
onSelectFinalizeMigration={(project, notification) => {
setProjectToFinalizeMigration(project)
setTargetNotification(notification)
}}
/>
{i !== notifications.length - 1 && <Popover.Separator />}
</Fragment>
))}
</>
)}
</div>
</div>
}
>
<Tooltip.Root delayDuration={0}>
<Tooltip.Trigger asChild>
<div className="relative flex">
<Button
asChild
id="notification-button"
type="default"
icon={<IconBell size={16} strokeWidth={1.5} className="text-scale-1200" />}
>
<span></span>
</Button>
{hasNewNotifications && (
<div className="absolute -top-1 -right-1 z-50 flex h-3 w-3 items-center justify-center">
<div className="h-full w-full animate-ping rounded-full bg-green-800 opacity-60"></div>
<div className="z-60 absolute top-0 right-0 h-full w-full rounded-full bg-green-900 opacity-80"></div>
</div>
)}
</div>
</Tooltip.Trigger>
<Tooltip.Portal>
<Tooltip.Content side="bottom">
<Tooltip.Arrow className="radix-tooltip-arrow" />
<div
className={[
'rounded bg-scale-100 py-1 px-2 leading-none shadow',
'border border-scale-200 flex items-center space-x-1',
].join(' ')}
>
<span className="text-xs text-scale-1200">Notifications</span>
</div>
</Tooltip.Content>
</Tooltip.Portal>
</Tooltip.Root>
</Popover>
<ConfirmModal
danger
visible={projectToRestart !== undefined}
title={`Restart project "${projectToRestart?.name}"`}
description={`Are you sure you want to restart the project? There will be a few minutes of downtime.`}
buttonLabel="Restart"
buttonLoadingLabel="Restarting"
onSelectCancel={() => setProjectToRestart(undefined)}
onSelectConfirm={onConfirmProjectRestart}
/>
<ConfirmModal
size="large"
visible={projectToApplyMigration !== undefined}
title={`Apply schema migration for "${projectToApplyMigration?.name}"`}
// @ts-ignore
description={
<div className="text-scale-1200 space-y-2">
<div className="space-y-1">
<p>The following schema migration will be applied to the project</p>
<ol className="list-disc pl-6">
<li>
<div className="flex items-center space-x-1">
<p>{(targetNotification?.data as any)?.additional?.name}</p>
<IconArrowRight size={12} strokeWidth={2} />
<p>{(targetNotification?.data as any)?.additional?.version_to}</p>
</div>
</li>
</ol>
</div>
<p>
This change can be rolled back anytime up till{' '}
{dayjs(
new Date(targetNotification?.meta.actions_available?.[0]?.deadline ?? 0)
).format('DD MMM YYYY, HH:mma ZZ')}
, after which the changes will be finalized and can no longer be undone.
</p>
</div>
}
buttonLabel="Confirm"
buttonLoadingLabel="Confirm"
onSelectCancel={() => setProjectToApplyMigration(undefined)}
onSelectConfirm={onConfirmProjectApplyMigration}
/>
<ConfirmModal
size="medium"
visible={projectToRollbackMigration !== undefined}
title={`Rollback schema migration for "${projectToRollbackMigration?.name}"`}
// @ts-ignore
description={
<div className="text-scale-1200 space-y-2">
<div className="space-y-1">
<p>The following schema migration will be rolled back for the project</p>
<ol className="list-disc pl-6">
<li>
<div className="flex items-center space-x-1">
<p>{(targetNotification?.data as any)?.additional?.name}</p>
<IconArrowRight size={12} strokeWidth={2} />
<p>{(targetNotification?.data as any)?.additional?.version_to}</p>
</div>
</li>
</ol>
</div>
<p>
This migration however will still be applied and finalized after{' '}
{dayjs(
new Date(targetNotification?.meta.actions_available?.[0]?.deadline ?? 0)
).format('DD MMM YYYY, HH:mma ZZ')}
, after which the changes can no longer be undone.
</p>
</div>
}
buttonLabel="Confirm"
buttonLoadingLabel="Confirm"
onSelectCancel={() => setProjectToRollbackMigration(undefined)}
onSelectConfirm={onConfirmProjectRollbackMigration}
/>
<ConfirmModal
danger
size="small"
visible={projectToFinalizeMigration !== undefined}
title={`Finalize schema migration for "${projectToFinalizeMigration?.name}"`}
// @ts-ignore
description={
<div className="text-scale-1200 space-y-4">
<Alert withIcon variant="warning" title="This action canot be undone" />
<div className="space-y-1">
<p>The following schema migration will be finalized for the project</p>
<ol className="list-disc pl-6">
<li>
<div className="flex items-center space-x-1">
<p>{(targetNotification?.data as any)?.additional?.name}</p>
<IconArrowRight size={12} strokeWidth={2} />
<p>{(targetNotification?.data as any)?.additional?.version_to}</p>
</div>
</li>
</ol>
</div>
</div>
}
buttonLabel="Confirm"
buttonLoadingLabel="Confirm"
onSelectCancel={() => setProjectToFinalizeMigration(undefined)}
onSelectConfirm={onConfirmProjectFinalizeMigration}
/>
</>
)
}
export default NotificationsPopover
| studio/components/layouts/ProjectLayout/LayoutHeader/NotificationsPopover/index.tsx | 1 | https://github.com/supabase/supabase/commit/2f78bf4c33a05fa9d4231be80fe1fff4bd6d9ada | [
0.9990733861923218,
0.4188322424888611,
0.0001668220793362707,
0.03264342620968819,
0.4753040671348572
] |
{
"id": 0,
"code_window": [
"\n",
" const [targetNotification, setTargetNotification] = useState<Notification>()\n",
"\n",
" if (!notifications) return <></>\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
" if (!notifications || !Array.isArray(notifications)) return <></>\n"
],
"file_path": "studio/components/layouts/ProjectLayout/LayoutHeader/NotificationsPopover/index.tsx",
"type": "replace",
"edit_start_line_idx": 35
} | import { useCallback, useState, FC, useEffect } from 'react'
import { debounce, includes, noop } from 'lodash'
import { SidePanel, Tabs } from 'ui'
import { PostgresTable } from '@supabase/postgres-meta'
import { useStore } from 'hooks'
import ActionBar from '../ActionBar'
import SpreadSheetTextInput from './SpreadSheetTextInput'
import SpreadSheetFileUpload from './SpreadSheetFileUpload'
import { SpreadsheetData } from './SpreadsheetImport.types'
import {
acceptedFileExtension,
parseSpreadsheet,
parseSpreadsheetText,
} from './SpreadsheetImport.utils'
import { UPLOAD_FILE_TYPES, EMPTY_SPREADSHEET_DATA } from './SpreadsheetImport.constants'
import { ImportContent } from '../TableEditor/TableEditor.types'
import SpreadsheetImportConfiguration from './SpreadSheetImportConfiguration'
import SpreadsheetImportPreview from './SpreadsheetImportPreview'
interface Props {
debounceDuration?: number
headers?: string[]
rows?: any[]
visible: boolean
selectedTable?: PostgresTable
saveContent: (prefillData: ImportContent) => void
closePanel: () => void
updateEditorDirty?: (value: boolean) => void
}
const SpreadsheetImport: FC<Props> = ({
visible = false,
debounceDuration = 250,
headers = [],
rows = [],
selectedTable,
saveContent,
closePanel,
updateEditorDirty = noop,
}) => {
const { ui } = useStore()
useEffect(() => {
if (visible && headers.length === 0) {
resetSpreadsheetImport()
}
}, [visible])
const [tab, setTab] = useState<'fileUpload' | 'pasteText'>('fileUpload')
const [input, setInput] = useState<string>('')
const [uploadedFile, setUploadedFile] = useState<File>()
const [parseProgress, setParseProgress] = useState<number>(0)
const [spreadsheetData, setSpreadsheetData] = useState<SpreadsheetData>({
headers: headers,
rows: rows,
rowCount: 0,
columnTypeMap: {},
})
const [errors, setErrors] = useState<any>([])
const [selectedHeaders, setSelectedHeaders] = useState<string[]>([])
const selectedTableColumns = (selectedTable?.columns ?? []).map((column) => column.name)
const incompatibleHeaders = selectedHeaders.filter(
(header) => !selectedTableColumns.includes(header)
)
const isCompatible = selectedTable !== undefined ? incompatibleHeaders.length === 0 : true
const onProgressUpdate = (progress: number) => {
setParseProgress(progress)
}
const onFileUpload = async (event: any) => {
setParseProgress(0)
event.persist()
const [file] = event.target.files || event.dataTransfer.files
if (!file || !includes(UPLOAD_FILE_TYPES, file?.type) || !acceptedFileExtension(file)) {
ui.setNotification({
category: 'info',
message: 'Sorry! We only accept CSV or TSV file types, please upload another file.',
})
} else {
updateEditorDirty(true)
setUploadedFile(file)
const { headers, rowCount, columnTypeMap, errors, previewRows } = await parseSpreadsheet(
file,
onProgressUpdate
)
if (errors.length > 0) {
ui.setNotification({
error: errors,
category: 'error',
message: `Some issues have been detected on ${errors.length} rows. More details below the content preview.`,
duration: 4000,
})
}
setErrors(errors)
setSelectedHeaders(headers)
setSpreadsheetData({ headers, rows: previewRows, rowCount, columnTypeMap })
}
event.target.value = ''
}
const resetSpreadsheetImport = () => {
setInput('')
setSpreadsheetData(EMPTY_SPREADSHEET_DATA)
setUploadedFile(undefined)
setErrors([])
updateEditorDirty(false)
}
const readSpreadsheetText = async (text: string) => {
if (text.length > 0) {
const { headers, rows, columnTypeMap, errors } = await parseSpreadsheetText(text)
if (errors.length > 0) {
ui.setNotification({
error: errors,
category: 'error',
message: `Some issues have been detected on ${errors.length} rows. More details below the content preview.`,
duration: 4000,
})
}
setErrors(errors)
setSelectedHeaders(headers)
setSpreadsheetData({ headers, rows, rowCount: rows.length, columnTypeMap })
} else {
setSpreadsheetData(EMPTY_SPREADSHEET_DATA)
}
}
const handler = useCallback(debounce(readSpreadsheetText, debounceDuration), [])
const onInputChange = (event: any) => {
setInput(event.target.value)
handler(event.target.value)
}
const onToggleHeader = (header: string) => {
const updatedSelectedHeaders = selectedHeaders.includes(header)
? selectedHeaders.filter((h) => h !== header)
: selectedHeaders.concat([header])
setSelectedHeaders(updatedSelectedHeaders)
}
const onConfirm = (resolve: () => void) => {
if (tab === 'fileUpload' && uploadedFile === undefined) {
ui.setNotification({
category: 'error',
message: 'Please upload a file to import your data with',
})
resolve()
} else if (selectedHeaders.length === 0) {
ui.setNotification({
category: 'error',
message: 'Please select at least one header from your CSV',
})
resolve()
} else if (!isCompatible) {
ui.setNotification({
category: 'error',
message: 'The data that you are trying to import is incompatible with your table structure',
})
resolve()
} else {
saveContent({ file: uploadedFile, ...spreadsheetData, selectedHeaders, resolve })
}
}
return (
<SidePanel
size="large"
visible={visible}
align="right"
header={
selectedTable !== undefined ? (
<>
Add data to{' '}
<code className="text-sm">
{selectedTable.schema}.{selectedTable.name}
</code>
</>
) : (
'Add content to new table'
)
}
onCancel={() => closePanel()}
customFooter={
<ActionBar
backButtonLabel="Cancel"
applyButtonLabel={selectedTable === undefined ? 'Save' : 'Import data'}
closePanel={closePanel}
applyFunction={onConfirm}
/>
}
>
<SidePanel.Content>
<div className="pt-6">
<Tabs block type="pills" onChange={setTab}>
<Tabs.Panel id="fileUpload" label="Upload CSV">
<SpreadSheetFileUpload
parseProgress={parseProgress}
uploadedFile={uploadedFile}
onFileUpload={onFileUpload}
removeUploadedFile={resetSpreadsheetImport}
/>
</Tabs.Panel>
<Tabs.Panel id="pasteText" label="Paste text">
<SpreadSheetTextInput input={input} onInputChange={onInputChange} />
</Tabs.Panel>
</Tabs>
</div>
</SidePanel.Content>
{spreadsheetData.headers.length > 0 && (
<>
<div className="pt-4">
<SidePanel.Separator />
</div>
<SpreadsheetImportConfiguration
spreadsheetData={spreadsheetData}
selectedHeaders={selectedHeaders}
onToggleHeader={onToggleHeader}
/>
<SidePanel.Separator />
<SpreadsheetImportPreview
selectedTable={selectedTable}
spreadsheetData={spreadsheetData}
errors={errors}
selectedHeaders={selectedHeaders}
incompatibleHeaders={incompatibleHeaders}
/>
<SidePanel.Separator />
</>
)}
</SidePanel>
)
}
export default SpreadsheetImport
| studio/components/interfaces/TableGridEditor/SidePanelEditor/SpreadsheetImport/SpreadsheetImport.tsx | 0 | https://github.com/supabase/supabase/commit/2f78bf4c33a05fa9d4231be80fe1fff4bd6d9ada | [
0.9746218323707581,
0.16174541413784027,
0.00016621334361843765,
0.0001726703194435686,
0.3520316779613495
] |
{
"id": 0,
"code_window": [
"\n",
" const [targetNotification, setTargetNotification] = useState<Notification>()\n",
"\n",
" if (!notifications) return <></>\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
" if (!notifications || !Array.isArray(notifications)) return <></>\n"
],
"file_path": "studio/components/layouts/ProjectLayout/LayoutHeader/NotificationsPopover/index.tsx",
"type": "replace",
"edit_start_line_idx": 35
} | import Link from 'next/link'
import SubscriptionV2 from 'components/interfaces/BillingV2/Subscription/Subscription'
import { SettingsLayout } from 'components/layouts'
import { useSelectedOrganization } from 'hooks'
import { NextPageWithLayout } from 'types'
import { Alert } from 'ui'
const ProjectBilling: NextPageWithLayout = () => {
const organization = useSelectedOrganization()
const isOrgBilling = !!organization?.subscription_id
if (isOrgBilling) {
return (
<div className="p-4">
<Alert
withIcon
variant="info"
title="This page is only available for projects which are on their own subscription"
>
Subscription management can be found on the{' '}
<Link href={`/org/${organization?.slug}/billing`}>
<a className="text-brand-900">organization's billing</a>
</Link>{' '}
page instead.
</Alert>
</div>
)
}
return <SubscriptionV2 />
}
ProjectBilling.getLayout = (page) => (
<SettingsLayout title="Billing and Usage">{page}</SettingsLayout>
)
export default ProjectBilling
| studio/pages/project/[ref]/settings/billing/subscription.tsx | 0 | https://github.com/supabase/supabase/commit/2f78bf4c33a05fa9d4231be80fe1fff4bd6d9ada | [
0.0001831636909628287,
0.00017373224545735866,
0.0001678701228229329,
0.00017194758402183652,
0.000005824020263389684
] |
{
"id": 0,
"code_window": [
"\n",
" const [targetNotification, setTargetNotification] = useState<Notification>()\n",
"\n",
" if (!notifications) return <></>\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
" if (!notifications || !Array.isArray(notifications)) return <></>\n"
],
"file_path": "studio/components/layouts/ProjectLayout/LayoutHeader/NotificationsPopover/index.tsx",
"type": "replace",
"edit_start_line_idx": 35
} | <svg width="400" height="211" viewBox="0 0 400 211" fill="none" xmlns="http://www.w3.org/2000/svg">
<g clip-path="url(#clip0_4348_100683)">
<rect x="200.689" y="24.5557" width="235.466" height="117.627" rx="3" stroke="url(#paint0_radial_4348_100683)" stroke-width="0.5" stroke-dasharray="2.05 3.41"/>
<rect x="18.5918" y="151.697" width="146.622" height="70.089" rx="3" stroke="url(#paint1_radial_4348_100683)" stroke-width="0.5" stroke-dasharray="2.05 3.41"/>
<rect x="-4.30078" y="-23.9202" width="144.514" height="110.236" rx="3" stroke="url(#paint2_radial_4348_100683)" stroke-width="0.5" stroke-dasharray="2.05 3.41"/>
<path d="M159.77 22.1903L159.655 25.0748L162.211 23.7325L159.77 22.1903ZM179.828 59.8429L161.038 24.0661L160.595 24.2985L179.386 60.0754L179.828 59.8429Z" fill="url(#paint3_linear_4348_100683)"/>
<path d="M226.582 35.0326L224.031 36.3851L226.478 37.9174L226.582 35.0326ZM204.149 71.3202L225.599 37.0721L225.176 36.8067L203.725 71.0548L204.149 71.3202Z" fill="url(#paint4_linear_4348_100683)"/>
<path d="M22.776 131.891L25.4341 133.017L25.0802 130.152L22.776 131.891ZM110.996 120.743L24.9784 131.367L25.0397 131.863L111.057 121.239L110.996 120.743Z" fill="url(#paint5_linear_4348_100683)"/>
<path d="M83.4132 141.409L86.2076 142.133L85.4376 139.351L83.4132 141.409ZM139.612 125.594L85.515 140.568L85.6484 141.049L139.745 126.076L139.612 125.594Z" fill="url(#paint6_linear_4348_100683)"/>
<path d="M58.5526 114.338L60.7877 116.165L61.2522 113.316L58.5526 114.338ZM91.6999 119.49L60.8135 114.454L60.733 114.947L91.6194 119.983L91.6999 119.49Z" fill="url(#paint7_linear_4348_100683)"/>
<path d="M271.871 163.422L270.248 161.035L268.992 163.634L271.871 163.422ZM241.558 149.054L269.736 162.668L269.954 162.218L241.776 148.604L241.558 149.054Z" fill="url(#paint8_linear_4348_100683)"/>
<path d="M348.902 176.341L347.147 174.049L346.039 176.715L348.902 176.341ZM282.072 148.855L346.728 175.709L346.92 175.247L282.264 148.393L282.072 148.855Z" fill="url(#paint9_linear_4348_100683)"/>
<path d="M338.206 67.2336L335.32 67.2761L336.8 69.7546L338.206 67.2336ZM304.479 87.6662L336.403 68.6018L336.146 68.1725L304.222 87.237L304.479 87.6662Z" fill="url(#paint10_linear_4348_100683)"/>
<path d="M348.748 87.3558L346.058 86.3077L346.496 89.1612L348.748 87.3558ZM224.287 106.679L346.562 87.9437L346.486 87.4495L224.211 106.184L224.287 106.679Z" fill="url(#paint11_linear_4348_100683)"/>
<circle cx="109.972" cy="64.962" r="3.04773" transform="rotate(-9.50119 109.972 64.962)" stroke="#105C3B"/>
<circle cx="320.19" cy="117.318" r="3.04773" stroke="#105C3B"/>
<circle cx="285.216" cy="53.5845" r="3.04773" stroke="#105C3B"/>
<circle cx="257.518" cy="113.685" r="3.04773" stroke="#1A2520"/>
<path fill-rule="evenodd" clip-rule="evenodd" d="M241.062 114.136C240.565 112.634 239.266 111.587 237.584 111.335C236.792 111.217 235.884 111.268 234.81 111.489C232.938 111.875 231.548 112.022 230.535 112.051C234.361 105.59 237.473 98.2228 239.264 91.2876C242.16 80.0739 240.612 74.9652 238.804 72.6543C234.017 66.5383 227.034 63.2524 218.608 63.1517C214.114 63.0969 210.168 63.9843 208.11 64.6222C206.194 64.2843 204.133 64.0955 201.971 64.0605C197.918 63.9959 194.337 64.8793 191.278 66.695C189.583 66.1224 186.865 65.3149 183.725 64.7994C176.341 63.5871 170.39 64.5318 166.037 67.6071C160.765 71.3306 158.322 77.7998 158.774 86.8353C158.917 89.7041 160.522 98.4323 163.049 106.71C164.501 111.468 166.049 115.419 167.651 118.455C169.923 122.759 172.353 125.294 175.082 126.204C176.611 126.714 179.39 127.07 182.313 124.636C182.684 125.085 183.178 125.531 183.834 125.945C184.667 126.47 185.685 126.899 186.703 127.154C190.369 128.07 193.803 127.841 196.733 126.557C196.751 127.078 196.765 127.575 196.777 128.005C196.796 128.703 196.815 129.386 196.841 130.026C197.014 134.349 197.309 137.711 198.18 140.063C198.228 140.193 198.292 140.39 198.36 140.599C198.795 141.93 199.522 144.159 201.372 145.904C203.287 147.712 205.604 148.267 207.726 148.266C208.79 148.266 209.806 148.127 210.696 147.936C213.871 147.256 217.476 146.219 220.085 142.505C222.55 138.995 223.749 133.707 223.966 125.375C223.994 125.14 224.02 124.915 224.045 124.7C224.062 124.555 224.079 124.408 224.096 124.26L224.677 124.311L224.827 124.321C228.061 124.468 232.014 123.783 234.442 122.655C236.361 121.764 242.509 118.519 241.062 114.136Z" fill="#161616"/>
<path fill-rule="evenodd" clip-rule="evenodd" d="M241.062 114.136C240.565 112.634 239.266 111.587 237.584 111.335C236.792 111.217 235.884 111.268 234.81 111.489C232.938 111.875 231.548 112.022 230.535 112.051C234.361 105.59 237.473 98.2228 239.264 91.2876C242.16 80.0739 240.612 74.9652 238.804 72.6543C234.017 66.5383 227.034 63.2524 218.608 63.1517C214.114 63.0969 210.168 63.9843 208.11 64.6222C206.194 64.2843 204.133 64.0955 201.971 64.0605C197.918 63.9959 194.337 64.8793 191.278 66.695C189.583 66.1224 186.865 65.3149 183.725 64.7994C176.341 63.5871 170.39 64.5318 166.037 67.6071C160.765 71.3306 158.322 77.7998 158.774 86.8353C158.917 89.7041 160.522 98.4323 163.049 106.71C164.501 111.468 166.049 115.419 167.651 118.455C169.923 122.759 172.353 125.294 175.082 126.204C176.611 126.714 179.39 127.07 182.313 124.636C182.684 125.085 183.178 125.531 183.834 125.945C184.667 126.47 185.685 126.899 186.703 127.154C190.369 128.07 193.803 127.841 196.733 126.557C196.751 127.078 196.765 127.575 196.777 128.005C196.796 128.703 196.815 129.386 196.841 130.026C197.014 134.349 197.309 137.711 198.18 140.063C198.228 140.193 198.292 140.39 198.36 140.599C198.795 141.93 199.522 144.159 201.372 145.904C203.287 147.712 205.604 148.267 207.726 148.266C208.79 148.266 209.806 148.127 210.696 147.936C213.871 147.256 217.476 146.219 220.085 142.505C222.55 138.995 223.749 133.707 223.966 125.375C223.994 125.14 224.02 124.915 224.045 124.7C224.062 124.555 224.079 124.408 224.096 124.26L224.677 124.311L224.827 124.321C228.061 124.468 232.014 123.783 234.442 122.655C236.361 121.764 242.509 118.519 241.062 114.136ZM193.563 89.3901C192.696 89.2695 191.912 89.3811 191.515 89.6816C191.291 89.8507 191.222 90.0466 191.204 90.1815C191.154 90.5388 191.404 90.9336 191.558 91.1374C191.993 91.714 192.629 92.1104 193.258 92.1977C193.349 92.2104 193.44 92.2165 193.53 92.2165C194.579 92.2165 195.533 91.3996 195.617 90.7966C195.722 90.0415 194.626 89.538 193.563 89.3901ZM222.262 89.4119H222.262C222.179 88.82 221.126 88.6512 220.126 88.7902C219.128 88.9293 218.16 89.3798 218.241 89.9731C218.306 90.4345 219.139 91.2221 220.125 91.2219C220.208 91.2219 220.292 91.2163 220.377 91.2045C221.035 91.1133 221.518 90.6953 221.747 90.4543C222.097 90.0874 222.299 89.678 222.262 89.4119ZM238.733 114.763C238.367 113.654 237.187 113.297 235.227 113.702C229.406 114.904 227.322 114.072 226.637 113.568C231.161 106.675 234.883 98.3441 236.891 90.5708C237.842 86.8888 238.368 83.4693 238.41 80.6823C238.458 77.6228 237.937 75.3749 236.862 74.0017C232.53 68.4655 226.171 65.496 218.474 65.4144C213.182 65.3549 208.712 66.7093 207.845 67.09C206.02 66.6361 204.03 66.3574 201.864 66.3219C197.891 66.2576 194.458 67.2087 191.615 69.1471C190.38 68.6876 187.188 67.5921 183.286 66.9635C176.538 65.8769 171.176 66.7001 167.35 69.4108C162.784 72.6455 160.677 78.4274 161.085 86.5958C161.223 89.3442 162.788 97.7983 165.26 105.895C168.512 116.551 172.048 122.584 175.768 123.825C176.204 123.97 176.706 124.071 177.26 124.071C178.617 124.071 180.281 123.46 182.012 121.378C184.887 117.919 187.572 115.02 188.562 113.967C190.024 114.752 191.631 115.19 193.274 115.234C193.277 115.277 193.281 115.32 193.285 115.363C192.955 115.754 192.685 116.097 192.455 116.39C191.316 117.835 191.079 118.136 187.414 118.89C186.372 119.105 183.602 119.676 183.562 121.617C183.518 123.738 186.835 124.628 187.213 124.723C188.53 125.052 189.799 125.215 191.009 125.215C193.952 125.215 196.541 124.248 198.611 122.376C198.547 129.936 198.862 137.386 199.77 139.656C200.513 141.514 202.33 146.055 208.067 146.054C208.908 146.054 209.835 145.957 210.854 145.738C216.841 144.454 219.441 141.808 220.447 135.974C220.985 132.856 221.909 125.411 222.343 121.417C223.26 121.703 224.441 121.834 225.717 121.834C228.378 121.834 231.448 121.269 233.374 120.375C235.537 119.37 239.441 116.905 238.733 114.763ZM224.474 87.7766C224.454 88.9557 224.292 90.026 224.12 91.1433C223.935 92.3449 223.743 93.5872 223.695 95.0954C223.647 96.5631 223.831 98.089 224.008 99.5645C224.366 102.545 224.734 105.613 223.311 108.641C223.09 108.249 222.876 107.82 222.68 107.345C222.504 106.917 222.12 106.228 221.588 105.275C219.519 101.565 214.675 92.8778 217.155 89.3328C217.893 88.2774 219.768 87.1927 224.474 87.7766ZM218.77 67.8025C225.666 67.9548 231.122 70.5348 234.984 75.4705C237.947 79.2563 234.685 96.4825 225.241 111.344C225.148 111.225 225.053 111.105 224.955 110.983C224.915 110.934 224.875 110.884 224.835 110.833C227.275 106.803 226.798 102.816 226.373 99.28C226.199 97.8292 226.034 96.4588 226.076 95.1718C226.119 93.8071 226.3 92.6373 226.474 91.5058C226.689 90.1113 226.907 88.6687 226.847 86.9679C226.892 86.7896 226.91 86.5787 226.886 86.3286C226.733 84.6975 224.871 79.8167 221.075 75.3984C218.999 72.9822 215.972 70.278 211.838 68.454C213.616 68.0856 216.048 67.7419 218.77 67.8025ZM180.18 119.854C178.273 122.147 176.956 121.708 176.523 121.564C173.7 120.622 170.426 114.657 167.538 105.198C165.04 97.0135 163.58 88.7834 163.465 86.4756C163.1 79.1768 164.869 74.09 168.724 71.3565C174.996 66.9081 185.31 69.5706 189.454 70.9211C189.394 70.9798 189.332 71.0349 189.273 71.0945C182.473 77.9622 182.634 89.6959 182.651 90.413C182.65 90.6897 182.673 91.0815 182.705 91.6205C182.822 93.5939 183.04 97.267 182.458 101.427C181.918 105.292 183.109 109.075 185.727 111.807C185.998 112.089 186.281 112.355 186.573 112.604C185.408 113.852 182.875 116.612 180.18 119.854ZM187.444 110.162C185.334 107.961 184.376 104.899 184.815 101.76C185.429 97.366 185.203 93.5391 185.081 91.4832C185.064 91.1955 185.049 90.9434 185.04 90.7445C186.033 89.8638 190.637 87.3969 193.92 88.1492C195.418 88.4924 196.331 89.5125 196.71 91.2674C198.675 100.352 196.971 104.139 195.601 107.182C195.319 107.808 195.052 108.401 194.824 109.014L194.648 109.488C194.201 110.686 193.785 111.8 193.528 112.858C191.285 112.851 189.103 111.893 187.444 110.162ZM187.791 122.411C187.136 122.247 186.547 121.963 186.201 121.727C186.49 121.591 187.004 121.407 187.894 121.223C192.206 120.335 192.872 119.709 194.326 117.863C194.659 117.44 195.037 116.96 195.56 116.375C195.561 116.375 195.561 116.375 195.561 116.374C196.341 115.502 196.697 115.65 197.344 115.918C197.868 116.135 198.378 116.791 198.585 117.514C198.683 117.856 198.793 118.504 198.433 119.008C195.395 123.261 190.969 123.206 187.791 122.411ZM210.351 143.414C205.076 144.544 203.209 141.853 201.978 138.776C201.184 136.79 200.794 127.833 201.071 117.942C201.074 117.81 201.055 117.683 201.019 117.564C200.988 117.333 200.939 117.1 200.872 116.865C200.46 115.426 199.456 114.222 198.252 113.723C197.774 113.524 196.895 113.161 195.84 113.431C196.065 112.503 196.456 111.457 196.879 110.323L197.056 109.846C197.256 109.308 197.507 108.751 197.772 108.162C199.205 104.978 201.168 100.617 199.038 90.7662C198.24 87.0766 195.575 85.2748 191.536 85.6932C189.115 85.9437 186.899 86.9208 185.795 87.481C185.557 87.6014 185.34 87.7176 185.137 87.8309C185.445 84.1131 186.61 77.1655 190.969 72.7698C193.713 70.0023 197.367 68.6355 201.82 68.7091C210.594 68.8528 216.22 73.3554 219.395 77.1074C222.131 80.3407 223.613 83.5975 224.204 85.3539C219.758 84.9019 216.734 85.7798 215.2 87.9714C211.865 92.7389 217.025 101.992 219.505 106.44C219.96 107.255 220.352 107.959 220.476 108.258C221.283 110.215 222.329 111.522 223.092 112.476C223.326 112.768 223.553 113.052 223.726 113.299C222.379 113.687 219.96 114.584 220.18 119.068C220.002 121.319 218.738 131.853 218.096 135.574C217.248 140.491 215.438 142.323 210.351 143.414ZM232.368 118.213C230.991 118.852 228.687 119.332 226.497 119.434C224.079 119.548 222.848 119.164 222.559 118.927C222.423 116.133 223.463 115.841 224.564 115.532C224.737 115.483 224.906 115.436 225.068 115.379C225.17 115.461 225.281 115.543 225.402 115.623C227.345 116.906 230.812 117.045 235.706 116.034C235.724 116.031 235.742 116.027 235.76 116.024C235.1 116.641 233.97 117.469 232.368 118.213Z" fill="url(#paint12_linear_4348_100683)" fill-opacity="0.5"/>
<path d="M116.381 67.6907L119.811 72.3348L122.118 67.0422L116.381 67.6907ZM188.523 98.5887L120.706 69.0304L120.307 69.9471L188.124 99.5055L188.523 98.5887Z" fill="url(#paint13_linear_4348_100683)"/>
<path d="M275.136 59.9765L269.375 59.6054L271.934 64.7806L275.136 59.9765ZM246.01 74.9386L271.324 62.4195L270.881 61.5232L245.567 74.0422L246.01 74.9386Z" fill="url(#paint14_linear_4348_100683)"/>
<path d="M313.313 117.318L308.498 114.132L308.146 119.895L313.313 117.318ZM262.192 114.7L308.79 117.543L308.851 116.545L262.253 113.702L262.192 114.7Z" fill="url(#paint15_linear_4348_100683)"/>
<path d="M137.386 160.551L143.155 160.781L140.47 155.67L137.386 160.551ZM190.26 132.21L141.137 158.015L141.602 158.901L190.725 133.095L190.26 132.21Z" fill="url(#paint16_linear_4348_100683)"/>
<circle cx="179.001" cy="138.046" r="3.04773" transform="rotate(-9.50119 179.001 138.046)" stroke="#1A2520"/>
<circle cx="130.257" cy="163.188" r="3.04773" transform="rotate(-9.50119 130.257 163.188)" stroke="#105C3B"/>
<path d="M74.2695 167.881H72.7255V160.417H74.2695V161.025H73.3815V167.281H74.2695V167.881ZM74.8702 166.185C74.8702 165.873 75.1102 165.625 75.4222 165.625C75.7342 165.625 75.9822 165.873 75.9822 166.185C75.9822 166.497 75.7342 166.737 75.4222 166.737C75.1102 166.737 74.8702 166.497 74.8702 166.185ZM79.0726 164.729H76.9046V164.073H79.0726V164.729ZM80.6112 164.105C80.6112 164.897 80.7552 165.457 81.0672 165.785C81.2672 165.993 81.5232 166.121 81.8912 166.121C82.2592 166.121 82.5152 165.993 82.7152 165.785C83.0272 165.457 83.1712 164.897 83.1712 164.105C83.1712 163.313 83.0272 162.753 82.7152 162.425C82.5152 162.217 82.2592 162.089 81.8912 162.089C81.5232 162.089 81.2672 162.217 81.0672 162.425C80.7552 162.753 80.6112 163.313 80.6112 164.105ZM79.8352 164.105C79.8352 163.393 79.9552 162.737 80.2992 162.225C80.6352 161.721 81.1552 161.393 81.8912 161.393C82.6272 161.393 83.1472 161.721 83.4832 162.225C83.8272 162.737 83.9472 163.393 83.9472 164.105C83.9472 164.817 83.8272 165.473 83.4832 165.985C83.1472 166.489 82.6272 166.817 81.8912 166.817C81.1552 166.817 80.6352 166.489 80.2992 165.985C79.9552 165.473 79.8352 164.817 79.8352 164.105ZM86.5342 166.697H85.7662V163.041H84.5102V162.489C85.2302 162.473 85.7262 162.073 85.8462 161.513H86.5342V166.697ZM87.6124 166.185C87.6124 165.897 87.8604 165.649 88.1964 165.649C88.5404 165.649 88.8444 165.905 88.8444 166.409C88.8444 167.465 88.1564 167.905 87.6604 167.969V167.553C88.0524 167.465 88.3164 167.073 88.3244 166.689C88.3004 166.705 88.2364 166.729 88.1484 166.729C87.8524 166.729 87.6124 166.529 87.6124 166.185ZM91.964 166.185C91.964 165.873 92.204 165.625 92.516 165.625C92.828 165.625 93.076 165.873 93.076 166.185C93.076 166.497 92.828 166.737 92.516 166.737C92.204 166.737 91.964 166.497 91.964 166.185ZM96.1664 164.729H93.9984V164.073H96.1664V164.729ZM97.657 163.377L96.873 163.281C96.865 163.209 96.865 163.137 96.865 163.073C96.865 162.185 97.521 161.393 98.657 161.393C99.769 161.393 100.409 162.121 100.409 162.985C100.409 163.665 100.025 164.209 99.433 164.585L98.409 165.241C98.113 165.433 97.849 165.649 97.777 165.969H100.441V166.697H96.809C96.825 165.849 97.161 165.201 98.041 164.633L98.905 164.073C99.393 163.761 99.617 163.393 99.617 162.993C99.617 162.521 99.297 162.081 98.641 162.081C97.961 162.081 97.641 162.553 97.641 163.145C97.641 163.217 97.649 163.297 97.657 163.377ZM101.323 166.185C101.323 165.897 101.571 165.649 101.907 165.649C102.251 165.649 102.555 165.905 102.555 166.409C102.555 167.465 101.867 167.905 101.371 167.969V167.553C101.763 167.465 102.027 167.073 102.035 166.689C102.011 166.705 101.947 166.729 101.859 166.729C101.563 166.729 101.323 166.529 101.323 166.185ZM105.675 166.185C105.675 165.873 105.915 165.625 106.227 165.625C106.539 165.625 106.787 165.873 106.787 166.185C106.787 166.497 106.539 166.737 106.227 166.737C105.915 166.737 105.675 166.497 105.675 166.185ZM109.877 164.729H107.709V164.073H109.877V164.729ZM111.416 164.105C111.416 164.897 111.56 165.457 111.872 165.785C112.072 165.993 112.328 166.121 112.696 166.121C113.064 166.121 113.32 165.993 113.52 165.785C113.832 165.457 113.976 164.897 113.976 164.105C113.976 163.313 113.832 162.753 113.52 162.425C113.32 162.217 113.064 162.089 112.696 162.089C112.328 162.089 112.072 162.217 111.872 162.425C111.56 162.753 111.416 163.313 111.416 164.105ZM110.64 164.105C110.64 163.393 110.76 162.737 111.104 162.225C111.44 161.721 111.96 161.393 112.696 161.393C113.432 161.393 113.952 161.721 114.288 162.225C114.632 162.737 114.752 163.393 114.752 164.105C114.752 164.817 114.632 165.473 114.288 165.985C113.952 166.489 113.432 166.817 112.696 166.817C111.96 166.817 111.44 166.489 111.104 165.985C110.76 165.473 110.64 164.817 110.64 164.105ZM116.282 163.377L115.498 163.281C115.49 163.209 115.49 163.137 115.49 163.073C115.49 162.185 116.146 161.393 117.282 161.393C118.394 161.393 119.034 162.121 119.034 162.985C119.034 163.665 118.65 164.209 118.058 164.585L117.034 165.241C116.738 165.433 116.474 165.649 116.402 165.969H119.066V166.697H115.434C115.45 165.849 115.786 165.201 116.666 164.633L117.53 164.073C118.018 163.761 118.242 163.393 118.242 162.993C118.242 162.521 117.922 162.081 117.266 162.081C116.586 162.081 116.266 162.553 116.266 163.145C116.266 163.217 116.274 163.297 116.282 163.377ZM120.972 167.881H119.428V167.281H120.316V161.025H119.428V160.417H120.972V167.881Z" fill="url(#paint17_linear_4348_100683)"/>
<path d="M338.186 121.403H336.642V113.939H338.186V114.547H337.298V120.803H338.186V121.403ZM338.786 119.707C338.786 119.395 339.026 119.147 339.338 119.147C339.65 119.147 339.898 119.395 339.898 119.707C339.898 120.019 339.65 120.259 339.338 120.259C339.026 120.259 338.786 120.019 338.786 119.707ZM341.48 117.627C341.48 118.419 341.624 118.979 341.936 119.307C342.136 119.515 342.392 119.643 342.76 119.643C343.128 119.643 343.384 119.515 343.584 119.307C343.896 118.979 344.04 118.419 344.04 117.627C344.04 116.835 343.896 116.275 343.584 115.947C343.384 115.739 343.128 115.611 342.76 115.611C342.392 115.611 342.136 115.739 341.936 115.947C341.624 116.275 341.48 116.835 341.48 117.627ZM340.704 117.627C340.704 116.915 340.824 116.259 341.168 115.747C341.504 115.243 342.024 114.915 342.76 114.915C343.496 114.915 344.016 115.243 344.352 115.747C344.696 116.259 344.816 116.915 344.816 117.627C344.816 118.339 344.696 118.995 344.352 119.507C344.016 120.011 343.496 120.339 342.76 120.339C342.024 120.339 341.504 120.011 341.168 119.507C340.824 118.995 340.704 118.339 340.704 117.627ZM346.979 117.811L346.595 117.163L348.123 115.755H345.643V115.035H349.163V115.739L347.683 117.107C348.443 117.107 349.283 117.619 349.283 118.683C349.283 119.555 348.611 120.347 347.403 120.347C346.203 120.347 345.523 119.563 345.475 118.715L346.243 118.539C346.275 119.227 346.771 119.659 347.395 119.659C348.107 119.659 348.491 119.219 348.491 118.699C348.491 118.019 347.947 117.731 347.435 117.731C347.275 117.731 347.115 117.763 346.979 117.811ZM350.083 119.707C350.083 119.419 350.331 119.171 350.667 119.171C351.011 119.171 351.315 119.427 351.315 119.931C351.315 120.987 350.627 121.427 350.131 121.491V121.075C350.523 120.987 350.787 120.595 350.795 120.211C350.771 120.227 350.707 120.251 350.619 120.251C350.323 120.251 350.083 120.051 350.083 119.707ZM354.435 119.707C354.435 119.395 354.675 119.147 354.987 119.147C355.299 119.147 355.547 119.395 355.547 119.707C355.547 120.019 355.299 120.259 354.987 120.259C354.675 120.259 354.435 120.019 354.435 119.707ZM357.909 117.811L357.525 117.163L359.053 115.755H356.573V115.035H360.093V115.739L358.613 117.107C359.373 117.107 360.213 117.619 360.213 118.683C360.213 119.555 359.541 120.347 358.333 120.347C357.133 120.347 356.453 119.563 356.405 118.715L357.173 118.539C357.205 119.227 357.701 119.659 358.325 119.659C359.037 119.659 359.421 119.219 359.421 118.699C359.421 118.019 358.877 117.731 358.365 117.731C358.205 117.731 358.045 117.763 357.909 117.811ZM361.013 119.707C361.013 119.419 361.261 119.171 361.597 119.171C361.941 119.171 362.245 119.427 362.245 119.931C362.245 120.987 361.557 121.427 361.061 121.491V121.075C361.453 120.987 361.717 120.595 361.725 120.211C361.701 120.227 361.637 120.251 361.549 120.251C361.253 120.251 361.013 120.051 361.013 119.707ZM365.364 119.707C365.364 119.395 365.604 119.147 365.916 119.147C366.228 119.147 366.476 119.395 366.476 119.707C366.476 120.019 366.228 120.259 365.916 120.259C365.604 120.259 365.364 120.019 365.364 119.707ZM368.058 117.627C368.058 118.419 368.202 118.979 368.514 119.307C368.714 119.515 368.97 119.643 369.338 119.643C369.706 119.643 369.962 119.515 370.162 119.307C370.474 118.979 370.618 118.419 370.618 117.627C370.618 116.835 370.474 116.275 370.162 115.947C369.962 115.739 369.706 115.611 369.338 115.611C368.97 115.611 368.714 115.739 368.514 115.947C368.202 116.275 368.058 116.835 368.058 117.627ZM367.282 117.627C367.282 116.915 367.402 116.259 367.746 115.747C368.082 115.243 368.602 114.915 369.338 114.915C370.074 114.915 370.594 115.243 370.93 115.747C371.274 116.259 371.394 116.915 371.394 117.627C371.394 118.339 371.274 118.995 370.93 119.507C370.594 120.011 370.074 120.339 369.338 120.339C368.602 120.339 368.082 120.011 367.746 119.507C367.402 118.995 367.282 118.339 367.282 117.627ZM373.557 117.811L373.173 117.163L374.701 115.755H372.221V115.035H375.741V115.739L374.261 117.107C375.021 117.107 375.861 117.619 375.861 118.683C375.861 119.555 375.189 120.347 373.981 120.347C372.781 120.347 372.101 119.563 372.053 118.715L372.821 118.539C372.853 119.227 373.349 119.659 373.973 119.659C374.685 119.659 375.069 119.219 375.069 118.699C375.069 118.019 374.525 117.731 374.013 117.731C373.853 117.731 373.693 117.763 373.557 117.811ZM377.763 121.403H376.219V120.803H377.107V114.547H376.219V113.939H377.763V121.403Z" fill="url(#paint18_linear_4348_100683)"/>
<path d="M300.744 57.4318H299.2V49.9678H300.744V50.5758H299.856V56.8318H300.744V57.4318ZM301.345 55.7358C301.345 55.4238 301.585 55.1758 301.897 55.1758C302.209 55.1758 302.457 55.4238 302.457 55.7358C302.457 56.0478 302.209 56.2878 301.897 56.2878C301.585 56.2878 301.345 56.0478 301.345 55.7358ZM304.039 53.6558C304.039 54.4478 304.183 55.0078 304.495 55.3358C304.695 55.5438 304.951 55.6718 305.319 55.6718C305.687 55.6718 305.943 55.5438 306.143 55.3358C306.455 55.0078 306.599 54.4478 306.599 53.6558C306.599 52.8638 306.455 52.3038 306.143 51.9758C305.943 51.7678 305.687 51.6398 305.319 51.6398C304.951 51.6398 304.695 51.7678 304.495 51.9758C304.183 52.3038 304.039 52.8638 304.039 53.6558ZM303.263 53.6558C303.263 52.9438 303.383 52.2878 303.727 51.7758C304.063 51.2718 304.583 50.9438 305.319 50.9438C306.055 50.9438 306.575 51.2718 306.911 51.7758C307.255 52.2878 307.375 52.9438 307.375 53.6558C307.375 54.3678 307.255 55.0238 306.911 55.5358C306.575 56.0398 306.055 56.3678 305.319 56.3678C304.583 56.3678 304.063 56.0398 303.727 55.5358C303.383 55.0238 303.263 54.3678 303.263 53.6558ZM308.018 54.8398L308.77 54.6158C308.818 55.2558 309.29 55.6878 309.938 55.6878C310.554 55.6878 311.05 55.2798 311.05 54.6398C311.05 53.9278 310.53 53.5678 309.93 53.5678C309.562 53.5678 309.21 53.7118 308.986 53.9438C308.714 53.8398 308.482 53.7358 308.218 53.6398L308.89 51.0638H311.626V51.7838H309.41L309.026 53.2718C309.258 53.0158 309.674 52.8878 310.082 52.8878C311.098 52.8878 311.842 53.5358 311.842 54.6078C311.842 55.5838 311.09 56.3758 309.938 56.3758C308.834 56.3758 308.09 55.6558 308.018 54.8398ZM312.603 55.7358C312.603 55.4478 312.851 55.1998 313.187 55.1998C313.531 55.1998 313.835 55.4558 313.835 55.9598C313.835 57.0158 313.147 57.4558 312.651 57.5198V57.1038C313.043 57.0158 313.307 56.6238 313.315 56.2398C313.291 56.2558 313.227 56.2798 313.139 56.2798C312.843 56.2798 312.603 56.0798 312.603 55.7358ZM316.954 55.7358C316.954 55.4238 317.194 55.1758 317.506 55.1758C317.818 55.1758 318.066 55.4238 318.066 55.7358C318.066 56.0478 317.818 56.2878 317.506 56.2878C317.194 56.2878 316.954 56.0478 316.954 55.7358ZM318.51 55.0798V54.1758L320.734 51.0638H321.814V54.3518H322.702V55.0798H321.814V56.2478H321.054V55.0798H318.51ZM321.054 54.3518V51.8158L319.23 54.3518H321.054ZM323.384 55.7358C323.384 55.4478 323.632 55.1998 323.968 55.1998C324.312 55.1998 324.616 55.4558 324.616 55.9598C324.616 57.0158 323.928 57.4558 323.432 57.5198V57.1038C323.824 57.0158 324.088 56.6238 324.096 56.2398C324.072 56.2558 324.008 56.2798 323.92 56.2798C323.624 56.2798 323.384 56.0798 323.384 55.7358ZM327.735 55.7358C327.735 55.4238 327.975 55.1758 328.287 55.1758C328.599 55.1758 328.847 55.4238 328.847 55.7358C328.847 56.0478 328.599 56.2878 328.287 56.2878C327.975 56.2878 327.735 56.0478 327.735 55.7358ZM330.43 53.6558C330.43 54.4478 330.574 55.0078 330.886 55.3358C331.086 55.5438 331.342 55.6718 331.71 55.6718C332.078 55.6718 332.334 55.5438 332.534 55.3358C332.846 55.0078 332.99 54.4478 332.99 53.6558C332.99 52.8638 332.846 52.3038 332.534 51.9758C332.334 51.7678 332.078 51.6398 331.71 51.6398C331.342 51.6398 331.086 51.7678 330.886 51.9758C330.574 52.3038 330.43 52.8638 330.43 53.6558ZM329.654 53.6558C329.654 52.9438 329.774 52.2878 330.118 51.7758C330.454 51.2718 330.974 50.9438 331.71 50.9438C332.446 50.9438 332.966 51.2718 333.302 51.7758C333.646 52.2878 333.766 52.9438 333.766 53.6558C333.766 54.3678 333.646 55.0238 333.302 55.5358C332.966 56.0398 332.446 56.3678 331.71 56.3678C330.974 56.3678 330.454 56.0398 330.118 55.5358C329.774 55.0238 329.654 54.3678 329.654 53.6558ZM335.296 52.9278L334.512 52.8318C334.504 52.7598 334.504 52.6878 334.504 52.6238C334.504 51.7358 335.16 50.9438 336.296 50.9438C337.408 50.9438 338.048 51.6718 338.048 52.5358C338.048 53.2158 337.664 53.7598 337.072 54.1358L336.048 54.7918C335.752 54.9838 335.488 55.1998 335.416 55.5198H338.08V56.2478H334.448C334.464 55.3998 334.8 54.7518 335.68 54.1838L336.544 53.6238C337.032 53.3118 337.256 52.9438 337.256 52.5438C337.256 52.0718 336.936 51.6318 336.28 51.6318C335.6 51.6318 335.28 52.1038 335.28 52.6958C335.28 52.7678 335.288 52.8478 335.296 52.9278ZM339.986 57.4318H338.442V56.8318H339.33V50.5758H338.442V49.9678H339.986V57.4318Z" fill="url(#paint19_linear_4348_100683)"/>
<path d="M55.6582 68.087H54.1142V60.623H55.6582V61.231H54.7702V67.487H55.6582V68.087ZM56.2589 66.391C56.2589 66.079 56.4989 65.831 56.8109 65.831C57.1229 65.831 57.3709 66.079 57.3709 66.391C57.3709 66.703 57.1229 66.943 56.8109 66.943C56.4989 66.943 56.2589 66.703 56.2589 66.391ZM60.4613 64.935H58.2933V64.279H60.4613V64.935ZM61.9999 64.311C61.9999 65.103 62.1439 65.663 62.4559 65.991C62.6559 66.199 62.9119 66.327 63.2799 66.327C63.6479 66.327 63.9039 66.199 64.1039 65.991C64.4159 65.663 64.5599 65.103 64.5599 64.311C64.5599 63.519 64.4159 62.959 64.1039 62.631C63.9039 62.423 63.6479 62.295 63.2799 62.295C62.9119 62.295 62.6559 62.423 62.4559 62.631C62.1439 62.959 61.9999 63.519 61.9999 64.311ZM61.2239 64.311C61.2239 63.599 61.3439 62.943 61.6879 62.431C62.0239 61.927 62.5439 61.599 63.2799 61.599C64.0159 61.599 64.5359 61.927 64.8719 62.431C65.2159 62.943 65.3359 63.599 65.3359 64.311C65.3359 65.023 65.2159 65.679 64.8719 66.191C64.5359 66.695 64.0159 67.023 63.2799 67.023C62.5439 67.023 62.0239 66.695 61.6879 66.191C61.3439 65.679 61.2239 65.023 61.2239 64.311ZM67.4989 64.495L67.1149 63.847L68.6429 62.439H66.1629V61.719H69.6829V62.423L68.2029 63.791C68.9629 63.791 69.8029 64.303 69.8029 65.367C69.8029 66.239 69.1309 67.031 67.9229 67.031C66.7229 67.031 66.0429 66.247 65.9949 65.399L66.7629 65.223C66.7949 65.911 67.2909 66.343 67.9149 66.343C68.6269 66.343 69.0109 65.903 69.0109 65.383C69.0109 64.703 68.4669 64.415 67.9549 64.415C67.7949 64.415 67.6349 64.447 67.4989 64.495ZM70.6027 66.391C70.6027 66.103 70.8507 65.855 71.1867 65.855C71.5307 65.855 71.8347 66.111 71.8347 66.615C71.8347 67.671 71.1467 68.111 70.6507 68.175V67.759C71.0427 67.671 71.3067 67.279 71.3147 66.895C71.2907 66.911 71.2267 66.935 71.1387 66.935C70.8427 66.935 70.6027 66.735 70.6027 66.391ZM74.9542 66.391C74.9542 66.079 75.1942 65.831 75.5062 65.831C75.8182 65.831 76.0662 66.079 76.0662 66.391C76.0662 66.703 75.8182 66.943 75.5062 66.943C75.1942 66.943 74.9542 66.703 74.9542 66.391ZM79.1566 64.935H76.9886V64.279H79.1566V64.935ZM81.587 66.903H80.819V63.247H79.563V62.695C80.283 62.679 80.779 62.279 80.899 61.719H81.587V66.903ZM82.6652 66.391C82.6652 66.103 82.9132 65.855 83.2492 65.855C83.5932 65.855 83.8972 66.111 83.8972 66.615C83.8972 67.671 83.2092 68.111 82.7132 68.175V67.759C83.1052 67.671 83.3692 67.279 83.3772 66.895C83.3532 66.911 83.2892 66.935 83.2012 66.935C82.9052 66.935 82.6652 66.735 82.6652 66.391ZM87.0167 66.391C87.0167 66.079 87.2567 65.831 87.5687 65.831C87.8807 65.831 88.1287 66.079 88.1287 66.391C88.1287 66.703 87.8807 66.943 87.5687 66.943C87.2567 66.943 87.0167 66.703 87.0167 66.391ZM89.7108 64.311C89.7108 65.103 89.8548 65.663 90.1668 65.991C90.3668 66.199 90.6228 66.327 90.9908 66.327C91.3588 66.327 91.6148 66.199 91.8148 65.991C92.1268 65.663 92.2708 65.103 92.2708 64.311C92.2708 63.519 92.1268 62.959 91.8148 62.631C91.6148 62.423 91.3588 62.295 90.9908 62.295C90.6228 62.295 90.3668 62.423 90.1668 62.631C89.8548 62.959 89.7108 63.519 89.7108 64.311ZM88.9348 64.311C88.9348 63.599 89.0548 62.943 89.3988 62.431C89.7348 61.927 90.2548 61.599 90.9908 61.599C91.7268 61.599 92.2468 61.927 92.5828 62.431C92.9268 62.943 93.0468 63.599 93.0468 64.311C93.0468 65.023 92.9268 65.679 92.5828 66.191C92.2468 66.695 91.7268 67.023 90.9908 67.023C90.2548 67.023 89.7348 66.695 89.3988 66.191C89.0548 65.679 88.9348 65.023 88.9348 64.311ZM95.6338 66.903H94.8658V63.247H93.6098V62.695C94.3298 62.679 94.8258 62.279 94.9458 61.719H95.6338V66.903ZM97.8923 68.087H96.3483V67.487H97.2363V61.231H96.3483V60.623H97.8923V68.087Z" fill="url(#paint20_linear_4348_100683)"/>
</g>
<defs>
<radialGradient id="paint0_radial_4348_100683" cx="0" cy="0" r="1" gradientUnits="userSpaceOnUse" gradientTransform="translate(318.349 84.3513) rotate(90) scale(50.1628 71.9898)">
<stop stop-color="#17FDDF"/>
<stop offset="1" stop-color="#10FFE0"/>
</radialGradient>
<radialGradient id="paint1_radial_4348_100683" cx="0" cy="0" r="1" gradientUnits="userSpaceOnUse" gradientTransform="translate(91.8568 187.327) rotate(90) scale(29.89 44.8271)">
<stop stop-color="#17FDDF"/>
<stop offset="1" stop-color="#10FFE0"/>
</radialGradient>
<radialGradient id="paint2_radial_4348_100683" cx="0" cy="0" r="1" gradientUnits="userSpaceOnUse" gradientTransform="translate(67.9111 32.1183) rotate(90) scale(47.0109 44.1827)">
<stop stop-color="#17FDDF"/>
<stop offset="1" stop-color="#10FFE0"/>
</radialGradient>
<linearGradient id="paint3_linear_4348_100683" x1="161.294" y1="21.1947" x2="180.69" y2="41.3103" gradientUnits="userSpaceOnUse">
<stop stop-color="#C4C4C4"/>
<stop offset="1" stop-color="#3F3F3F" stop-opacity="0"/>
</linearGradient>
<linearGradient id="paint4_linear_4348_100683" x1="228.209" y1="35.8478" x2="220.595" y2="62.7341" gradientUnits="userSpaceOnUse">
<stop stop-color="#C4C4C4"/>
<stop offset="1" stop-color="#3F3F3F" stop-opacity="0"/>
</linearGradient>
<linearGradient id="paint5_linear_4348_100683" x1="29.3744" y1="119.38" x2="75.7395" y2="141.27" gradientUnits="userSpaceOnUse">
<stop stop-color="#C4C4C4"/>
<stop offset="1" stop-color="#3F3F3F" stop-opacity="0"/>
</linearGradient>
<linearGradient id="paint6_linear_4348_100683" x1="82.6101" y1="140.712" x2="92.9289" y2="117.571" gradientUnits="userSpaceOnUse">
<stop stop-color="#C4C4C4"/>
<stop offset="1" stop-color="#3F3F3F" stop-opacity="0"/>
</linearGradient>
<linearGradient id="paint7_linear_4348_100683" x1="58.4186" y1="113.422" x2="76.2082" y2="105.843" gradientUnits="userSpaceOnUse">
<stop stop-color="#C4C4C4"/>
<stop offset="1" stop-color="#3F3F3F" stop-opacity="0"/>
</linearGradient>
<linearGradient id="paint8_linear_4348_100683" x1="271.739" y1="164.338" x2="252.528" y2="166.544" gradientUnits="userSpaceOnUse">
<stop stop-color="#C4C4C4"/>
<stop offset="1" stop-color="#3F3F3F" stop-opacity="0"/>
</linearGradient>
<linearGradient id="paint9_linear_4348_100683" x1="339.969" y1="182.616" x2="313.683" y2="148.762" gradientUnits="userSpaceOnUse">
<stop stop-color="#C4C4C4"/>
<stop offset="1" stop-color="#3F3F3F" stop-opacity="0"/>
</linearGradient>
<linearGradient id="paint10_linear_4348_100683" x1="339.18" y1="70.9737" x2="314.306" y2="79.7185" gradientUnits="userSpaceOnUse">
<stop stop-color="#C4C4C4"/>
<stop offset="1" stop-color="#3F3F3F" stop-opacity="0"/>
</linearGradient>
<linearGradient id="paint11_linear_4348_100683" x1="348.763" y1="98.9458" x2="248.593" y2="102.179" gradientUnits="userSpaceOnUse">
<stop stop-color="white"/>
<stop offset="1" stop-color="#696969" stop-opacity="0"/>
</linearGradient>
<linearGradient id="paint12_linear_4348_100683" x1="182.806" y1="81.6693" x2="217.33" y2="143.322" gradientUnits="userSpaceOnUse">
<stop stop-color="#70F8BB"/>
<stop offset="1" stop-color="#A3A3A3" stop-opacity="0.6"/>
</linearGradient>
<linearGradient id="paint13_linear_4348_100683" x1="119.984" y1="70.7266" x2="145.904" y2="96.1937" gradientUnits="userSpaceOnUse">
<stop stop-color="#00FF8E"/>
<stop offset="1" stop-color="#3DCB8C" stop-opacity="0"/>
</linearGradient>
<linearGradient id="paint14_linear_4348_100683" x1="274.274" y1="72.4848" x2="247.293" y2="75.9329" gradientUnits="userSpaceOnUse">
<stop stop-color="#02FF8F"/>
<stop offset="1" stop-color="#3DCB8C" stop-opacity="0"/>
</linearGradient>
<linearGradient id="paint15_linear_4348_100683" x1="309.014" y1="126.432" x2="264.074" y2="125.141" gradientUnits="userSpaceOnUse">
<stop stop-color="#02FF8F"/>
<stop offset="1" stop-color="#3DCB8C" stop-opacity="0"/>
</linearGradient>
<linearGradient id="paint16_linear_4348_100683" x1="136.467" y1="159.105" x2="159.181" y2="135.7" gradientUnits="userSpaceOnUse">
<stop stop-color="#3ECF8E"/>
<stop offset="1" stop-color="#3DCB8C" stop-opacity="0"/>
</linearGradient>
<linearGradient id="paint17_linear_4348_100683" x1="96.8493" y1="150.697" x2="96.8493" y2="176.895" gradientUnits="userSpaceOnUse">
<stop stop-color="#23FF98"/>
<stop offset="1" stop-color="#49FFAA" stop-opacity="0"/>
</linearGradient>
<linearGradient id="paint18_linear_4348_100683" x1="357.203" y1="104.219" x2="357.203" y2="130.417" gradientUnits="userSpaceOnUse">
<stop stop-color="#23FF98"/>
<stop offset="1" stop-color="#49FFAA" stop-opacity="0"/>
</linearGradient>
<linearGradient id="paint19_linear_4348_100683" x1="319.593" y1="40.2478" x2="319.593" y2="66.4461" gradientUnits="userSpaceOnUse">
<stop stop-color="#23FF98"/>
<stop offset="1" stop-color="#49FFAA" stop-opacity="0"/>
</linearGradient>
<linearGradient id="paint20_linear_4348_100683" x1="76.0036" y1="50.903" x2="76.0036" y2="77.1013" gradientUnits="userSpaceOnUse">
<stop stop-color="#23FF98"/>
<stop offset="1" stop-color="#49FFAA" stop-opacity="0"/>
</linearGradient>
<clipPath id="clip0_4348_100683">
<rect width="400" height="210" fill="white" transform="translate(0 0.707886)"/>
</clipPath>
</defs>
</svg>
| apps/www/public/images/product/vector/highlight-pgvector.svg | 0 | https://github.com/supabase/supabase/commit/2f78bf4c33a05fa9d4231be80fe1fff4bd6d9ada | [
0.0003958211455028504,
0.0001860629126895219,
0.00016686537128407508,
0.000168056387337856,
0.000060576119722099975
] |
{
"id": 1,
"code_window": [
"\n",
" const hasNewNotifications = notifications?.some(\n",
" (notification) => notification.notification_status === NotificationStatus.New\n",
" )\n",
"\n",
" const onOpenChange = async (open: boolean) => {\n"
],
"labels": [
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" const hasNewNotifications = notifications.some(\n"
],
"file_path": "studio/components/layouts/ProjectLayout/LayoutHeader/NotificationsPopover/index.tsx",
"type": "replace",
"edit_start_line_idx": 37
} | import * as Tooltip from '@radix-ui/react-tooltip'
import {
ActionType,
Notification,
NotificationStatus,
} from '@supabase/shared-types/out/notifications'
import { useQueryClient } from '@tanstack/react-query'
import dayjs from 'dayjs'
import { useRouter } from 'next/router'
import { Fragment, useState } from 'react'
import ConfirmModal from 'components/ui/Dialogs/ConfirmDialog'
import { useNotificationsQuery } from 'data/notifications/notifications-query'
import { getProjectDetail } from 'data/projects/project-detail-query'
import { invalidateProjectsQuery, setProjectPostgrestStatus } from 'data/projects/projects-query'
import { useStore } from 'hooks'
import { delete_, patch, post } from 'lib/common/fetch'
import { API_URL } from 'lib/constants'
import { Project } from 'types'
import { Alert, Button, IconArrowRight, IconBell, Popover } from 'ui'
import NotificationRow from './NotificationRow'
const NotificationsPopover = () => {
const queryClient = useQueryClient()
const router = useRouter()
const { meta, ui } = useStore()
const { data: notifications, refetch } = useNotificationsQuery()
const [projectToRestart, setProjectToRestart] = useState<Project>()
const [projectToApplyMigration, setProjectToApplyMigration] = useState<Project>()
const [projectToRollbackMigration, setProjectToRollbackMigration] = useState<Project>()
const [projectToFinalizeMigration, setProjectToFinalizeMigration] = useState<Project>()
const [targetNotification, setTargetNotification] = useState<Notification>()
if (!notifications) return <></>
const hasNewNotifications = notifications?.some(
(notification) => notification.notification_status === NotificationStatus.New
)
const onOpenChange = async (open: boolean) => {
// TODO(alaister): move this to a mutation
if (!open) {
// Mark notifications as seen
const notificationIds = notifications
.filter((notification) => notification.notification_status === NotificationStatus.New)
.map((notification) => notification.id)
if (notificationIds.length > 0) {
const { error } = await patch(`${API_URL}/notifications`, { ids: notificationIds })
if (error) console.error('Failed to update notifications', error)
refetch()
}
}
}
const onConfirmProjectRestart = async () => {
if (!projectToRestart || !targetNotification) return
const { id } = targetNotification
const { ref, region } = projectToRestart
const serviceNamesByActionName: Record<string, string> = {
[ActionType.PgBouncerRestart]: 'pgbouncer',
[ActionType.SchedulePostgresRestart]: 'postgresql',
[ActionType.MigratePostgresSchema]: 'postgresql',
}
const services: string[] = targetNotification.meta.actions_available
.map((action) => action.action_type)
.filter((actionName) => Object.keys(serviceNamesByActionName).indexOf(actionName) !== -1)
.map((actionName) => serviceNamesByActionName[actionName])
const { error } = await post(`${API_URL}/projects/${ref}/restart-services`, {
restartRequest: {
region,
source_notification_id: id,
services: services,
},
})
if (error) {
ui.setNotification({
category: 'error',
message: `Failed to restart project: ${error.message}`,
error,
})
} else {
setProjectPostgrestStatus(queryClient, ref, 'OFFLINE')
ui.setNotification({ category: 'success', message: `Restarting services` })
router.push(`/project/${ref}`)
}
setProjectToRestart(undefined)
setTargetNotification(undefined)
}
// [Joshen/Qiao] These are all very specific to the upcoming security patch
// https://github.com/supabase/supabase/discussions/9314
// We probably need to revisit this again when we're planning to push out the next wave of
// notifications. Ideally, we should allow these to be more flexible and configurable
// Perhaps the URLs could come from the notification themselves if the actions
// require an external API call, then we just need one method instead of individual ones like this
const onConfirmProjectApplyMigration = async () => {
if (!projectToApplyMigration) return
const res = await post(`${API_URL}/database/${projectToApplyMigration.ref}/owner-reassign`, {})
if (!res.error) {
const project = await getProjectDetail({ ref: projectToApplyMigration.ref })
if (project) {
meta.setProjectDetails(project)
}
ui.setNotification({
category: 'success',
message: `Successfully applied migration for project "${projectToApplyMigration.name}"`,
})
} else {
ui.setNotification({
error: res.error,
category: 'error',
message: `Failed to apply migration: ${res.error.message}`,
})
}
setProjectToApplyMigration(undefined)
}
const onConfirmProjectRollbackMigration = async () => {
if (!projectToRollbackMigration) return
const res = await delete_(
`${API_URL}/database/${projectToRollbackMigration.ref}/owner-reassign`,
{}
)
if (!res.error) {
const project = await getProjectDetail({ ref: projectToRollbackMigration.ref })
if (project) {
meta.setProjectDetails(project)
}
ui.setNotification({
category: 'success',
message: `Successfully rolled back migration for project "${projectToRollbackMigration.name}"`,
})
} else {
ui.setNotification({
error: res.error,
category: 'error',
message: `Failed to roll back migration: ${res.error.message}`,
})
}
setProjectToRollbackMigration(undefined)
}
const onConfirmProjectFinalizeMigration = async () => {
if (!projectToFinalizeMigration) return
const res = await patch(
`${API_URL}/database/${projectToFinalizeMigration.ref}/owner-reassign`,
{}
)
if (!res.error) {
const project = await getProjectDetail({ ref: projectToFinalizeMigration.ref })
if (project) {
meta.setProjectDetails(project)
}
ui.setNotification({
category: 'success',
message: `Successfully finalized migration for project "${projectToFinalizeMigration.name}"`,
})
} else {
ui.setNotification({
error: res.error,
category: 'error',
message: `Failed to finalize migration: ${res.error.message}`,
})
}
setProjectToFinalizeMigration(undefined)
}
return (
<>
<Popover
size="content"
align="end"
side="bottom"
sideOffset={8}
onOpenChange={onOpenChange}
overlay={
<div className="w-[400px] lg:w-[700px]">
<div className="flex items-center justify-between border-b border-gray-500 bg-gray-400 px-4 py-2">
<p className="text-sm">Notifications</p>
{/* Area for improvement: Paginate notifications and show in a side panel */}
{/* <p className="text-scale-1000 hover:text-scale-1200 cursor-pointer text-sm transition">
See all{' '}
{notifications.length > MAX_NOTIFICATIONS_TO_SHOW && `(${notifications.length})`}
</p> */}
</div>
<div className="max-h-[380px] overflow-y-auto py-2">
{notifications.length === 0 ? (
<div className="py-2 px-4">
<p className="text-sm text-scale-1000">No notifications available</p>
</div>
) : (
<>
{notifications.map((notification, i: number) => (
<Fragment key={notification.id}>
<NotificationRow
notification={notification}
onSelectRestartProject={(project, notification) => {
setProjectToRestart(project)
setTargetNotification(notification)
}}
onSelectApplyMigration={(project, notification) => {
setProjectToApplyMigration(project)
setTargetNotification(notification)
}}
onSelectRollbackMigration={(project, notification) => {
setProjectToRollbackMigration(project)
setTargetNotification(notification)
}}
onSelectFinalizeMigration={(project, notification) => {
setProjectToFinalizeMigration(project)
setTargetNotification(notification)
}}
/>
{i !== notifications.length - 1 && <Popover.Separator />}
</Fragment>
))}
</>
)}
</div>
</div>
}
>
<Tooltip.Root delayDuration={0}>
<Tooltip.Trigger asChild>
<div className="relative flex">
<Button
asChild
id="notification-button"
type="default"
icon={<IconBell size={16} strokeWidth={1.5} className="text-scale-1200" />}
>
<span></span>
</Button>
{hasNewNotifications && (
<div className="absolute -top-1 -right-1 z-50 flex h-3 w-3 items-center justify-center">
<div className="h-full w-full animate-ping rounded-full bg-green-800 opacity-60"></div>
<div className="z-60 absolute top-0 right-0 h-full w-full rounded-full bg-green-900 opacity-80"></div>
</div>
)}
</div>
</Tooltip.Trigger>
<Tooltip.Portal>
<Tooltip.Content side="bottom">
<Tooltip.Arrow className="radix-tooltip-arrow" />
<div
className={[
'rounded bg-scale-100 py-1 px-2 leading-none shadow',
'border border-scale-200 flex items-center space-x-1',
].join(' ')}
>
<span className="text-xs text-scale-1200">Notifications</span>
</div>
</Tooltip.Content>
</Tooltip.Portal>
</Tooltip.Root>
</Popover>
<ConfirmModal
danger
visible={projectToRestart !== undefined}
title={`Restart project "${projectToRestart?.name}"`}
description={`Are you sure you want to restart the project? There will be a few minutes of downtime.`}
buttonLabel="Restart"
buttonLoadingLabel="Restarting"
onSelectCancel={() => setProjectToRestart(undefined)}
onSelectConfirm={onConfirmProjectRestart}
/>
<ConfirmModal
size="large"
visible={projectToApplyMigration !== undefined}
title={`Apply schema migration for "${projectToApplyMigration?.name}"`}
// @ts-ignore
description={
<div className="text-scale-1200 space-y-2">
<div className="space-y-1">
<p>The following schema migration will be applied to the project</p>
<ol className="list-disc pl-6">
<li>
<div className="flex items-center space-x-1">
<p>{(targetNotification?.data as any)?.additional?.name}</p>
<IconArrowRight size={12} strokeWidth={2} />
<p>{(targetNotification?.data as any)?.additional?.version_to}</p>
</div>
</li>
</ol>
</div>
<p>
This change can be rolled back anytime up till{' '}
{dayjs(
new Date(targetNotification?.meta.actions_available?.[0]?.deadline ?? 0)
).format('DD MMM YYYY, HH:mma ZZ')}
, after which the changes will be finalized and can no longer be undone.
</p>
</div>
}
buttonLabel="Confirm"
buttonLoadingLabel="Confirm"
onSelectCancel={() => setProjectToApplyMigration(undefined)}
onSelectConfirm={onConfirmProjectApplyMigration}
/>
<ConfirmModal
size="medium"
visible={projectToRollbackMigration !== undefined}
title={`Rollback schema migration for "${projectToRollbackMigration?.name}"`}
// @ts-ignore
description={
<div className="text-scale-1200 space-y-2">
<div className="space-y-1">
<p>The following schema migration will be rolled back for the project</p>
<ol className="list-disc pl-6">
<li>
<div className="flex items-center space-x-1">
<p>{(targetNotification?.data as any)?.additional?.name}</p>
<IconArrowRight size={12} strokeWidth={2} />
<p>{(targetNotification?.data as any)?.additional?.version_to}</p>
</div>
</li>
</ol>
</div>
<p>
This migration however will still be applied and finalized after{' '}
{dayjs(
new Date(targetNotification?.meta.actions_available?.[0]?.deadline ?? 0)
).format('DD MMM YYYY, HH:mma ZZ')}
, after which the changes can no longer be undone.
</p>
</div>
}
buttonLabel="Confirm"
buttonLoadingLabel="Confirm"
onSelectCancel={() => setProjectToRollbackMigration(undefined)}
onSelectConfirm={onConfirmProjectRollbackMigration}
/>
<ConfirmModal
danger
size="small"
visible={projectToFinalizeMigration !== undefined}
title={`Finalize schema migration for "${projectToFinalizeMigration?.name}"`}
// @ts-ignore
description={
<div className="text-scale-1200 space-y-4">
<Alert withIcon variant="warning" title="This action canot be undone" />
<div className="space-y-1">
<p>The following schema migration will be finalized for the project</p>
<ol className="list-disc pl-6">
<li>
<div className="flex items-center space-x-1">
<p>{(targetNotification?.data as any)?.additional?.name}</p>
<IconArrowRight size={12} strokeWidth={2} />
<p>{(targetNotification?.data as any)?.additional?.version_to}</p>
</div>
</li>
</ol>
</div>
</div>
}
buttonLabel="Confirm"
buttonLoadingLabel="Confirm"
onSelectCancel={() => setProjectToFinalizeMigration(undefined)}
onSelectConfirm={onConfirmProjectFinalizeMigration}
/>
</>
)
}
export default NotificationsPopover
| studio/components/layouts/ProjectLayout/LayoutHeader/NotificationsPopover/index.tsx | 1 | https://github.com/supabase/supabase/commit/2f78bf4c33a05fa9d4231be80fe1fff4bd6d9ada | [
0.9987433552742004,
0.11329781264066696,
0.0001652301725698635,
0.00021036317048128694,
0.30547234416007996
] |
{
"id": 1,
"code_window": [
"\n",
" const hasNewNotifications = notifications?.some(\n",
" (notification) => notification.notification_status === NotificationStatus.New\n",
" )\n",
"\n",
" const onOpenChange = async (open: boolean) => {\n"
],
"labels": [
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" const hasNewNotifications = notifications.some(\n"
],
"file_path": "studio/components/layouts/ProjectLayout/LayoutHeader/NotificationsPopover/index.tsx",
"type": "replace",
"edit_start_line_idx": 37
} | import { LOGS_TAILWIND_CLASSES } from '../Logs.constants'
import { jsonSyntaxHighlight, SelectionDetailedRow } from '../LogsFormatters'
const DefaultExplorerSelectionRenderer = ({ log }: any) => {
const DetailedJsonRow = ({
label,
value,
code,
}: {
label: string
value: Object
code?: boolean
}) => {
return (
<div className="grid grid-cols-12">
<span className="text-scale-900 text-sm col-span-4">{label}</span>
<span
className={`text-scale-1200 text-sm col-span-8 overflow-x-auto ${
code && 'text-xs font-mono'
}`}
>
<pre
dangerouslySetInnerHTML={{
__html: jsonSyntaxHighlight(value),
}}
/>
</span>
</div>
)
}
return (
<div className="overflow-hidden overflow-x-auto space-y-6">
{Object.entries(log).map(([key, value], index) => {
return (
<div
key={`${key}-${index}`}
className={`${LOGS_TAILWIND_CLASSES.log_selection_x_padding}`}
>
{value && typeof value === 'object' ? (
<DetailedJsonRow label={key} value={value} />
) : (
<SelectionDetailedRow label={key} value={value === null ? 'NULL ' : String(value)} />
)}
</div>
)
})}
</div>
)
}
export default DefaultExplorerSelectionRenderer
| studio/components/interfaces/Settings/Logs/LogSelectionRenderers/DefaultExplorerSelectionRenderer.tsx | 0 | https://github.com/supabase/supabase/commit/2f78bf4c33a05fa9d4231be80fe1fff4bd6d9ada | [
0.00017167792248073965,
0.00016918852634262294,
0.00016449180839117616,
0.0001699077256489545,
0.0000024828186724334955
] |
{
"id": 1,
"code_window": [
"\n",
" const hasNewNotifications = notifications?.some(\n",
" (notification) => notification.notification_status === NotificationStatus.New\n",
" )\n",
"\n",
" const onOpenChange = async (open: boolean) => {\n"
],
"labels": [
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" const hasNewNotifications = notifications.some(\n"
],
"file_path": "studio/components/layouts/ProjectLayout/LayoutHeader/NotificationsPopover/index.tsx",
"type": "replace",
"edit_start_line_idx": 37
} | ---
title: 'Getting started with Flutter authentication'
description: Learn how authentication on Flutter works through Google sign in with Supabase auth.
tags:
- flutter
- auth
date: '2023-07-18'
toc_depth: 2
author: tyler_shukert
image: flutter-authentication/flutter-authentication.png
thumb: flutter-authentication/flutter-authentication.png
---
Flutter is Google’s open-source framework to develop cross-platform applications. In this article, we will take a look at how we can implement authentication using Google sign-in to secure our application using the [Supabase SDK for Flutter](https://supabase.com/docs/reference/dart/introduction).
We will also dive into the deep ends of Open ID Connect sign-in to better understand how third-party sign-ins are being performed. You can check out the code of the sample in this article [here](https://github.com/supabase/supabase/tree/master/examples/auth/flutter-native-google-auth).
## Prerequisites
This article assumes you are comfortable with writing a basic application in Flutter. No knowledge of Supabase is required.
We will use the following tools
- [Flutter](https://docs.flutter.dev/get-started/install) - we used v3.10.5 for this article
- Supabase - create your account [here](https://database.new/) if you do not have one
- IDE of your choosing
## What is Open ID Connect?
We will implement third-party login with Google utilizing the Open ID Connect functionality of Supabase Auth. Open ID Connect, or OIDC is a protocol built on top of OAuth 2.0 that allows third-party applications to request the users to provide some personal information, such as name or profile image, in the form of an identity token along with an access token. This identity token can then be verified and decoded by the application to obtain that personal information.
Supabase auth provides `signInWithIdToken` method where we can sign in a user using their ID token obtained from third-party auth providers such as Google. Upon signing a user with the `signInWithIdToken` method, Supabase automatically populates the content of the ID token in the Supabase user metadata for easy access to the information. We will be utilizing this feature in this example to display the user profile upon the user signing in.
In today’s example, our app will make a request to Google, obtain the identity token, and we will use it to sign the user in as well as obtain basic user information.
## What we will build
We will build a simple app with a login screen and a home screen. The user is first presented with the login screen, and only after they sign in, can they proceed to the home screen. The login screen presents a login button that will kick off a third-party authentication flow to complete the sign-in. The profile screen displays user information such as the profile image or their full name.

## Setup the Flutter project
Let’s start by creating a fresh Flutter project.
```bash
flutter create myauthapp
```
then we can install the dependencies. Change the working directory to the newly created app directory and run the following command to install our dependencies.
```dart
flutter pub add supabase_flutter flutter_appauth crypto
```
We will use [supabase_flutter](https://pub.dev/packages/supabase_flutter) to interact with our Supabase instance. [flutter_appauth](https://pub.dev/packages/flutter_appauth) will be used to implement Google login, and [crypto](https://pub.dev/packages/crypto) is a library that has utility functions for encryption that we will use when performing OIDC logins.
We are done installing our dependencies. Let’s set up [authentication](https://supabase.com/docs/guides/auth) now.
## Configure Google sign-in on Supabase Auth
We will obtain client IDs for iOS and Android from the Google Cloud console, and register them to our Supabase project.
First, create your Google Cloud project [here](https://cloud.google.com/) if you do not have one yet. Within your Google Cloud project, follow the [Configure a Google API Console project for Android](https://developers.google.com/identity/sign-in/android/start-integrating#configure_a_project) guide and [Get an OAuth client ID for the iOS](https://developers.google.com/identity/sign-in/ios/start-integrating#get_an_oauth_client_id) guide to obtain client IDs for Android and iOS respectively.
Once you have the client IDs, let’s add them to our Supabase dashboard. If you don’t have a Supabase project created yet, you can create one at [database.new](https://database.new) for free. The name is just an internal name, so we can call it “Auth” for now. Database Password will not be used in this example and can be reconfigured later, so press the `Generate a password` button and let Supabase generate a secure random password. No need to copy it anywhere. The region should be anywhere close to where you live, or where your users live in an actual production app.
Lastly, for the pricing plan choose the free plan that allows you to connect with all major social OAuth providers and supports up to 50,000 monthly active users.

Your project should be ready in a minute or two. Once your project is ready, you can open `authentication -> Providers -> Google` to set up Google auth. Toggle the `Enable Sign in with Google` switch first. Then add the two client IDs you obtained in your Google Cloud console to `Authorized Client IDs` field with a comma in between the two client IDs like this: `ANDROID_CLIENT_ID,IOS_CLIENT_ID`.

We also need some Android specific settings to make [flutter_appauth](https://pub.dev/packages/flutter_appauth#android-setup) work. Open `android/app/build.gradle` and find the `defaultConfig`. We need to set the reversed DNS form of the Android Client ID as the`appAuthRedirectScheme` manifest placeholder value.
```groovy
...
android {
...
defaultConfig {
...
manifestPlaceholders += [
// *account_id* will be unique for every single app
'appAuthRedirectScheme': 'com.googleusercontent.apps.*account_id*'
]
}
}
```
That is it for setting up our [Supabase auth to prepare for Google sign-in](https://supabase.com/docs/guides/auth/social-login/auth-google#using-native-sign-in).
Finally, we can initialize Supabase in our Flutter application with the credentials of our Supabase instance. Update your `main.dart` file and add `Supabase.initialize()` in the `main` function like the following. Note that you will see some errors since the home screen is set to the `LoginScreen`, which we will create later.
```dart
import 'package:flutter/material.dart';
import 'package:myauthapp/screens/login_screen.dart';
import 'package:supabase_flutter/supabase_flutter.dart';
void main() async {
/// TODO: update Supabase credentials with your own
await Supabase.initialize(
url: 'YOUR_SUPABASE_URL',
anonKey: 'YOUR_ANON_KEY',
);
runApp(const MyApp());
}
final supabase = Supabase.instance.client;
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Flutter Auth',
theme: ThemeData(
colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
useMaterial3: true,
),
home: const LoginScreen(),
);
}
}
```
You can find your Supabase URL and Anon key in `Settings -> API` from your [Supabase dashboard](https://supabase.com/dashboard/project/_/settings/api).

## Create the Login Screen
We will have two screens for this app, `LoginScreen` and `ProfileScreen`. `LoginScreen` presents a single sign-in button for the user to perform Google sign-in. Create a `lib/screens/login_screen.dart` file add add the following.
```dart
import 'dart:convert';
import 'dart:io';
import 'dart:math';
import 'package:crypto/crypto.dart';
import 'package:flutter/material.dart';
import 'package:flutter_appauth/flutter_appauth.dart';
import 'package:myauthapp/main.dart';
import 'package:myauthapp/screens/profile_screen.dart';
import 'package:supabase_flutter/supabase_flutter.dart';
class LoginScreen extends StatefulWidget {
const LoginScreen({super.key});
@override
State<LoginScreen> createState() => _LoginScreenState();
}
class _LoginScreenState extends State<LoginScreen> {
@override
void initState() {
_setupAuthListener();
super.initState();
}
void _setupAuthListener() {
supabase.auth.onAuthStateChange.listen((data) {
final event = data.event;
if (event == AuthChangeEvent.signedIn) {
Navigator.of(context).pushReplacement(
MaterialPageRoute(
builder: (context) => const ProfileScreen(),
),
);
}
});
}
/// Function to generate a random 16 character string.
String _generateRandomString() {
final random = Random.secure();
return base64Url.encode(List<int>.generate(16, (_) => random.nextInt(256)));
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Login'),
),
body: Center(
child: ElevatedButton(
onPressed: () async {
const appAuth = FlutterAppAuth();
// Just a random string
final rawNonce = _generateRandomString();
final hashedNonce =
sha256.convert(utf8.encode(rawNonce)).toString();
/// TODO: update the iOS and Android client ID with your own.
///
/// Client ID that you registered with Google Cloud.
/// You will have two different values for iOS and Android.
final clientId =
Platform.isIOS ? 'IOS_CLIENT_ID' : 'ANDROID_CLIENT_ID';
/// Set as reversed DNS form of Google Client ID + `:/` for Google login
final redirectUrl = '${clientId.split('.').reversed.join('.')}:/';
/// Fixed value for google login
const discoveryUrl =
'https://accounts.google.com/.well-known/openid-configuration';
// authorize the user by opening the concent page
final result = await appAuth.authorize(
AuthorizationRequest(
clientId,
redirectUrl,
discoveryUrl: discoveryUrl,
nonce: hashedNonce,
scopes: [
'openid',
'email',
'profile',
],
),
);
if (result == null) {
throw 'No result';
}
// Request the access and id token to google
final tokenResult = await appAuth.token(
TokenRequest(
clientId,
redirectUrl,
authorizationCode: result.authorizationCode,
discoveryUrl: discoveryUrl,
codeVerifier: result.codeVerifier,
nonce: result.nonce,
scopes: [
'openid',
'email',
],
),
);
final idToken = tokenResult?.idToken;
if (idToken == null) {
throw 'No idToken';
}
await supabase.auth.signInWithIdToken(
provider: Provider.google,
idToken: idToken,
nonce: rawNonce,
);
},
child: const Text('Google login'),
),
),
);
}
}
```
In terms of UI, this page is very simple, it just has a basic `Scaffold` with an `AppBar`, and has a button right in the middle of the body. Upon pressing the button, Google sign in flow starts. The user is presented with a Google authentication screen where they will complete the consent to allow our application to sign the user in using a Google account, as well as allow us to view some personal information.

Let’s break down what is going on within the `onPressed` callback of the sign in button.
First, we are generating a [nonce](https://openid.net/specs/openid-connect-core-1_0.html#SelfIssuedDiscovery:~:text=auth_time%20response%20parameter.)-,nonce,-String%20value%20used), which is essentially just a random string. This string is later passed to Google after being hashed to verify that the ID token has not been tampered to prevent a man-in-the-middle attack.
```dart
// Random string to verify the integrity of the ID Token
final rawNonce = _generateRandomString();
final hashedNonce = sha256.convert(utf8.encode(rawNonce)).toString();
```
`clientId` and `applicationId` are the app-specific values. These will be used to the authentication request to Google later on.
```dart
/// Client ID that you registered with Google Cloud.
/// You will have two different values for iOS and Android.
final clientId = Platform.isIOS ? 'IOS_CLIENT_ID' : 'ANDROID_CLIENT_ID';
```
`redirectUrl` is the URL at which the user will be redirected after a successful authentication request. For Google sign-in, we can set it to the reversed DNS form of the client ID followed by `:/`. `discoveryUrl` is a URL provided by Google that contains information about their Open ID configuration.
```dart
/// Set as reversed DNS form of Google Client ID + `:/` for Google login
final redirectUrl = '${clientId.split('.').reversed.join('.')}:/';
/// Fixed value for google login
const discoveryUrl = 'https://accounts.google.com/.well-known/openid-configuration';
```
Then we are sending an authorization request to Google. This is where the user is taken to Google’s page to perform sign in and consent our app to obtain some personal information. Note that we are requesting three scopes here. `openid` and `email` are required by Supabase auth to complete the sign-in process. `profile` is not required by Supabase auth, but we are requesting it to display some profile information on the profile screen later on. We do not actually obtain the requested information in this step though. All we are doing is requesting an access token that has permission to obtain the personal information we have requested.
```dart
// Authorize the user by opening the concent page
final result = await appAuth.authorize(
AuthorizationRequest(
clientId,
redirectUrl,
discoveryUrl: discoveryUrl,
nonce: hashedNonce,
scopes: [
'openid',
'email',
'profile',
],
),
);
```
Using the authorization token obtained in the previous step, we make the final request to Google’s auth server to obtain the personal information we asked for earlier. We get an ID token in return, which contains the personal information.
```dart
// Request the access and id token to google
final tokenResult = await appAuth.token(
TokenRequest(
clientId,
redirectUrl,
authorizationCode: result.authorizationCode,
discoveryUrl: discoveryUrl,
codeVerifier: result.codeVerifier,
nonce: result.nonce,
scopes: [
'openid',
'email',
'profile',
],
),
);
```
And lastly, we pass the ID token we obtained from Google to Supabase to complete the sign-in on Supabase auth. Once the user is signed in, the auth state listener in the `initState` fires and takes the user to the `ProfileScreen`.
```dart
await supabase.auth.signInWithIdToken(
provider: Provider.google,
idToken: idToken,
nonce: rawNonce,
);
```
## Create the Profile Screen
The `ProfileScreen` will be just a simple UI presenting some of the information we obtained in the `LoginPage`. We can access the user data with `supabase.auth.currentUser`, where Supabase has saved the personal information in a property called `userMetadata`. In this example, we are displaying the `avatar_url` and `full_name` to display a basic profile page. Create a `lib/screens/profile_screen.dart` file and add the following.
```dart
import 'package:flutter/material.dart';
import 'package:myauthapp/main.dart';
import 'package:myauthapp/screens/login_screen.dart';
class ProfileScreen extends StatelessWidget {
const ProfileScreen({super.key});
@override
Widget build(BuildContext context) {
final user = supabase.auth.currentUser;
final profileImageUrl = user?.userMetadata?['avatar_url'];
final fullName = user?.userMetadata?['full_name'];
return Scaffold(
appBar: AppBar(
title: const Text('Profile'),
actions: [
TextButton(
onPressed: () async {
await supabase.auth.signOut();
if (context.mounted) {
Navigator.of(context).pushReplacement(
MaterialPageRoute(builder: (context) => const LoginScreen()),
);
}
},
child: const Text('Sign out'),
)
],
),
body: Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
if (profileImageUrl != null)
ClipOval(
child: Image.network(
profileImageUrl,
width: 100,
height: 100,
fit: BoxFit.cover,
),
),
const SizedBox(height: 16),
Text(
fullName ?? '',
style: Theme.of(context).textTheme.headlineMedium,
),
const SizedBox(height: 32),
],
),
),
);
}
}
```
And with that, we now have a basic working personalized application that utilizes Google sign-in.

## Conclusion
In this post, we learned how to implement authentication in a Flutter application using Google sign-in and the Supabase SDK for Flutter. We also delved into the Open ID Connect functionality, which allows third-party sign-ins and the retrieval of personal information through identity tokens.
You can also check out the [Flutter reference documents](https://supabase.com/docs/reference/dart/installing) to see how you can use `supabase-flutter` to implement a Postgres database, Storage, Realtime, and more.
## More Flutter and Supabase resources
- [supabase_flutter package](https://pub.dev/packages/supabase_flutter)
- [Build a chat application using Flutter and Supabase](https://supabase.com/blog/flutter-tutorial-building-a-chat-app)
- [Securing your Flutter apps with Multi-Factor Authentication](https://supabase.com/blog/flutter-multi-factor-authentication)
- [How to build a real-time multiplayer game with Flutter Flame](https://supabase.com/blog/flutter-real-time-multiplayer-game)
| apps/www/_blog/2023-07-18-flutter-authentication.mdx | 0 | https://github.com/supabase/supabase/commit/2f78bf4c33a05fa9d4231be80fe1fff4bd6d9ada | [
0.00021290966833475977,
0.0001707252231426537,
0.0001612172636669129,
0.00016865723591763526,
0.000010040877896244638
] |
{
"id": 1,
"code_window": [
"\n",
" const hasNewNotifications = notifications?.some(\n",
" (notification) => notification.notification_status === NotificationStatus.New\n",
" )\n",
"\n",
" const onOpenChange = async (open: boolean) => {\n"
],
"labels": [
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" const hasNewNotifications = notifications.some(\n"
],
"file_path": "studio/components/layouts/ProjectLayout/LayoutHeader/NotificationsPopover/index.tsx",
"type": "replace",
"edit_start_line_idx": 37
} | import Layout from '~/layouts/DefaultGuideLayout'
import { Accordion } from 'ui'
export const meta = {
id: 'server-side-rendering',
title: 'Server-Side Rendering',
description: 'Render pages with user information on the server.',
}
Single-page apps with server-side rendering (SSR) is a popular way to optimize rendering performance and leverage advanced caching strategies.
Supabase Auth supports server-side rendering when you need access to user information, or your server needs to authorize API requests on behalf of your user to render content.
When a user authenticates with Supabase Auth, two pieces of information are issued by the server:
1. **Access token** in the form of a JWT.
2. **Refresh token** which is a randomly generated string.
Most Supabase projects have their auth server listening on `<project-ref>.supabase.co/auth/v1`, thus the access token and refresh token are set as `sb-access-token` and `sb-refresh-token` cookies on the `<project-ref>.supabase.co` domain.
<Admonition type="note">
These cookie names are for internal Supabase use only and may change without warning. They are included in this guide for illustration purposes only.
</Admonition>
Web browsers limit access to cookies across domains, consistent with the [Same-Origin Policy (SOP)](https://developer.mozilla.org/en-US/docs/Web/Security/Same-origin_policy).
Your web application cannot access these cookies, nor will these cookies be sent to your application's server.
## Understanding the authentication flow
When you call one of the `signIn` methods, the client library running in the browser sends the request to the Supabase Auth server. The Auth server determines whether to verify a phone number, email and password combination, a Magic Link, or use a social login (if you have any setup in your project).
Upon successful verification of the identity of the user, the Supabase Auth server redirects the user back to your single-page app.
<Admonition type="tip">
You can configure [redirects URLs](https://supabase.com/dashboard/project/_/auth/url-configuration) in the Supabase Dashboard. You can use [wildcard match patterns](/docs/guides/auth#redirect-urls-and-wildcards) like `*` and `**` to allow redirects to different forms of URLs.
</Admonition>
Supabase Auth supports two authentication flows: **Implicit** and **PKCE**. The **PKCE** flow is generally preferred when on the server. It introduces a few additional steps which guard a against replay and URL capture attacks. Unlike the implicit flow, it also allows users to access the `access_token` and `refresh_token` on the server.
<Accordion
type="default"
openBehaviour="multiple"
chevronAlign="right"
justified
size="medium"
className="text-scale-900 dark:text-white"
>
<div className="border-b pb-3">
<Accordion.Item
header={<span className="text-scale-1200 font-bold">Implicit</span>}
id={`ssr-implicit-flow`}
>
When using the implicit flow, a redirect URL will be returned with the following structure:
```
https://yourapp.com/...#access_token=<...>&refresh_token=<...>&...
```
The first access and refresh tokens after a successful verification are contained in the URL fragment (anything after the `#` sign) of the redirect location. This is intentional and not configurable.
The client libraries are designed to listen for this type of URL, extract the access token, refresh token and some extra information from it, and finally persist it in local storage for further use by the library and your app.
<Admonition type="info">
Web browsers do not send the URL fragment to the server they're making the request to. Since you may not be hosting the single-page app on a server under your direct control (such as on GitHub Pages or other freemium hosting providers), we want to prevent hosting services from getting access to your user's authorization credentials by default.
Even if the server is under your direct control, `GET` requests and their full URLs are often logged. This approach also avoids leaking credentials in request or access logs. If you wish to obtain the `access_token` and `refresh_token` on a server, please consider using the PKCE flow.
</Admonition>
</Accordion.Item>
</div>
<div className="border-b pb-3">
<Accordion.Item
header={<span className="text-scale-1200 font-bold">PKCE</span>}
id={`ssr-pkce-flow`}
>
When using the PKCE flow, a redirect URL will be returned with the following structure:
```
https://yourapp.com/...?code=<...>
```
The `code` parameter is commonly known as the Auth Code and can be exchanged for an access token by calling `exchangeCodeForSession(code)`.
<Admonition type="info">
For security purposes, the code has a validity of 5 minutes and can only be exchanged for an access token once. You will need to restart the authentication flow from scratch if you wish to obtain a new access token.
</Admonition>
As the flow is run server side, `localStorage` may not be available. You may configure the client library to use a custom storage adapter an alternate backing storage such as cookies by setting the `storage` option to an object with the following methods:
```js
const customStorageAdapter: SupportedStorage = {
getItem: (key) => {
if (!supportsLocalStorage()) {
// Configure alternate storage
return null
}
return globalThis.localStorage.getItem(key)
},
setItem: (key, value) => {
if (!supportsLocalStorage()) {
// Configure alternate storage here
return
}
globalThis.localStorage.setItem(key, value)
},
removeItem: (key) => {
if (!supportsLocalStorage()) {
// Configure alternate storage here
return
}
globalThis.localStorage.removeItem(key)
},
}
```
You may also configure the client library to automatically exchange it for a session after a successful redirect. This can be done by setting the `detectSessionInUrl` option to `true`.
Putting it all together, your client library initialization may look like this:
```js
const supabase = createClient(
'https://xyzcompany.supabase.co',
'public-anon-key',
options: {
...
auth: {
...
detectSessionInUrl: true,
flowType: 'pkce',
storage: customStorageAdapter,
}
...
}
)
```
[Learn more](https://oauth.net/2/pkce/) about the PKCE flow.
</Accordion.Item>
</div>
</Accordion>
## Bringing it together
As seen from the authentication flow, the initial request after successful login made by the browser to your app's server after user login **does not contain any information about the user**. This is because first the client-side JavaScript library must run before it makes the access and refresh token available to your server.
It is very important to make sure that the redirect route right after login works without any server-side rendering. Other routes requiring authorization do not have the same limitation, provided you send the access and refresh tokens to your server.
This is traditionally done by setting cookies. Here's an example you can add to the root of your application:
```typescript
supabase.auth.onAuthStateChange((event, session) => {
if (event === 'SIGNED_OUT' || event === 'USER_DELETED') {
// delete cookies on sign out
const expires = new Date(0).toUTCString()
document.cookie = `my-access-token=; path=/; expires=${expires}; SameSite=Lax; secure`
document.cookie = `my-refresh-token=; path=/; expires=${expires}; SameSite=Lax; secure`
} else if (event === 'SIGNED_IN' || event === 'TOKEN_REFRESHED') {
const maxAge = 100 * 365 * 24 * 60 * 60 // 100 years, never expires
document.cookie = `my-access-token=${session.access_token}; path=/; max-age=${maxAge}; SameSite=Lax; secure`
document.cookie = `my-refresh-token=${session.refresh_token}; path=/; max-age=${maxAge}; SameSite=Lax; secure`
}
})
```
This uses the standard [`document.cookie` API](https://developer.mozilla.org/en-US/docs/Web/API/Document/cookie) to set cookies on all paths of your app's domain. All subsequent requests made by the browser to your app's server include the `my-access-token` and `my-refresh-token` cookies (the names of the cookies and additional parameters can be changed).
In your server-side rendering code you can now access user and session information:
```typescript
const refreshToken = req.cookies['my-refresh-token']
const accessToken = req.cookies['my-access-token']
if (refreshToken && accessToken) {
await supabase.auth.setSession({
refresh_token: refreshToken,
access_token: accessToken,
{
auth: { persistSession: false },
}
})
} else {
// make sure you handle this case!
throw new Error('User is not authenticated.')
}
// returns user information
await supabase.auth.getUser()
```
Use `setSession({ access_token, refresh_token })` instead of `setSession(refreshToken)` or `getUser(accessToken)` as refresh tokens or access tokens alone do not properly identify a user session.
Access tokens are valid only for a short amount of time.
Even though refresh tokens are long-lived, there is no guarantee that a user has an active session. They may have logged out and your application failed to remove the `my-refresh-token` cookie, or some other failure occurred that left a stale refresh token in the browser. Furthermore, a refresh token can only be used a few seconds after it was first used. Only use a refresh token if the access token is about to expire, which will avoid the introduction of difficult to diagnose logout bugs in your app.
A good practice is to handle unauthorized errors by deferring rendering the page in the browser instead of in the server. Some user information is contained in the access token though, so in certain cases, you may be able to use this potentially stale information to render a page.
## Frequently Asked Questions
### No session on the server side with Next.js route prefetching?
When you use route prefetching in Next.js using `<Link href="/...">` components or the `Router.push()` APIs can send server-side requests before the browser processes the access and refresh tokens. This means that those requests may not have any cookies set and your server code will render unauthenticated content.
To improve experience for your users, we recommend redirecting users to one specific page after sign-in that does not include any route prefetching from Next.js. Once the Supabase client library running in the browser has obtained the access and refresh tokens from the URL fragment, you can send users to any pages that use prefetching.
### How do I make the cookies `HttpOnly`?
This is not necessary. Both the access token and refresh token are designed to be passed around to different components in your application. The browser-based side of your application needs access to the refresh token to properly maintain a browser session anyway.
### My server is getting invalid refresh token errors. What's going on?
It is likely that the refresh token sent from the browser to your server is stale. Make sure the `onAuthStateChange` listener callback is free of bugs and is registered relatively early in your application's lifetime
When you receive this error on the server-side, try to defer rendering to the browser where the client library can access an up-to-date refresh token and present the user with a better experience.
### Should I set a shorter `Max-Age` parameter on the cookies?
The `Max-Age` or `Expires` cookie parameters only control whether the browser sends the value to the server. Since a refresh token represents the long-lived authentication session of the user on that browser, setting a short `Max-Age` or `Expires` parameter on the cookies only results in a degraded user experience.
The only way to ensure that a user has logged out or their session has ended is to get the user's details with `getUser()`.
### What should I use for the `SameSite` property?
Make sure you [understand the behavior of the property in different situations](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie/SameSite) as some properties can degrade the user experience.
A good default is to use `Lax` which sends cookies when users are navigating to your site. Cookies typically require the `Secure` attribute, which only sends them over HTTPS. However, this can be a problem when developing on `localhost`.
### Can I use server-side rendering with a CDN or cache?
Yes, but you need to be careful to include at least the refresh token cookie value in the cache key. Otherwise you may be accidentally serving pages with data belonging to different users!
Also be sure you set proper cache control headers. We recommend invalidating cache keys every hour or less.
### Which authentication flows have PKCE support?
At present, PKCE is supported on the Magic Link, OAuth, Sign Up, and Password Recovery routes. These correspond to the `signInWithOtp`, `signInWithOAuth`, `signUp`, and `resetPasswordForEmail` methods on the Supabase client library. When using PKCE with Phone and Email OTPs, there is no behavior change with respect to the implicit flow - an access token will be returned in the body when a request is successful.
export const Page = ({ children }) => <Layout meta={meta} children={children} />
export default Page
| apps/docs/pages/guides/auth/server-side-rendering.mdx | 0 | https://github.com/supabase/supabase/commit/2f78bf4c33a05fa9d4231be80fe1fff4bd6d9ada | [
0.0001750027877278626,
0.00016649658209644258,
0.00016257030074484646,
0.00016608914302196354,
0.0000024336331989616156
] |
{
"id": 2,
"code_window": [
"export async function getOrganizations(signal?: AbortSignal): Promise<Organization[]> {\n",
" const data = await get(`${API_URL}/organizations`, { signal })\n",
" if (data.error) throw data.error\n",
"\n",
" const sorted = (data as Organization[]).sort((a, b) => a.name.localeCompare(b.name))\n",
"\n",
" return sorted\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" if (!Array.isArray(data)) {\n",
" return []\n",
" }\n",
"\n"
],
"file_path": "studio/data/organizations/organizations-query.ts",
"type": "add",
"edit_start_line_idx": 11
} | import * as Tooltip from '@radix-ui/react-tooltip'
import {
ActionType,
Notification,
NotificationStatus,
} from '@supabase/shared-types/out/notifications'
import { useQueryClient } from '@tanstack/react-query'
import dayjs from 'dayjs'
import { useRouter } from 'next/router'
import { Fragment, useState } from 'react'
import ConfirmModal from 'components/ui/Dialogs/ConfirmDialog'
import { useNotificationsQuery } from 'data/notifications/notifications-query'
import { getProjectDetail } from 'data/projects/project-detail-query'
import { invalidateProjectsQuery, setProjectPostgrestStatus } from 'data/projects/projects-query'
import { useStore } from 'hooks'
import { delete_, patch, post } from 'lib/common/fetch'
import { API_URL } from 'lib/constants'
import { Project } from 'types'
import { Alert, Button, IconArrowRight, IconBell, Popover } from 'ui'
import NotificationRow from './NotificationRow'
const NotificationsPopover = () => {
const queryClient = useQueryClient()
const router = useRouter()
const { meta, ui } = useStore()
const { data: notifications, refetch } = useNotificationsQuery()
const [projectToRestart, setProjectToRestart] = useState<Project>()
const [projectToApplyMigration, setProjectToApplyMigration] = useState<Project>()
const [projectToRollbackMigration, setProjectToRollbackMigration] = useState<Project>()
const [projectToFinalizeMigration, setProjectToFinalizeMigration] = useState<Project>()
const [targetNotification, setTargetNotification] = useState<Notification>()
if (!notifications) return <></>
const hasNewNotifications = notifications?.some(
(notification) => notification.notification_status === NotificationStatus.New
)
const onOpenChange = async (open: boolean) => {
// TODO(alaister): move this to a mutation
if (!open) {
// Mark notifications as seen
const notificationIds = notifications
.filter((notification) => notification.notification_status === NotificationStatus.New)
.map((notification) => notification.id)
if (notificationIds.length > 0) {
const { error } = await patch(`${API_URL}/notifications`, { ids: notificationIds })
if (error) console.error('Failed to update notifications', error)
refetch()
}
}
}
const onConfirmProjectRestart = async () => {
if (!projectToRestart || !targetNotification) return
const { id } = targetNotification
const { ref, region } = projectToRestart
const serviceNamesByActionName: Record<string, string> = {
[ActionType.PgBouncerRestart]: 'pgbouncer',
[ActionType.SchedulePostgresRestart]: 'postgresql',
[ActionType.MigratePostgresSchema]: 'postgresql',
}
const services: string[] = targetNotification.meta.actions_available
.map((action) => action.action_type)
.filter((actionName) => Object.keys(serviceNamesByActionName).indexOf(actionName) !== -1)
.map((actionName) => serviceNamesByActionName[actionName])
const { error } = await post(`${API_URL}/projects/${ref}/restart-services`, {
restartRequest: {
region,
source_notification_id: id,
services: services,
},
})
if (error) {
ui.setNotification({
category: 'error',
message: `Failed to restart project: ${error.message}`,
error,
})
} else {
setProjectPostgrestStatus(queryClient, ref, 'OFFLINE')
ui.setNotification({ category: 'success', message: `Restarting services` })
router.push(`/project/${ref}`)
}
setProjectToRestart(undefined)
setTargetNotification(undefined)
}
// [Joshen/Qiao] These are all very specific to the upcoming security patch
// https://github.com/supabase/supabase/discussions/9314
// We probably need to revisit this again when we're planning to push out the next wave of
// notifications. Ideally, we should allow these to be more flexible and configurable
// Perhaps the URLs could come from the notification themselves if the actions
// require an external API call, then we just need one method instead of individual ones like this
const onConfirmProjectApplyMigration = async () => {
if (!projectToApplyMigration) return
const res = await post(`${API_URL}/database/${projectToApplyMigration.ref}/owner-reassign`, {})
if (!res.error) {
const project = await getProjectDetail({ ref: projectToApplyMigration.ref })
if (project) {
meta.setProjectDetails(project)
}
ui.setNotification({
category: 'success',
message: `Successfully applied migration for project "${projectToApplyMigration.name}"`,
})
} else {
ui.setNotification({
error: res.error,
category: 'error',
message: `Failed to apply migration: ${res.error.message}`,
})
}
setProjectToApplyMigration(undefined)
}
const onConfirmProjectRollbackMigration = async () => {
if (!projectToRollbackMigration) return
const res = await delete_(
`${API_URL}/database/${projectToRollbackMigration.ref}/owner-reassign`,
{}
)
if (!res.error) {
const project = await getProjectDetail({ ref: projectToRollbackMigration.ref })
if (project) {
meta.setProjectDetails(project)
}
ui.setNotification({
category: 'success',
message: `Successfully rolled back migration for project "${projectToRollbackMigration.name}"`,
})
} else {
ui.setNotification({
error: res.error,
category: 'error',
message: `Failed to roll back migration: ${res.error.message}`,
})
}
setProjectToRollbackMigration(undefined)
}
const onConfirmProjectFinalizeMigration = async () => {
if (!projectToFinalizeMigration) return
const res = await patch(
`${API_URL}/database/${projectToFinalizeMigration.ref}/owner-reassign`,
{}
)
if (!res.error) {
const project = await getProjectDetail({ ref: projectToFinalizeMigration.ref })
if (project) {
meta.setProjectDetails(project)
}
ui.setNotification({
category: 'success',
message: `Successfully finalized migration for project "${projectToFinalizeMigration.name}"`,
})
} else {
ui.setNotification({
error: res.error,
category: 'error',
message: `Failed to finalize migration: ${res.error.message}`,
})
}
setProjectToFinalizeMigration(undefined)
}
return (
<>
<Popover
size="content"
align="end"
side="bottom"
sideOffset={8}
onOpenChange={onOpenChange}
overlay={
<div className="w-[400px] lg:w-[700px]">
<div className="flex items-center justify-between border-b border-gray-500 bg-gray-400 px-4 py-2">
<p className="text-sm">Notifications</p>
{/* Area for improvement: Paginate notifications and show in a side panel */}
{/* <p className="text-scale-1000 hover:text-scale-1200 cursor-pointer text-sm transition">
See all{' '}
{notifications.length > MAX_NOTIFICATIONS_TO_SHOW && `(${notifications.length})`}
</p> */}
</div>
<div className="max-h-[380px] overflow-y-auto py-2">
{notifications.length === 0 ? (
<div className="py-2 px-4">
<p className="text-sm text-scale-1000">No notifications available</p>
</div>
) : (
<>
{notifications.map((notification, i: number) => (
<Fragment key={notification.id}>
<NotificationRow
notification={notification}
onSelectRestartProject={(project, notification) => {
setProjectToRestart(project)
setTargetNotification(notification)
}}
onSelectApplyMigration={(project, notification) => {
setProjectToApplyMigration(project)
setTargetNotification(notification)
}}
onSelectRollbackMigration={(project, notification) => {
setProjectToRollbackMigration(project)
setTargetNotification(notification)
}}
onSelectFinalizeMigration={(project, notification) => {
setProjectToFinalizeMigration(project)
setTargetNotification(notification)
}}
/>
{i !== notifications.length - 1 && <Popover.Separator />}
</Fragment>
))}
</>
)}
</div>
</div>
}
>
<Tooltip.Root delayDuration={0}>
<Tooltip.Trigger asChild>
<div className="relative flex">
<Button
asChild
id="notification-button"
type="default"
icon={<IconBell size={16} strokeWidth={1.5} className="text-scale-1200" />}
>
<span></span>
</Button>
{hasNewNotifications && (
<div className="absolute -top-1 -right-1 z-50 flex h-3 w-3 items-center justify-center">
<div className="h-full w-full animate-ping rounded-full bg-green-800 opacity-60"></div>
<div className="z-60 absolute top-0 right-0 h-full w-full rounded-full bg-green-900 opacity-80"></div>
</div>
)}
</div>
</Tooltip.Trigger>
<Tooltip.Portal>
<Tooltip.Content side="bottom">
<Tooltip.Arrow className="radix-tooltip-arrow" />
<div
className={[
'rounded bg-scale-100 py-1 px-2 leading-none shadow',
'border border-scale-200 flex items-center space-x-1',
].join(' ')}
>
<span className="text-xs text-scale-1200">Notifications</span>
</div>
</Tooltip.Content>
</Tooltip.Portal>
</Tooltip.Root>
</Popover>
<ConfirmModal
danger
visible={projectToRestart !== undefined}
title={`Restart project "${projectToRestart?.name}"`}
description={`Are you sure you want to restart the project? There will be a few minutes of downtime.`}
buttonLabel="Restart"
buttonLoadingLabel="Restarting"
onSelectCancel={() => setProjectToRestart(undefined)}
onSelectConfirm={onConfirmProjectRestart}
/>
<ConfirmModal
size="large"
visible={projectToApplyMigration !== undefined}
title={`Apply schema migration for "${projectToApplyMigration?.name}"`}
// @ts-ignore
description={
<div className="text-scale-1200 space-y-2">
<div className="space-y-1">
<p>The following schema migration will be applied to the project</p>
<ol className="list-disc pl-6">
<li>
<div className="flex items-center space-x-1">
<p>{(targetNotification?.data as any)?.additional?.name}</p>
<IconArrowRight size={12} strokeWidth={2} />
<p>{(targetNotification?.data as any)?.additional?.version_to}</p>
</div>
</li>
</ol>
</div>
<p>
This change can be rolled back anytime up till{' '}
{dayjs(
new Date(targetNotification?.meta.actions_available?.[0]?.deadline ?? 0)
).format('DD MMM YYYY, HH:mma ZZ')}
, after which the changes will be finalized and can no longer be undone.
</p>
</div>
}
buttonLabel="Confirm"
buttonLoadingLabel="Confirm"
onSelectCancel={() => setProjectToApplyMigration(undefined)}
onSelectConfirm={onConfirmProjectApplyMigration}
/>
<ConfirmModal
size="medium"
visible={projectToRollbackMigration !== undefined}
title={`Rollback schema migration for "${projectToRollbackMigration?.name}"`}
// @ts-ignore
description={
<div className="text-scale-1200 space-y-2">
<div className="space-y-1">
<p>The following schema migration will be rolled back for the project</p>
<ol className="list-disc pl-6">
<li>
<div className="flex items-center space-x-1">
<p>{(targetNotification?.data as any)?.additional?.name}</p>
<IconArrowRight size={12} strokeWidth={2} />
<p>{(targetNotification?.data as any)?.additional?.version_to}</p>
</div>
</li>
</ol>
</div>
<p>
This migration however will still be applied and finalized after{' '}
{dayjs(
new Date(targetNotification?.meta.actions_available?.[0]?.deadline ?? 0)
).format('DD MMM YYYY, HH:mma ZZ')}
, after which the changes can no longer be undone.
</p>
</div>
}
buttonLabel="Confirm"
buttonLoadingLabel="Confirm"
onSelectCancel={() => setProjectToRollbackMigration(undefined)}
onSelectConfirm={onConfirmProjectRollbackMigration}
/>
<ConfirmModal
danger
size="small"
visible={projectToFinalizeMigration !== undefined}
title={`Finalize schema migration for "${projectToFinalizeMigration?.name}"`}
// @ts-ignore
description={
<div className="text-scale-1200 space-y-4">
<Alert withIcon variant="warning" title="This action canot be undone" />
<div className="space-y-1">
<p>The following schema migration will be finalized for the project</p>
<ol className="list-disc pl-6">
<li>
<div className="flex items-center space-x-1">
<p>{(targetNotification?.data as any)?.additional?.name}</p>
<IconArrowRight size={12} strokeWidth={2} />
<p>{(targetNotification?.data as any)?.additional?.version_to}</p>
</div>
</li>
</ol>
</div>
</div>
}
buttonLabel="Confirm"
buttonLoadingLabel="Confirm"
onSelectCancel={() => setProjectToFinalizeMigration(undefined)}
onSelectConfirm={onConfirmProjectFinalizeMigration}
/>
</>
)
}
export default NotificationsPopover
| studio/components/layouts/ProjectLayout/LayoutHeader/NotificationsPopover/index.tsx | 1 | https://github.com/supabase/supabase/commit/2f78bf4c33a05fa9d4231be80fe1fff4bd6d9ada | [
0.0001791242539184168,
0.0001738962746458128,
0.0001664747396716848,
0.00017380289500579238,
0.0000033122535114671336
] |
{
"id": 2,
"code_window": [
"export async function getOrganizations(signal?: AbortSignal): Promise<Organization[]> {\n",
" const data = await get(`${API_URL}/organizations`, { signal })\n",
" if (data.error) throw data.error\n",
"\n",
" const sorted = (data as Organization[]).sort((a, b) => a.name.localeCompare(b.name))\n",
"\n",
" return sorted\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" if (!Array.isArray(data)) {\n",
" return []\n",
" }\n",
"\n"
],
"file_path": "studio/data/organizations/organizations-query.ts",
"type": "add",
"edit_start_line_idx": 11
} | import LayoutHeader from './LayoutHeader'
export default LayoutHeader
| studio/components/layouts/ProjectLayout/LayoutHeader/index.ts | 0 | https://github.com/supabase/supabase/commit/2f78bf4c33a05fa9d4231be80fe1fff4bd6d9ada | [
0.00017582235159352422,
0.00017582235159352422,
0.00017582235159352422,
0.00017582235159352422,
0
] |
{
"id": 2,
"code_window": [
"export async function getOrganizations(signal?: AbortSignal): Promise<Organization[]> {\n",
" const data = await get(`${API_URL}/organizations`, { signal })\n",
" if (data.error) throw data.error\n",
"\n",
" const sorted = (data as Organization[]).sort((a, b) => a.name.localeCompare(b.name))\n",
"\n",
" return sorted\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" if (!Array.isArray(data)) {\n",
" return []\n",
" }\n",
"\n"
],
"file_path": "studio/data/organizations/organizations-query.ts",
"type": "add",
"edit_start_line_idx": 11
} | html,
body {
--custom-font-family: -apple-system, BlinkMacSystemFont, Segoe UI, Roboto,
Oxygen, Ubuntu, Cantarell, Fira Sans, Droid Sans, Helvetica Neue, sans-serif;
--custom-bg-color: #101010;
--custom-panel-color: #222;
--custom-box-shadow: 0 2px 8px 0 rgba(0, 0, 0, 0.8);
--custom-color: #fff;
--custom-color-brand: #24b47e;
--custom-color-secondary: #666;
--custom-border: 1px solid #333;
--custom-border-radius: 5px;
--custom-spacing: 5px;
padding: 0;
margin: 0;
font-family: var(--custom-font-family);
background-color: var(--custom-bg-color);
}
* {
color: var(--custom-color);
font-family: var(--custom-font-family);
box-sizing: border-box;
}
html,
body,
#__next {
height: 100vh;
width: 100vw;
overflow-x: hidden;
}
/* Grid */
.container {
width: 90%;
margin-left: auto;
margin-right: auto;
}
.row {
position: relative;
width: 100%;
}
.row [class^="col"] {
float: left;
margin: 0.5rem 2%;
min-height: 0.125rem;
}
.col-1,
.col-2,
.col-3,
.col-4,
.col-5,
.col-6,
.col-7,
.col-8,
.col-9,
.col-10,
.col-11,
.col-12 {
width: 96%;
}
.col-1-sm {
width: 4.33%;
}
.col-2-sm {
width: 12.66%;
}
.col-3-sm {
width: 21%;
}
.col-4-sm {
width: 29.33%;
}
.col-5-sm {
width: 37.66%;
}
.col-6-sm {
width: 46%;
}
.col-7-sm {
width: 54.33%;
}
.col-8-sm {
width: 62.66%;
}
.col-9-sm {
width: 71%;
}
.col-10-sm {
width: 79.33%;
}
.col-11-sm {
width: 87.66%;
}
.col-12-sm {
width: 96%;
}
.row::after {
content: "";
display: table;
clear: both;
}
.hidden-sm {
display: none;
}
@media only screen and (min-width: 33.75em) {
/* 540px */
.container {
width: 80%;
}
}
@media only screen and (min-width: 45em) {
/* 720px */
.col-1 {
width: 4.33%;
}
.col-2 {
width: 12.66%;
}
.col-3 {
width: 21%;
}
.col-4 {
width: 29.33%;
}
.col-5 {
width: 37.66%;
}
.col-6 {
width: 46%;
}
.col-7 {
width: 54.33%;
}
.col-8 {
width: 62.66%;
}
.col-9 {
width: 71%;
}
.col-10 {
width: 79.33%;
}
.col-11 {
width: 87.66%;
}
.col-12 {
width: 96%;
}
.hidden-sm {
display: block;
}
}
@media only screen and (min-width: 60em) {
/* 960px */
.container {
width: 75%;
max-width: 60rem;
}
}
/* Forms */
label {
display: block;
margin: 5px 0;
color: var(--custom-color-secondary);
font-size: 0.8rem;
text-transform: uppercase;
}
input {
width: 100%;
border-radius: 5px;
border: var(--custom-border);
padding: 8px;
font-size: 0.9rem;
background-color: var(--custom-bg-color);
color: var(--custom-color);
}
input[disabled] {
color: var(--custom-color-secondary);
}
/* Utils */
.block {
display: block;
width: 100%;
}
.inline-block {
display: inline-block;
width: 100%;
}
.flex {
display: flex;
}
.flex.column {
flex-direction: column;
}
.flex.row {
flex-direction: row;
}
.flex.flex-1 {
flex: 1 1 0;
}
.flex-end {
justify-content: flex-end;
}
.flex-center {
justify-content: center;
}
.items-center {
align-items: center;
}
.text-sm {
font-size: 0.8rem;
font-weight: 300;
}
.text-right {
text-align: right;
}
.font-light {
font-weight: 300;
}
.opacity-half {
opacity: 50%;
}
/* Button */
button,
.button {
color: var(--custom-color);
border: var(--custom-border);
background-color: var(--custom-bg-color);
display: inline-block;
text-align: center;
border-radius: var(--custom-border-radius);
padding: 0.5rem 1rem;
cursor: pointer;
text-align: center;
font-size: 0.9rem;
text-transform: uppercase;
}
button.primary,
.button.primary {
background-color: var(--custom-color-brand);
border: 1px solid var(--custom-color-brand);
}
/* Widgets */
.card {
width: 100%;
display: block;
border: var(--custom-border);
border-radius: var(--custom-border-radius);
padding: var(--custom-spacing);
}
.avatar {
border-radius: var(--custom-border-radius);
overflow: hidden;
max-width: 100%;
}
.avatar.image {
object-fit: cover;
}
.avatar.no-image {
background-color: #333;
border: 1px solid rgb(200, 200, 200);
border-radius: 5px;
}
.footer {
position: absolute;
max-width: 100%;
bottom: 0;
left: 0;
right: 0;
display: flex;
flex-flow: row;
border-top: var(--custom-border);
background-color: var(--custom-bg-color);
}
.footer div {
padding: var(--custom-spacing);
display: flex;
align-items: center;
width: 100%;
}
.footer div > img {
height: 20px;
margin-left: 10px;
}
.footer > div:first-child {
display: none;
}
.footer > div:nth-child(2) {
justify-content: left;
}
@media only screen and (min-width: 60em) {
/* 960px */
.footer > div:first-child {
display: flex;
}
.footer > div:nth-child(2) {
justify-content: center;
}
}
@keyframes spin {
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
}
.mainHeader {
width: 100%;
font-size: 1.3rem;
margin-bottom: 20px;
}
.avatarPlaceholder {
border: var(--custom-border);
border-radius: var(--custom-border-radius);
width: 35px;
height: 35px;
background-color: rgba(255, 255, 255, 0.2);
display: flex;
align-items: center;
justify-content: center;
}
.form-widget {
display: flex;
flex-direction: column;
gap: 20px;
}
.form-widget > .button {
display: flex;
align-items: center;
justify-content: center;
border: none;
background-color: #444444;
text-transform: none !important;
transition: all 0.2s ease;
}
.form-widget .button:hover {
background-color: #2a2a2a;
}
.form-widget .button > .loader {
width: 17px;
animation: spin 1s linear infinite;
filter: invert(1);
}
| examples/user-management/angular-user-management/src/styles.css | 0 | https://github.com/supabase/supabase/commit/2f78bf4c33a05fa9d4231be80fe1fff4bd6d9ada | [
0.0001804144703783095,
0.00017707904044073075,
0.00017271065735258162,
0.00017751072300598025,
0.000002117577196258935
] |
{
"id": 2,
"code_window": [
"export async function getOrganizations(signal?: AbortSignal): Promise<Organization[]> {\n",
" const data = await get(`${API_URL}/organizations`, { signal })\n",
" if (data.error) throw data.error\n",
"\n",
" const sorted = (data as Organization[]).sort((a, b) => a.name.localeCompare(b.name))\n",
"\n",
" return sorted\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" if (!Array.isArray(data)) {\n",
" return []\n",
" }\n",
"\n"
],
"file_path": "studio/data/organizations/organizations-query.ts",
"type": "add",
"edit_start_line_idx": 11
} | # Miscellaneous
*.class
*.log
*.pyc
*.swp
.DS_Store
.atom/
.buildlog/
.history
.svn/
# IntelliJ related
*.iml
*.ipr
*.iws
.idea/
# The .vscode folder contains launch configuration and tasks you configure in
# VS Code which you may wish to be included in version control, so this line
# is commented out by default.
#.vscode/
# Flutter/Dart/Pub related
**/doc/api/
**/ios/Flutter/.last_build_id
.dart_tool/
.flutter-plugins
.flutter-plugins-dependencies
.packages
.pub-cache/
.pub/
/build/
pubspec.lock
# Web related
lib/generated_plugin_registrant.dart
# Symbolication related
app.*.symbols
# Obfuscation related
app.*.map.json
# Android Studio will place build artifacts here
/android/app/debug
/android/app/profile
/android/app/release
| examples/user-management/flutter-user-management/.gitignore | 0 | https://github.com/supabase/supabase/commit/2f78bf4c33a05fa9d4231be80fe1fff4bd6d9ada | [
0.00017587734328117222,
0.00017361219215672463,
0.00017105731240008026,
0.00017432362074032426,
0.0000020151733224338386
] |
{
"id": 3,
"code_window": [
" action: string,\n",
" resource: string,\n",
" data?: object,\n",
" organizationId?: number\n",
") {\n",
" return (permissions ?? [])\n",
" .filter(\n",
" (permission) =>\n",
" permission.organization_id === organizationId &&\n",
" permission.actions.some((act) => (action ? action.match(toRegexpString(act)) : null)) &&\n",
" permission.resources.some((res) => resource.match(toRegexpString(res)))\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" if (!permissions || !Array.isArray(permissions)) {\n",
" return false\n",
" }\n",
"\n",
" return permissions\n"
],
"file_path": "studio/hooks/misc/useCheckPermissions.ts",
"type": "replace",
"edit_start_line_idx": 17
} | import * as Tooltip from '@radix-ui/react-tooltip'
import {
ActionType,
Notification,
NotificationStatus,
} from '@supabase/shared-types/out/notifications'
import { useQueryClient } from '@tanstack/react-query'
import dayjs from 'dayjs'
import { useRouter } from 'next/router'
import { Fragment, useState } from 'react'
import ConfirmModal from 'components/ui/Dialogs/ConfirmDialog'
import { useNotificationsQuery } from 'data/notifications/notifications-query'
import { getProjectDetail } from 'data/projects/project-detail-query'
import { invalidateProjectsQuery, setProjectPostgrestStatus } from 'data/projects/projects-query'
import { useStore } from 'hooks'
import { delete_, patch, post } from 'lib/common/fetch'
import { API_URL } from 'lib/constants'
import { Project } from 'types'
import { Alert, Button, IconArrowRight, IconBell, Popover } from 'ui'
import NotificationRow from './NotificationRow'
const NotificationsPopover = () => {
const queryClient = useQueryClient()
const router = useRouter()
const { meta, ui } = useStore()
const { data: notifications, refetch } = useNotificationsQuery()
const [projectToRestart, setProjectToRestart] = useState<Project>()
const [projectToApplyMigration, setProjectToApplyMigration] = useState<Project>()
const [projectToRollbackMigration, setProjectToRollbackMigration] = useState<Project>()
const [projectToFinalizeMigration, setProjectToFinalizeMigration] = useState<Project>()
const [targetNotification, setTargetNotification] = useState<Notification>()
if (!notifications) return <></>
const hasNewNotifications = notifications?.some(
(notification) => notification.notification_status === NotificationStatus.New
)
const onOpenChange = async (open: boolean) => {
// TODO(alaister): move this to a mutation
if (!open) {
// Mark notifications as seen
const notificationIds = notifications
.filter((notification) => notification.notification_status === NotificationStatus.New)
.map((notification) => notification.id)
if (notificationIds.length > 0) {
const { error } = await patch(`${API_URL}/notifications`, { ids: notificationIds })
if (error) console.error('Failed to update notifications', error)
refetch()
}
}
}
const onConfirmProjectRestart = async () => {
if (!projectToRestart || !targetNotification) return
const { id } = targetNotification
const { ref, region } = projectToRestart
const serviceNamesByActionName: Record<string, string> = {
[ActionType.PgBouncerRestart]: 'pgbouncer',
[ActionType.SchedulePostgresRestart]: 'postgresql',
[ActionType.MigratePostgresSchema]: 'postgresql',
}
const services: string[] = targetNotification.meta.actions_available
.map((action) => action.action_type)
.filter((actionName) => Object.keys(serviceNamesByActionName).indexOf(actionName) !== -1)
.map((actionName) => serviceNamesByActionName[actionName])
const { error } = await post(`${API_URL}/projects/${ref}/restart-services`, {
restartRequest: {
region,
source_notification_id: id,
services: services,
},
})
if (error) {
ui.setNotification({
category: 'error',
message: `Failed to restart project: ${error.message}`,
error,
})
} else {
setProjectPostgrestStatus(queryClient, ref, 'OFFLINE')
ui.setNotification({ category: 'success', message: `Restarting services` })
router.push(`/project/${ref}`)
}
setProjectToRestart(undefined)
setTargetNotification(undefined)
}
// [Joshen/Qiao] These are all very specific to the upcoming security patch
// https://github.com/supabase/supabase/discussions/9314
// We probably need to revisit this again when we're planning to push out the next wave of
// notifications. Ideally, we should allow these to be more flexible and configurable
// Perhaps the URLs could come from the notification themselves if the actions
// require an external API call, then we just need one method instead of individual ones like this
const onConfirmProjectApplyMigration = async () => {
if (!projectToApplyMigration) return
const res = await post(`${API_URL}/database/${projectToApplyMigration.ref}/owner-reassign`, {})
if (!res.error) {
const project = await getProjectDetail({ ref: projectToApplyMigration.ref })
if (project) {
meta.setProjectDetails(project)
}
ui.setNotification({
category: 'success',
message: `Successfully applied migration for project "${projectToApplyMigration.name}"`,
})
} else {
ui.setNotification({
error: res.error,
category: 'error',
message: `Failed to apply migration: ${res.error.message}`,
})
}
setProjectToApplyMigration(undefined)
}
const onConfirmProjectRollbackMigration = async () => {
if (!projectToRollbackMigration) return
const res = await delete_(
`${API_URL}/database/${projectToRollbackMigration.ref}/owner-reassign`,
{}
)
if (!res.error) {
const project = await getProjectDetail({ ref: projectToRollbackMigration.ref })
if (project) {
meta.setProjectDetails(project)
}
ui.setNotification({
category: 'success',
message: `Successfully rolled back migration for project "${projectToRollbackMigration.name}"`,
})
} else {
ui.setNotification({
error: res.error,
category: 'error',
message: `Failed to roll back migration: ${res.error.message}`,
})
}
setProjectToRollbackMigration(undefined)
}
const onConfirmProjectFinalizeMigration = async () => {
if (!projectToFinalizeMigration) return
const res = await patch(
`${API_URL}/database/${projectToFinalizeMigration.ref}/owner-reassign`,
{}
)
if (!res.error) {
const project = await getProjectDetail({ ref: projectToFinalizeMigration.ref })
if (project) {
meta.setProjectDetails(project)
}
ui.setNotification({
category: 'success',
message: `Successfully finalized migration for project "${projectToFinalizeMigration.name}"`,
})
} else {
ui.setNotification({
error: res.error,
category: 'error',
message: `Failed to finalize migration: ${res.error.message}`,
})
}
setProjectToFinalizeMigration(undefined)
}
return (
<>
<Popover
size="content"
align="end"
side="bottom"
sideOffset={8}
onOpenChange={onOpenChange}
overlay={
<div className="w-[400px] lg:w-[700px]">
<div className="flex items-center justify-between border-b border-gray-500 bg-gray-400 px-4 py-2">
<p className="text-sm">Notifications</p>
{/* Area for improvement: Paginate notifications and show in a side panel */}
{/* <p className="text-scale-1000 hover:text-scale-1200 cursor-pointer text-sm transition">
See all{' '}
{notifications.length > MAX_NOTIFICATIONS_TO_SHOW && `(${notifications.length})`}
</p> */}
</div>
<div className="max-h-[380px] overflow-y-auto py-2">
{notifications.length === 0 ? (
<div className="py-2 px-4">
<p className="text-sm text-scale-1000">No notifications available</p>
</div>
) : (
<>
{notifications.map((notification, i: number) => (
<Fragment key={notification.id}>
<NotificationRow
notification={notification}
onSelectRestartProject={(project, notification) => {
setProjectToRestart(project)
setTargetNotification(notification)
}}
onSelectApplyMigration={(project, notification) => {
setProjectToApplyMigration(project)
setTargetNotification(notification)
}}
onSelectRollbackMigration={(project, notification) => {
setProjectToRollbackMigration(project)
setTargetNotification(notification)
}}
onSelectFinalizeMigration={(project, notification) => {
setProjectToFinalizeMigration(project)
setTargetNotification(notification)
}}
/>
{i !== notifications.length - 1 && <Popover.Separator />}
</Fragment>
))}
</>
)}
</div>
</div>
}
>
<Tooltip.Root delayDuration={0}>
<Tooltip.Trigger asChild>
<div className="relative flex">
<Button
asChild
id="notification-button"
type="default"
icon={<IconBell size={16} strokeWidth={1.5} className="text-scale-1200" />}
>
<span></span>
</Button>
{hasNewNotifications && (
<div className="absolute -top-1 -right-1 z-50 flex h-3 w-3 items-center justify-center">
<div className="h-full w-full animate-ping rounded-full bg-green-800 opacity-60"></div>
<div className="z-60 absolute top-0 right-0 h-full w-full rounded-full bg-green-900 opacity-80"></div>
</div>
)}
</div>
</Tooltip.Trigger>
<Tooltip.Portal>
<Tooltip.Content side="bottom">
<Tooltip.Arrow className="radix-tooltip-arrow" />
<div
className={[
'rounded bg-scale-100 py-1 px-2 leading-none shadow',
'border border-scale-200 flex items-center space-x-1',
].join(' ')}
>
<span className="text-xs text-scale-1200">Notifications</span>
</div>
</Tooltip.Content>
</Tooltip.Portal>
</Tooltip.Root>
</Popover>
<ConfirmModal
danger
visible={projectToRestart !== undefined}
title={`Restart project "${projectToRestart?.name}"`}
description={`Are you sure you want to restart the project? There will be a few minutes of downtime.`}
buttonLabel="Restart"
buttonLoadingLabel="Restarting"
onSelectCancel={() => setProjectToRestart(undefined)}
onSelectConfirm={onConfirmProjectRestart}
/>
<ConfirmModal
size="large"
visible={projectToApplyMigration !== undefined}
title={`Apply schema migration for "${projectToApplyMigration?.name}"`}
// @ts-ignore
description={
<div className="text-scale-1200 space-y-2">
<div className="space-y-1">
<p>The following schema migration will be applied to the project</p>
<ol className="list-disc pl-6">
<li>
<div className="flex items-center space-x-1">
<p>{(targetNotification?.data as any)?.additional?.name}</p>
<IconArrowRight size={12} strokeWidth={2} />
<p>{(targetNotification?.data as any)?.additional?.version_to}</p>
</div>
</li>
</ol>
</div>
<p>
This change can be rolled back anytime up till{' '}
{dayjs(
new Date(targetNotification?.meta.actions_available?.[0]?.deadline ?? 0)
).format('DD MMM YYYY, HH:mma ZZ')}
, after which the changes will be finalized and can no longer be undone.
</p>
</div>
}
buttonLabel="Confirm"
buttonLoadingLabel="Confirm"
onSelectCancel={() => setProjectToApplyMigration(undefined)}
onSelectConfirm={onConfirmProjectApplyMigration}
/>
<ConfirmModal
size="medium"
visible={projectToRollbackMigration !== undefined}
title={`Rollback schema migration for "${projectToRollbackMigration?.name}"`}
// @ts-ignore
description={
<div className="text-scale-1200 space-y-2">
<div className="space-y-1">
<p>The following schema migration will be rolled back for the project</p>
<ol className="list-disc pl-6">
<li>
<div className="flex items-center space-x-1">
<p>{(targetNotification?.data as any)?.additional?.name}</p>
<IconArrowRight size={12} strokeWidth={2} />
<p>{(targetNotification?.data as any)?.additional?.version_to}</p>
</div>
</li>
</ol>
</div>
<p>
This migration however will still be applied and finalized after{' '}
{dayjs(
new Date(targetNotification?.meta.actions_available?.[0]?.deadline ?? 0)
).format('DD MMM YYYY, HH:mma ZZ')}
, after which the changes can no longer be undone.
</p>
</div>
}
buttonLabel="Confirm"
buttonLoadingLabel="Confirm"
onSelectCancel={() => setProjectToRollbackMigration(undefined)}
onSelectConfirm={onConfirmProjectRollbackMigration}
/>
<ConfirmModal
danger
size="small"
visible={projectToFinalizeMigration !== undefined}
title={`Finalize schema migration for "${projectToFinalizeMigration?.name}"`}
// @ts-ignore
description={
<div className="text-scale-1200 space-y-4">
<Alert withIcon variant="warning" title="This action canot be undone" />
<div className="space-y-1">
<p>The following schema migration will be finalized for the project</p>
<ol className="list-disc pl-6">
<li>
<div className="flex items-center space-x-1">
<p>{(targetNotification?.data as any)?.additional?.name}</p>
<IconArrowRight size={12} strokeWidth={2} />
<p>{(targetNotification?.data as any)?.additional?.version_to}</p>
</div>
</li>
</ol>
</div>
</div>
}
buttonLabel="Confirm"
buttonLoadingLabel="Confirm"
onSelectCancel={() => setProjectToFinalizeMigration(undefined)}
onSelectConfirm={onConfirmProjectFinalizeMigration}
/>
</>
)
}
export default NotificationsPopover
| studio/components/layouts/ProjectLayout/LayoutHeader/NotificationsPopover/index.tsx | 1 | https://github.com/supabase/supabase/commit/2f78bf4c33a05fa9d4231be80fe1fff4bd6d9ada | [
0.0029713616240769625,
0.00029259518487378955,
0.00016442326887045056,
0.00017024738190229982,
0.000519990804605186
] |
{
"id": 3,
"code_window": [
" action: string,\n",
" resource: string,\n",
" data?: object,\n",
" organizationId?: number\n",
") {\n",
" return (permissions ?? [])\n",
" .filter(\n",
" (permission) =>\n",
" permission.organization_id === organizationId &&\n",
" permission.actions.some((act) => (action ? action.match(toRegexpString(act)) : null)) &&\n",
" permission.resources.some((res) => resource.match(toRegexpString(res)))\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" if (!permissions || !Array.isArray(permissions)) {\n",
" return false\n",
" }\n",
"\n",
" return permissions\n"
],
"file_path": "studio/hooks/misc/useCheckPermissions.ts",
"type": "replace",
"edit_start_line_idx": 17
} | ---
title: 'Mobbin uses Supabase to authenticate 200,000 users'
description: Learn how Mobbin migrated 200,000 users from Firebase for a better authentication experience.
author: rory_wilding
author_url: https://github.com/roryw10
author_image_url: https://github.com/roryw10.png
authorURL: https://github.com/roryw10
image: mobbin/og-mobbin-supabase.jpg
thumb: mobbin/cover-mobbin-supabase.jpg
tags:
- auth
date: '2021-07-28'
toc_depth: 2
---
Learn how Mobbin migrated 200,000 users from Firebase for a better authentication experience.
Mobbin helps over 200,000 creators globally search and view the latest design patterns from well-known apps.
Their platform allows creators to search screenshots of mobile apps to inspire product development.
Creators use Mobbin to combine inspiration and develop new experiences.
## From Idea to 30,000 users in one Product Hunt launch
The initial concept for Mobbin was just a Dropbox full of screenshots. After sharing with their early users,
the team tried organizing them into folders but this quickly became unscalable. Clear interest from users encouraged them to build a full website. They used Firebase for the backend and launched on
[Product Hunt](https://www.producthunt.com/posts/mobbin-1).
Mobbin went viral, and within the first week they had 30,000 users. In just over two years, they have grown to over 200,000
registered users through word of mouth. Their curation continues to attract designers and creators globally.

## Scaling issues put Mobbin growth at risk
Firebase helped the team launch quickly, but at scale, they found Firebase lacked the functionality required for a high-quality user experience.
The first problem was duplicate user logins. Firebase Authentication doesn't automatically merge users with the same email address.
For example, users cannot log in with Google and Facebook if they share the same email address.
Users struggled to upgrade to a paid account because they couldn't remember which authentication provider they signed up with.
Next, they had issues with data integrity. While Firebase has 99.95% uptime, application code can (and does) fail.
Mobbin didn't want to implement idempotence for every mutative Firebase Function. Between a failed Function execution and a retry,
a document state might change without strict validation. The team could never be confident their data had the level of integrity they required.
Finally, the team grew concerned with their increasing Firebase bill. Because of the document-based data structure,
their API requests required several round trips. At one point, they were making 5 million API requests per month.
These round trips made their website slow and led to a notable time investment hacking together a fix.

## Migrating to Supabase
Mobbin's initial product gave them a comprehensive understanding of customer requirements. For their second version,
they needed a better authentication experience, fairer pricing, and a relational database to deliver a quality
application sustainable for their business model.
The team found Supabase and realized it covered all the bases. Not only that, their team had experience with the
tools open source tools that Supabase is built with.
Auth, built using [GoTrue](https://github.com/supabase/gotrue), instantly solved their users' login issues.
Under the hood, Supabase is just Postgres, and Jian Jie (co-founder and CTO of Mobbin) knows this is one of the best battle-tested
open source relational databases.
They decided that moving to Supabase was a no-brainer. The process itself was smooth - the real challenge was validating their
data integrity due to historical failures on their serverless functions.
Mobbin is now successfully running on top of Supabase, with superior performance compared to their old Firebase setup.
Because Supabase does not charge based on API requests, Mobbin significantly reduced their monthly spending without maintaining a custom backend.
<Quote img="jian-mobbin.jpg" caption="Jian Jie Liau, Co-founder and CTO at Mobbin.">
<p>Migrating to Supabase meant that we could instantly fix our Auth problems and save money.</p>
<p>
Just being on Supabase alone gives us confidence we can deliver on whatever users need in the
future.
</p>
<p>
The cool thing is now we know under the hood it's just Postgres, it really does feel like
anything is possible for the future of our product
</p>
</Quote>
## Supabase saves Mobbin time and money
Migrating to Supabase helped the team at Mobbin instantly improve the end-user experience and save costs.
They now add new features with confidence, and they continue to help creators all over the globe find inspiration for their next project.
You can [check out Mobbin on their website](https://mobbin.design/browse/ios/apps).
Sign up to Supabase's free plan and set up a scalable backend in less than 2 minutes.
| apps/www/_blog/2021-07-28-mobbin-supabase-200000-users.mdx | 0 | https://github.com/supabase/supabase/commit/2f78bf4c33a05fa9d4231be80fe1fff4bd6d9ada | [
0.00017424052930437028,
0.00017038127407431602,
0.00016613442858215421,
0.00017042775289155543,
0.000002376181100771646
] |
{
"id": 3,
"code_window": [
" action: string,\n",
" resource: string,\n",
" data?: object,\n",
" organizationId?: number\n",
") {\n",
" return (permissions ?? [])\n",
" .filter(\n",
" (permission) =>\n",
" permission.organization_id === organizationId &&\n",
" permission.actions.some((act) => (action ? action.match(toRegexpString(act)) : null)) &&\n",
" permission.resources.some((res) => resource.match(toRegexpString(res)))\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" if (!permissions || !Array.isArray(permissions)) {\n",
" return false\n",
" }\n",
"\n",
" return permissions\n"
],
"file_path": "studio/hooks/misc/useCheckPermissions.ts",
"type": "replace",
"edit_start_line_idx": 17
} | ---
id: introduction
title: Introduction
hideTitle: true
---
<div className="flex items-start gap-6 not-prose" id="introduction">
<img src="/docs/img/icons/menu/reference-realtime.svg" className="w-8 h-8 rounded" />
<div className="flex flex-col gap-2">
<h1 className="text-3xl text-scale-1200 m-0">Self-Hosting Realtime</h1>
</div>
</div>
<RefSubLayout.EducationRow>
<RefSubLayout.Details>
Supabase Realtime is a server built with Elixir using the [Phoenix Framework](https://www.phoenixframework.org) that allows you to listen to changes in your PostgreSQL database via logical replication and then broadcast those changes via WebSockets.
There are two versions of this server: `Realtime` and `Realtime RLS`.
`Realtime` server works by:
1. Listening to PostgreSQL's replication functionality (using PostgreSQL's logical decoding)
2. Converting the byte stream into JSON
3. Broadcasting to all connected clients over WebSockets
`Realtime RLS` server works by:
1. Polling PostgreSQL's replication functionality (using PostgreSQL's logical decoding and [wal2json](https://github.com/eulerto/wal2json) output plugin)
2. Passing database changes to a [Write Ahead Log Realtime Unified Security (WALRUS)](https://github.com/supabase/walrus) PostgresSQL function and receiving a list of authorized subscribers depending on Row Level Security (RLS) policies
3. Converting the changes into JSON
4. Broadcasting to authorized subscribers over WebSockets
## Why not just use PostgreSQL's `NOTIFY`?
A few reasons:
1. You don't have to set up triggers on every table.
2. `NOTIFY` has a payload limit of 8000 bytes and will fail for anything larger. The usual solution is to send an ID and then fetch the record, but that's heavy on the database.
3. `Realtime` server consumes two connections to the database, then you can connect many clients to this server. Easier on your database, and to scale up you just add additional `Realtime` servers.
## Benefits
1. The beauty of listening to the replication functionality is that you can make changes to your database from anywhere - your API, directly in the DB, via a console, etc. - and you will still receive the changes via WebSockets.
2. Decoupling. For example, if you want to send a new slack message every time someone makes a new purchase you might build that functionality directly into your API. This allows you to decouple your async functionality from your API.
3. This is built with Phoenix, an [extremely scalable Elixir framework](https://www.phoenixframework.org/blog/the-road-to-2-million-websocket-connections).
## Does this server guarantee delivery of every data change?
Not yet! Due to the following limitations:
1. Postgres database runs out of disk space due to Write-Ahead Logging (WAL) buildup, which can crash the database and prevent Realtime server from receiving and broadcasting changes. This can be mitigated in the Realtime RLS version of this server by setting the Postgres config `max_slot_wal_keep_size` to a reasonable size.
2. Realtime server can crash due to a larger replication lag than available memory, forcing the creation of a new replication slot and resetting replication to read from the latest WAL data.
3. When Realtime server falls too far behind for any reason, for example disconnecting from database as WAL continues to build up, then database can delete WAL segments the server still needs to read from, for example after reconnecting.
</RefSubLayout.Details>
<RefSubLayout.Examples>
### Client libraries
- [JavaScript](https://github.com/supabase/realtime-js)
- [Dart](https://github.com/supabase/realtime-dart)
### Additional links
- [Source code](https://github.com/supabase/realtime)
- [Known bugs and issues](https://github.com/supabase/realtime/issues)
- [Realtime guides](/docs/guides/realtime)
</RefSubLayout.Examples>
</RefSubLayout.EducationRow>
| apps/docs/docs/ref/self-hosting-realtime/introduction.mdx | 0 | https://github.com/supabase/supabase/commit/2f78bf4c33a05fa9d4231be80fe1fff4bd6d9ada | [
0.00017181088333018124,
0.00016934513405431062,
0.00016513282025698572,
0.0001699647691566497,
0.000002188759708587895
] |
{
"id": 3,
"code_window": [
" action: string,\n",
" resource: string,\n",
" data?: object,\n",
" organizationId?: number\n",
") {\n",
" return (permissions ?? [])\n",
" .filter(\n",
" (permission) =>\n",
" permission.organization_id === organizationId &&\n",
" permission.actions.some((act) => (action ? action.match(toRegexpString(act)) : null)) &&\n",
" permission.resources.some((res) => resource.match(toRegexpString(res)))\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" if (!permissions || !Array.isArray(permissions)) {\n",
" return false\n",
" }\n",
"\n",
" return permissions\n"
],
"file_path": "studio/hooks/misc/useCheckPermissions.ts",
"type": "replace",
"edit_start_line_idx": 17
} | <svg width="16" height="17" viewBox="0 0 16 17" fill="none" xmlns="http://www.w3.org/2000/svg">
<rect x="2.08203" y="2.44824" width="5" height="5" stroke="#4CC38A" stroke-miterlimit="10" stroke-linejoin="bevel"/>
<rect x="8.91797" y="9.19775" width="5" height="5" stroke="#4CC38A" stroke-miterlimit="10" stroke-linejoin="bevel"/>
<path d="M11.418 2.44824V7.44824" stroke="#4CC38A" stroke-miterlimit="10" stroke-linejoin="bevel"/>
<path d="M13.918 4.94849L8.91797 4.94849" stroke="#4CC38A" stroke-miterlimit="10" stroke-linejoin="bevel"/>
<circle cx="4.58154" cy="11.6978" r="2.68506" fill="#133929" stroke="#4CC38A" stroke-miterlimit="10" stroke-linejoin="bevel"/>
</svg>
| apps/docs/public/img/icons/menu/integrations.svg | 0 | https://github.com/supabase/supabase/commit/2f78bf4c33a05fa9d4231be80fe1fff4bd6d9ada | [
0.00017291217227466404,
0.00017291217227466404,
0.00017291217227466404,
0.00017291217227466404,
0
] |
{
"id": 0,
"code_window": [
"\t\tconst commonlyUsed = resolveSettingsTree(commonlyUsedData, dividedGroups.core);\n",
"\t\tresolvedSettingsRoot.children.unshift(commonlyUsed);\n",
"\n",
"\t\tresolvedSettingsRoot.children.push(resolveExtensionsSettings(dividedGroups.extension || []));\n",
"\n",
"\t\tif (this.settingsTreeModel) {\n",
"\t\t\tthis.settingsTreeModel.update(resolvedSettingsRoot);\n",
"\t\t} else {\n",
"\t\t\tthis.settingsTreeModel = this.instantiationService.createInstance(SettingsTreeModel, this.viewState, resolvedSettingsRoot);\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tif (this.searchResultModel) {\n",
"\t\t\tthis.searchResultModel.updateChildren();\n",
"\t\t}\n",
"\n"
],
"file_path": "src/vs/workbench/parts/preferences/browser/settingsEditor2.ts",
"type": "add",
"edit_start_line_idx": 567
} | /*---------------------------------------------------------------------------------------------
* 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 { StandardKeyboardEvent } from 'vs/base/browser/keyboardEvent';
import { IMouseEvent } from 'vs/base/browser/mouseEvent';
import { Button } from 'vs/base/browser/ui/button/button';
import { Checkbox } from 'vs/base/browser/ui/checkbox/checkbox';
import { InputBox } from 'vs/base/browser/ui/inputbox/inputBox';
import { SelectBox } from 'vs/base/browser/ui/selectBox/selectBox';
import * as arrays from 'vs/base/common/arrays';
import { Color } from 'vs/base/common/color';
import { Emitter, Event } from 'vs/base/common/event';
import { KeyCode } from 'vs/base/common/keyCodes';
import { dispose, IDisposable } from 'vs/base/common/lifecycle';
import * as objects from 'vs/base/common/objects';
import { escapeRegExpCharacters } from 'vs/base/common/strings';
import URI from 'vs/base/common/uri';
import { TPromise } from 'vs/base/common/winjs.base';
import { IAccessibilityProvider, IDataSource, IFilter, IRenderer, ITree } from 'vs/base/parts/tree/browser/tree';
import { localize } from 'vs/nls';
import { ConfigurationTarget, IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { IContextViewService } from 'vs/platform/contextview/browser/contextView';
import { WorkbenchTree, WorkbenchTreeController } from 'vs/platform/list/browser/listService';
import { registerColor, selectBackground, selectBorder } from 'vs/platform/theme/common/colorRegistry';
import { attachButtonStyler, attachInputBoxStyler, attachSelectBoxStyler } from 'vs/platform/theme/common/styler';
import { ICssStyleCollector, ITheme, IThemeService, registerThemingParticipant } from 'vs/platform/theme/common/themeService';
import { SettingsTarget } from 'vs/workbench/parts/preferences/browser/preferencesWidgets';
import { ITOCEntry } from 'vs/workbench/parts/preferences/browser/settingsLayout';
import { ISearchResult, ISetting, ISettingsGroup } from 'vs/workbench/services/preferences/common/preferences';
const $ = DOM.$;
export const modifiedItemForeground = registerColor('settings.modifiedItemForeground', {
light: '#019001',
dark: '#73C991',
hc: '#73C991'
}, localize('modifiedItemForeground', "(For settings editor preview) The foreground color for a modified setting."));
registerThemingParticipant((theme: ITheme, collector: ICssStyleCollector) => {
const modifiedItemForegroundColor = theme.getColor(modifiedItemForeground);
if (modifiedItemForegroundColor) {
collector.addRule(`.settings-editor > .settings-body > .settings-tree-container .setting-item.is-configured .setting-item-is-configured-label { color: ${modifiedItemForegroundColor}; }`);
}
});
registerThemingParticipant((theme: ITheme, collector: ICssStyleCollector) => {
// TODO@roblou Hacks! Make checkbox background themeable
const selectBackgroundColor = theme.getColor(selectBackground);
if (selectBackgroundColor) {
collector.addRule(`.settings-editor > .settings-body > .settings-tree-container .setting-item-bool .setting-value-checkbox { background-color: ${selectBackgroundColor} !important; }`);
}
// TODO@roblou Hacks! Use proper inputbox theming instead of !important
const selectBorderColor = theme.getColor(selectBorder);
if (selectBorderColor) {
collector.addRule(`.settings-editor > .settings-body > .settings-tree-container .setting-item-bool .setting-value-checkbox { border-color: ${selectBorderColor} !important; }`);
collector.addRule(`.settings-editor > .settings-body > .settings-tree-container .setting-item .setting-item-control > .monaco-inputbox { border: solid 1px ${selectBorderColor} !important; }`);
}
});
export abstract class SettingsTreeElement {
id: string;
parent: any; // SearchResultModel or group element... TODO search should be more similar to the normal case
}
export class SettingsTreeGroupElement extends SettingsTreeElement {
children: (SettingsTreeGroupElement | SettingsTreeSettingElement)[];
label: string;
level: number;
}
export class SettingsTreeSettingElement extends SettingsTreeElement {
setting: ISetting;
isExpanded: boolean;
displayCategory: string;
displayLabel: string;
value: any;
isConfigured: boolean;
overriddenScopeList: string[];
description: string;
valueType?: string | string[];
enum?: string[];
}
export interface ITOCEntry {
id: string;
label: string;
children?: ITOCEntry[];
settings?: (string | ISetting)[];
}
export class SettingsTreeModel {
private _root: SettingsTreeGroupElement;
private _treeElementsById = new Map<string, SettingsTreeElement>();
constructor(
private _viewState: ISettingsEditorViewState,
private _tocRoot: ITOCEntry,
@IConfigurationService private _configurationService: IConfigurationService
) {
this.update(this._tocRoot);
}
get root(): SettingsTreeGroupElement {
return this._root;
}
update(newTocRoot = this._tocRoot): void {
const newRoot = this.createSettingsTreeGroupElement(newTocRoot);
if (this._root) {
this._root.children = newRoot.children;
} else {
this._root = newRoot;
}
}
getElementById(id: string): SettingsTreeElement {
return this._treeElementsById.get(id);
}
private createSettingsTreeGroupElement(tocEntry: ITOCEntry, parent?: SettingsTreeGroupElement): SettingsTreeGroupElement {
const element = new SettingsTreeGroupElement();
element.id = tocEntry.id;
element.label = tocEntry.label;
element.parent = parent;
element.level = this.getDepth(element);
if (tocEntry.children) {
element.children = tocEntry.children.map(child => this.createSettingsTreeGroupElement(child, element));
} else if (tocEntry.settings) {
element.children = tocEntry.settings.map(s => this.createSettingsTreeSettingElement(<ISetting>s, element));
}
this._treeElementsById.set(element.id, element);
return element;
}
private getDepth(element: SettingsTreeElement): number {
if (element.parent) {
return 1 + this.getDepth(element.parent);
} else {
return 0;
}
}
private createSettingsTreeSettingElement(setting: ISetting, parent: SettingsTreeGroupElement): SettingsTreeSettingElement {
const element = createSettingsTreeSettingElement(setting, parent, this._viewState.settingsTarget, this._configurationService);
this._treeElementsById.set(element.id, element);
return element;
}
}
function sanitizeId(id: string): string {
return id.replace(/[\.\/]/, '_');
}
function createSettingsTreeSettingElement(setting: ISetting, parent: any, settingsTarget: SettingsTarget, configurationService: IConfigurationService): SettingsTreeSettingElement {
const element = new SettingsTreeSettingElement();
element.id = sanitizeId(parent.id + '_' + setting.key);
element.parent = parent;
const { isConfigured, inspected, targetSelector } = inspectSetting(setting.key, settingsTarget, configurationService);
const displayValue = isConfigured ? inspected[targetSelector] : inspected.default;
const overriddenScopeList = [];
if (targetSelector === 'user' && typeof inspected.workspace !== 'undefined') {
overriddenScopeList.push(localize('workspace', "Workspace"));
}
if (targetSelector === 'workspace' && typeof inspected.user !== 'undefined') {
overriddenScopeList.push(localize('user', "User"));
}
const displayKeyFormat = settingKeyToDisplayFormat(setting.key, parent.id);
element.setting = setting;
element.displayLabel = displayKeyFormat.label;
element.displayCategory = displayKeyFormat.category;
element.isExpanded = false;
element.value = displayValue;
element.isConfigured = isConfigured;
element.overriddenScopeList = overriddenScopeList;
element.description = setting.description.join('\n');
element.enum = setting.enum;
element.valueType = setting.type;
return element;
}
function inspectSetting(key: string, target: SettingsTarget, configurationService: IConfigurationService): { isConfigured: boolean, inspected: any, targetSelector: string } {
const inspectOverrides = URI.isUri(target) ? { resource: target } : undefined;
const inspected = configurationService.inspect(key, inspectOverrides);
const targetSelector = target === ConfigurationTarget.USER ? 'user' :
target === ConfigurationTarget.WORKSPACE ? 'workspace' :
'workspaceFolder';
const isConfigured = typeof inspected[targetSelector] !== 'undefined';
return { isConfigured, inspected, targetSelector };
}
export function resolveSettingsTree(tocData: ITOCEntry, coreSettingsGroups: ISettingsGroup[]): ITOCEntry {
return _resolveSettingsTree(tocData, getFlatSettings(coreSettingsGroups));
}
export function resolveExtensionsSettings(groups: ISettingsGroup[]): ITOCEntry {
const settingsGroupToEntry = (group: ISettingsGroup) => {
const flatSettings = arrays.flatten(
group.sections.map(section => section.settings));
return {
id: group.id,
label: group.title,
settings: flatSettings
};
};
const extGroups = groups
.sort((a, b) => a.title.localeCompare(b.title))
.map(g => settingsGroupToEntry(g));
return {
id: 'extensions',
label: localize('extensions', "Extensions"),
children: extGroups
};
}
function _resolveSettingsTree(tocData: ITOCEntry, allSettings: Set<ISetting>): ITOCEntry {
if (tocData.settings) {
return <ITOCEntry>{
id: tocData.id,
label: tocData.label,
settings: arrays.flatten(tocData.settings.map(pattern => getMatchingSettings(allSettings, <string>pattern)))
};
} else if (tocData.children) {
return <ITOCEntry>{
id: tocData.id,
label: tocData.label,
children: tocData.children.map(child => _resolveSettingsTree(child, allSettings))
};
}
return null;
}
function getMatchingSettings(allSettings: Set<ISetting>, pattern: string): ISetting[] {
const result: ISetting[] = [];
allSettings.forEach(s => {
if (settingMatches(s, pattern)) {
result.push(s);
allSettings.delete(s);
}
});
return result.sort((a, b) => a.key.localeCompare(b.key));
}
function settingMatches(s: ISetting, pattern: string): boolean {
pattern = escapeRegExpCharacters(pattern)
.replace(/\\\*/g, '.*');
const regexp = new RegExp(`^${pattern}`, 'i');
return regexp.test(s.key);
}
function getFlatSettings(settingsGroups: ISettingsGroup[]) {
const result: Set<ISetting> = new Set();
for (let group of settingsGroups) {
for (let section of group.sections) {
for (let s of section.settings) {
result.add(s);
}
}
}
return result;
}
export class SettingsDataSource implements IDataSource {
getId(tree: ITree, element: SettingsTreeElement): string {
return element.id;
}
hasChildren(tree: ITree, element: SettingsTreeElement): boolean {
if (element instanceof SearchResultModel) {
return true;
}
if (element instanceof SettingsTreeGroupElement) {
return true;
}
return false;
}
getChildren(tree: ITree, element: SettingsTreeElement): TPromise<any, any> {
return TPromise.as(this._getChildren(element));
}
private _getChildren(element: SettingsTreeElement): SettingsTreeElement[] {
if (element instanceof SearchResultModel) {
return element.getChildren();
} else if (element instanceof SettingsTreeGroupElement) {
return element.children;
} else {
// No children...
return null;
}
}
getParent(tree: ITree, element: SettingsTreeElement): TPromise<any, any> {
return TPromise.wrap(element.parent);
}
shouldAutoexpand(): boolean {
return true;
}
}
export function settingKeyToDisplayFormat(key: string, groupId = ''): { category: string, label: string } {
let label = wordifyKey(key);
const lastDotIdx = label.lastIndexOf('.');
let category = '';
if (lastDotIdx >= 0) {
category = label.substr(0, lastDotIdx);
label = label.substr(lastDotIdx + 1);
}
groupId = wordifyKey(groupId.replace(/\//g, '.'));
category = trimCategoryForGroup(category, groupId);
return { category, label };
}
function wordifyKey(key: string): string {
return key
.replace(/\.([a-z])/g, (match, p1) => `.${p1.toUpperCase()}`)
.replace(/([a-z])([A-Z])/g, '$1 $2') // fooBar => foo Bar
.replace(/^[a-z]/g, match => match.toUpperCase()); // foo => Foo
}
function trimCategoryForGroup(category: string, groupId: string): string {
const doTrim = forward => {
const parts = groupId.split('.');
while (parts.length) {
const reg = new RegExp(`^${parts.join('\\.')}(\\.|$)`, 'i');
if (reg.test(category)) {
return category.replace(reg, '');
}
if (forward) {
parts.pop();
} else {
parts.shift();
}
}
return null;
};
let trimmed = doTrim(true);
if (trimmed === null) {
trimmed = doTrim(false);
}
if (trimmed === null) {
trimmed = category;
}
return trimmed;
}
export interface ISettingsEditorViewState {
settingsTarget: SettingsTarget;
showConfiguredOnly?: boolean;
filterToCategory?: SettingsTreeGroupElement;
}
interface IDisposableTemplate {
toDispose: IDisposable[];
}
interface ISettingItemTemplate extends IDisposableTemplate {
parent: HTMLElement;
containerElement: HTMLElement;
categoryElement: HTMLElement;
labelElement: HTMLElement;
descriptionElement: HTMLElement;
controlElement: HTMLElement;
isConfiguredElement: HTMLElement;
otherOverridesElement: HTMLElement;
}
interface ISettingBoolItemTemplate extends IDisposableTemplate {
parent: HTMLElement;
onChange?: (newState: boolean) => void;
containerElement: HTMLElement;
categoryElement: HTMLElement;
labelElement: HTMLElement;
descriptionElement: HTMLElement;
checkbox: Checkbox;
isConfiguredElement: HTMLElement;
otherOverridesElement: HTMLElement;
}
interface IGroupTitleTemplate extends IDisposableTemplate {
context?: SettingsTreeGroupElement;
parent: HTMLElement;
}
const SETTINGS_ELEMENT_TEMPLATE_ID = 'settings.entry.template';
const SETTINGS_BOOL_TEMPLATE_ID = 'settings.bool.template';
const SETTINGS_GROUP_ELEMENT_TEMPLATE_ID = 'settings.group.template';
export interface ISettingChangeEvent {
key: string;
value: any; // undefined => reset/unconfigure
}
export class SettingsRenderer implements IRenderer {
private static readonly SETTING_ROW_HEIGHT = 94;
private static readonly SETTING_BOOL_ROW_HEIGHT = 61;
private readonly _onDidChangeSetting: Emitter<ISettingChangeEvent> = new Emitter<ISettingChangeEvent>();
public readonly onDidChangeSetting: Event<ISettingChangeEvent> = this._onDidChangeSetting.event;
private readonly _onDidOpenSettings: Emitter<void> = new Emitter<void>();
public readonly onDidOpenSettings: Event<void> = this._onDidOpenSettings.event;
private measureContainer: HTMLElement;
constructor(
_measureContainer: HTMLElement,
@IThemeService private themeService: IThemeService,
@IContextViewService private contextViewService: IContextViewService
) {
this.measureContainer = DOM.append(_measureContainer, $('.setting-measure-container.monaco-tree-row'));
}
getHeight(tree: ITree, element: SettingsTreeElement): number {
if (element instanceof SettingsTreeGroupElement) {
return 40 + (7 * element.level);
}
if (element instanceof SettingsTreeSettingElement) {
const isSelected = this.elementIsSelected(tree, element);
if (isSelected) {
return this.measureSettingElementHeight(tree, element);
} else {
return this._getUnexpandedSettingHeight(element);
}
}
return 0;
}
_getUnexpandedSettingHeight(element: SettingsTreeSettingElement): number {
if (element.valueType === 'boolean') {
return SettingsRenderer.SETTING_BOOL_ROW_HEIGHT;
} else {
return SettingsRenderer.SETTING_ROW_HEIGHT;
}
}
private measureSettingElementHeight(tree: ITree, element: SettingsTreeSettingElement): number {
const measureHelper = DOM.append(this.measureContainer, $('.setting-measure-helper'));
const templateId = this.getTemplateId(tree, element);
const template = this.renderTemplate(tree, templateId, measureHelper);
this.renderElement(tree, element, templateId, template);
const height = this.measureContainer.offsetHeight;
this.measureContainer.removeChild(this.measureContainer.firstChild);
return Math.max(height, this._getUnexpandedSettingHeight(element));
}
getTemplateId(tree: ITree, element: SettingsTreeElement): string {
if (element instanceof SettingsTreeGroupElement) {
return SETTINGS_GROUP_ELEMENT_TEMPLATE_ID;
}
if (element instanceof SettingsTreeSettingElement) {
if (element.valueType === 'boolean') {
return SETTINGS_BOOL_TEMPLATE_ID;
}
return SETTINGS_ELEMENT_TEMPLATE_ID;
}
return '';
}
renderTemplate(tree: ITree, templateId: string, container: HTMLElement) {
if (templateId === SETTINGS_GROUP_ELEMENT_TEMPLATE_ID) {
return this.renderGroupTitleTemplate(container);
}
if (templateId === SETTINGS_ELEMENT_TEMPLATE_ID) {
return this.renderSettingTemplate(tree, container);
}
if (templateId === SETTINGS_BOOL_TEMPLATE_ID) {
return this.renderSettingBoolTemplate(tree, container);
}
return null;
}
private renderGroupTitleTemplate(container: HTMLElement): IGroupTitleTemplate {
DOM.addClass(container, 'group-title');
const toDispose = [];
const template: IGroupTitleTemplate = {
parent: container,
toDispose
};
return template;
}
private renderSettingTemplate(tree: ITree, container: HTMLElement): ISettingItemTemplate {
DOM.addClass(container, 'setting-item');
const titleElement = DOM.append(container, $('.setting-item-title'));
const categoryElement = DOM.append(titleElement, $('span.setting-item-category'));
const labelElement = DOM.append(titleElement, $('span.setting-item-label'));
const isConfiguredElement = DOM.append(titleElement, $('span.setting-item-is-configured-label'));
const otherOverridesElement = DOM.append(titleElement, $('span.setting-item-overrides'));
const descriptionElement = DOM.append(container, $('.setting-item-description'));
const valueElement = DOM.append(container, $('.setting-item-value'));
const controlElement = DOM.append(valueElement, $('div'));
const resetButtonElement = DOM.append(valueElement, $('.reset-button-container'));
const toDispose = [];
const template: ISettingItemTemplate = {
parent: container,
toDispose,
containerElement: container,
categoryElement,
labelElement,
descriptionElement,
controlElement,
isConfiguredElement,
otherOverridesElement
};
// Prevent clicks from being handled by list
toDispose.push(DOM.addDisposableListener(controlElement, 'mousedown', (e: IMouseEvent) => e.stopPropagation()));
toDispose.push(DOM.addDisposableListener(resetButtonElement, 'mousedown', (e: IMouseEvent) => e.stopPropagation()));
toDispose.push(DOM.addStandardDisposableListener(valueElement, 'keydown', (e: StandardKeyboardEvent) => {
if (e.keyCode === KeyCode.Escape) {
tree.domFocus();
e.browserEvent.stopPropagation();
}
}));
return template;
}
private renderSettingBoolTemplate(tree: ITree, container: HTMLElement): ISettingBoolItemTemplate {
DOM.addClass(container, 'setting-item');
DOM.addClass(container, 'setting-item-bool');
const titleElement = DOM.append(container, $('.setting-item-title'));
const categoryElement = DOM.append(titleElement, $('span.setting-item-category'));
const labelElement = DOM.append(titleElement, $('span.setting-item-label'));
const isConfiguredElement = DOM.append(titleElement, $('span.setting-item-is-configured-label'));
const otherOverridesElement = DOM.append(titleElement, $('span.setting-item-overrides'));
const descriptionAndValueElement = DOM.append(container, $('.setting-item-value-description'));
const controlElement = DOM.append(descriptionAndValueElement, $('.setting-item-bool-control'));
const descriptionElement = DOM.append(descriptionAndValueElement, $('.setting-item-description'));
const toDispose = [];
const checkbox = new Checkbox({ actionClassName: 'setting-value-checkbox', isChecked: true, title: '', inputActiveOptionBorder: null });
controlElement.appendChild(checkbox.domNode);
toDispose.push(checkbox);
toDispose.push(checkbox.onChange(() => {
if (template.onChange) {
template.onChange(checkbox.checked);
}
}));
const template: ISettingBoolItemTemplate = {
parent: container,
toDispose,
containerElement: container,
categoryElement,
labelElement,
checkbox,
descriptionElement,
isConfiguredElement,
otherOverridesElement
};
// Prevent clicks from being handled by list
toDispose.push(DOM.addDisposableListener(controlElement, 'mousedown', (e: IMouseEvent) => e.stopPropagation()));
toDispose.push(DOM.addStandardDisposableListener(controlElement, 'keydown', (e: StandardKeyboardEvent) => {
if (e.keyCode === KeyCode.Escape) {
tree.domFocus();
e.browserEvent.stopPropagation();
}
}));
return template;
}
renderElement(tree: ITree, element: SettingsTreeElement, templateId: string, template: any): void {
if (templateId === SETTINGS_ELEMENT_TEMPLATE_ID) {
return this.renderSettingElement(tree, <SettingsTreeSettingElement>element, template);
}
if (templateId === SETTINGS_BOOL_TEMPLATE_ID) {
return this.renderSettingElement(tree, <SettingsTreeSettingElement>element, template);
}
if (templateId === SETTINGS_GROUP_ELEMENT_TEMPLATE_ID) {
return this.renderGroupElement(<SettingsTreeGroupElement>element, template);
}
}
private renderGroupElement(element: SettingsTreeGroupElement, template: IGroupTitleTemplate): void {
template.parent.innerHTML = '';
const labelElement = DOM.append(template.parent, $('div.settings-group-title-label'));
labelElement.classList.add(`settings-group-level-${element.level}`);
labelElement.textContent = (<SettingsTreeGroupElement>element).label;
}
private elementIsSelected(tree: ITree, element: SettingsTreeElement): boolean {
const selection = tree.getSelection();
const selectedElement: SettingsTreeElement = selection && selection[0];
return selectedElement && selectedElement.id === element.id;
}
private renderSettingElement(tree: ITree, element: SettingsTreeSettingElement, template: ISettingItemTemplate | ISettingBoolItemTemplate): void {
const isSelected = !!this.elementIsSelected(tree, element);
const setting = element.setting;
DOM.toggleClass(template.parent, 'is-configured', element.isConfigured);
DOM.toggleClass(template.parent, 'is-expanded', isSelected);
template.containerElement.id = element.id.replace(/\./g, '_');
const titleTooltip = setting.key;
template.categoryElement.textContent = element.displayCategory && (element.displayCategory + ': ');
template.categoryElement.title = titleTooltip;
template.labelElement.textContent = element.displayLabel;
template.labelElement.title = titleTooltip;
template.descriptionElement.textContent = element.description;
this.renderValue(element, isSelected, <ISettingItemTemplate>template);
template.isConfiguredElement.textContent = element.isConfigured ? localize('configured', "Modified") : '';
if (element.overriddenScopeList.length) {
let otherOverridesLabel = element.isConfigured ?
localize('alsoConfiguredIn', "Also modified in") :
localize('configuredIn', "Modified in");
template.otherOverridesElement.textContent = `(${otherOverridesLabel}: ${element.overriddenScopeList.join(', ')})`;
}
}
private renderValue(element: SettingsTreeSettingElement, isSelected: boolean, template: ISettingItemTemplate | ISettingBoolItemTemplate): void {
const onChange = value => this._onDidChangeSetting.fire({ key: element.setting.key, value });
if (element.valueType === 'boolean') {
this.renderBool(element, isSelected, <ISettingBoolItemTemplate>template, onChange);
} else {
return this._renderValue(element, isSelected, <ISettingItemTemplate>template, onChange);
}
}
private _renderValue(element: SettingsTreeSettingElement, isSelected: boolean, template: ISettingItemTemplate, onChange: (value: any) => void): void {
const valueControlElement = template.controlElement;
valueControlElement.innerHTML = '';
valueControlElement.setAttribute('class', 'setting-item-control');
if (element.enum && (element.valueType === 'string' || !element.valueType)) {
valueControlElement.classList.add('setting-type-enum');
this.renderEnum(element, isSelected, template, valueControlElement, onChange);
} else if (element.valueType === 'string') {
valueControlElement.classList.add('setting-type-string');
this.renderText(element, isSelected, template, valueControlElement, onChange);
} else if (element.valueType === 'number' || element.valueType === 'integer') {
valueControlElement.classList.add('setting-type-number');
const parseFn = element.valueType === 'integer' ? parseInt : parseFloat;
this.renderText(element, isSelected, template, valueControlElement, value => onChange(parseFn(value)));
} else {
valueControlElement.classList.add('setting-type-complex');
this.renderEditInSettingsJson(element, isSelected, template, valueControlElement);
}
}
private renderBool(dataElement: SettingsTreeSettingElement, isSelected: boolean, template: ISettingBoolItemTemplate, onChange: (value: boolean) => void): void {
template.onChange = null;
template.checkbox.checked = dataElement.value;
template.onChange = onChange;
template.checkbox.domNode.tabIndex = isSelected ? 0 : -1;
}
private renderEnum(dataElement: SettingsTreeSettingElement, isSelected: boolean, template: ISettingItemTemplate, element: HTMLElement, onChange: (value: string) => void): void {
const idx = dataElement.enum.indexOf(dataElement.value);
const displayOptions = dataElement.enum.map(escapeInvisibleChars);
const selectBox = new SelectBox(displayOptions, idx, this.contextViewService);
template.toDispose.push(attachSelectBoxStyler(selectBox, this.themeService));
selectBox.render(element);
if (element.firstElementChild) {
element.firstElementChild.setAttribute('tabindex', isSelected ? '0' : '-1');
}
template.toDispose.push(
selectBox.onDidSelect(e => onChange(dataElement.enum[e.index])));
}
private renderText(dataElement: SettingsTreeSettingElement, isSelected: boolean, template: ISettingItemTemplate, element: HTMLElement, onChange: (value: string) => void): void {
const inputBox = new InputBox(element, this.contextViewService);
template.toDispose.push(attachInputBoxStyler(inputBox, this.themeService));
template.toDispose.push(inputBox);
inputBox.value = dataElement.value;
inputBox.inputElement.tabIndex = isSelected ? 0 : -1;
template.toDispose.push(
inputBox.onDidChange(e => onChange(e)));
}
private renderEditInSettingsJson(dataElement: SettingsTreeSettingElement, isSelected: boolean, template: ISettingItemTemplate, element: HTMLElement): void {
const openSettingsButton = new Button(element, { title: true, buttonBackground: null, buttonHoverBackground: null });
openSettingsButton.onDidClick(() => this._onDidOpenSettings.fire());
openSettingsButton.label = localize('editInSettingsJson', "Edit in settings.json");
openSettingsButton.element.classList.add('edit-in-settings-button');
openSettingsButton.element.tabIndex = isSelected ? 0 : -1;
template.toDispose.push(openSettingsButton);
template.toDispose.push(attachButtonStyler(openSettingsButton, this.themeService, {
buttonBackground: Color.transparent.toString(),
buttonHoverBackground: Color.transparent.toString(),
buttonForeground: 'foreground'
}));
}
disposeTemplate(tree: ITree, templateId: string, template: IDisposableTemplate): void {
dispose(template.toDispose);
}
}
function escapeInvisibleChars(enumValue: string): string {
return enumValue && enumValue
.replace(/\n/g, '\\n')
.replace(/\r/g, '\\r');
}
export class SettingsTreeFilter implements IFilter {
constructor(
private viewState: ISettingsEditorViewState,
@IConfigurationService private configurationService: IConfigurationService
) { }
isVisible(tree: ITree, element: SettingsTreeElement): boolean {
if (this.viewState.filterToCategory && element instanceof SettingsTreeSettingElement) {
if (!this.settingContainedInGroup(element.setting, this.viewState.filterToCategory)) {
return false;
}
}
if (element instanceof SettingsTreeSettingElement && this.viewState.showConfiguredOnly) {
return element.isConfigured;
}
if (element instanceof SettingsTreeGroupElement && this.viewState.showConfiguredOnly) {
return this.groupHasConfiguredSetting(element);
}
return true;
}
private settingContainedInGroup(setting: ISetting, group: SettingsTreeGroupElement): boolean {
return group.children.some(child => {
if (child instanceof SettingsTreeGroupElement) {
return this.settingContainedInGroup(setting, child);
} else if (child instanceof SettingsTreeSettingElement) {
return child.setting.key === setting.key;
} else {
return false;
}
});
}
private groupHasConfiguredSetting(element: SettingsTreeGroupElement): boolean {
for (let child of element.children) {
if (child instanceof SettingsTreeSettingElement) {
const { isConfigured } = inspectSetting(child.setting.key, this.viewState.settingsTarget, this.configurationService);
if (isConfigured) {
return true;
}
} else {
if (child instanceof SettingsTreeGroupElement) {
return this.groupHasConfiguredSetting(child);
}
}
}
return false;
}
}
export class SettingsTreeController extends WorkbenchTreeController {
constructor(
@IConfigurationService configurationService: IConfigurationService
) {
super({}, configurationService);
}
}
export class SettingsAccessibilityProvider implements IAccessibilityProvider {
getAriaLabel(tree: ITree, element: SettingsTreeElement): string {
if (!element) {
return '';
}
if (element instanceof SettingsTreeSettingElement) {
return localize('settingRowAriaLabel', "{0} {1}, Setting", element.displayCategory, element.displayLabel);
}
if (element instanceof SettingsTreeGroupElement) {
return localize('groupRowAriaLabel', "{0}, group", element.label);
}
return '';
}
}
export enum SearchResultIdx {
Local = 0,
Remote = 1
}
export class SearchResultModel {
private rawSearchResults: ISearchResult[];
private cachedUniqueSearchResults: ISearchResult[];
private children: SettingsTreeSettingElement[];
readonly id = 'searchResultModel';
constructor(
private _viewState: ISettingsEditorViewState,
@IConfigurationService private _configurationService: IConfigurationService
) { }
getChildren(): SettingsTreeSettingElement[] {
return this.children;
}
getUniqueResults(): ISearchResult[] {
if (this.cachedUniqueSearchResults) {
return this.cachedUniqueSearchResults;
}
if (!this.rawSearchResults) {
return [];
}
const localMatchKeys = new Set();
const localResult = objects.deepClone(this.rawSearchResults[SearchResultIdx.Local]);
if (localResult) {
localResult.filterMatches.forEach(m => localMatchKeys.add(m.setting.key));
}
const remoteResult = objects.deepClone(this.rawSearchResults[SearchResultIdx.Remote]);
if (remoteResult) {
remoteResult.filterMatches = remoteResult.filterMatches.filter(m => !localMatchKeys.has(m.setting.key));
}
this.cachedUniqueSearchResults = [localResult, remoteResult];
return this.cachedUniqueSearchResults;
}
getRawResults(): ISearchResult[] {
return this.rawSearchResults;
}
setResult(type: SearchResultIdx, result: ISearchResult): void {
this.cachedUniqueSearchResults = null;
this.rawSearchResults = this.rawSearchResults || [];
if (!result) {
delete this.rawSearchResults[type];
return;
}
this.rawSearchResults[type] = result;
// Recompute children
this.children = this.getFlatSettings()
.map(s => createSettingsTreeSettingElement(s, result, this._viewState.settingsTarget, this._configurationService));
}
private getFlatSettings(): ISetting[] {
const flatSettings: ISetting[] = [];
this.getUniqueResults()
.filter(r => !!r)
.forEach(r => {
flatSettings.push(
...r.filterMatches.map(m => m.setting));
});
return flatSettings;
}
}
export class NonExpandableTree extends WorkbenchTree {
expand(): TPromise<any, any> {
return TPromise.wrap(null);
}
collapse(): TPromise<any, any> {
return TPromise.wrap(null);
}
}
| src/vs/workbench/parts/preferences/browser/settingsTree.ts | 1 | https://github.com/microsoft/vscode/commit/3d688527f93a1077a23032c55a829f3f4078d0db | [
0.012099877931177616,
0.0005058803362771869,
0.000164374039741233,
0.00017402802768629044,
0.0014510122127830982
] |
{
"id": 0,
"code_window": [
"\t\tconst commonlyUsed = resolveSettingsTree(commonlyUsedData, dividedGroups.core);\n",
"\t\tresolvedSettingsRoot.children.unshift(commonlyUsed);\n",
"\n",
"\t\tresolvedSettingsRoot.children.push(resolveExtensionsSettings(dividedGroups.extension || []));\n",
"\n",
"\t\tif (this.settingsTreeModel) {\n",
"\t\t\tthis.settingsTreeModel.update(resolvedSettingsRoot);\n",
"\t\t} else {\n",
"\t\t\tthis.settingsTreeModel = this.instantiationService.createInstance(SettingsTreeModel, this.viewState, resolvedSettingsRoot);\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tif (this.searchResultModel) {\n",
"\t\t\tthis.searchResultModel.updateChildren();\n",
"\t\t}\n",
"\n"
],
"file_path": "src/vs/workbench/parts/preferences/browser/settingsEditor2.ts",
"type": "add",
"edit_start_line_idx": 567
} | {
"": [
"--------------------------------------------------------------------------------------------",
"Copyright (c) Microsoft Corporation. All rights reserved.",
"Licensed under the MIT License. See License.txt in the project root for license information.",
"--------------------------------------------------------------------------------------------",
"Do not edit this file. It is machine generated."
],
"codeWorkspace": "コード ワークスペース",
"untitledWorkspace": "未設定 (ワークスペース)",
"workspaceNameVerbose": "{0} (ワークスペース)",
"workspaceName": "{0} (ワークスペース)"
} | i18n/jpn/src/vs/platform/workspaces/common/workspaces.i18n.json | 0 | https://github.com/microsoft/vscode/commit/3d688527f93a1077a23032c55a829f3f4078d0db | [
0.00017791402933653444,
0.00017650381778366864,
0.0001750935916788876,
0.00017650381778366864,
0.0000014102188288234174
] |
{
"id": 0,
"code_window": [
"\t\tconst commonlyUsed = resolveSettingsTree(commonlyUsedData, dividedGroups.core);\n",
"\t\tresolvedSettingsRoot.children.unshift(commonlyUsed);\n",
"\n",
"\t\tresolvedSettingsRoot.children.push(resolveExtensionsSettings(dividedGroups.extension || []));\n",
"\n",
"\t\tif (this.settingsTreeModel) {\n",
"\t\t\tthis.settingsTreeModel.update(resolvedSettingsRoot);\n",
"\t\t} else {\n",
"\t\t\tthis.settingsTreeModel = this.instantiationService.createInstance(SettingsTreeModel, this.viewState, resolvedSettingsRoot);\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tif (this.searchResultModel) {\n",
"\t\t\tthis.searchResultModel.updateChildren();\n",
"\t\t}\n",
"\n"
],
"file_path": "src/vs/workbench/parts/preferences/browser/settingsEditor2.ts",
"type": "add",
"edit_start_line_idx": 567
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
import { onUnexpectedError } from 'vs/base/common/errors';
import { marked } from 'vs/base/common/marked/marked';
import { OS } from 'vs/base/common/platform';
import URI from 'vs/base/common/uri';
import { TPromise } from 'vs/base/common/winjs.base';
import { asText } from 'vs/base/node/request';
import { IMode, TokenizationRegistry } from 'vs/editor/common/modes';
import { generateTokensCSSForColorMap } from 'vs/editor/common/modes/supports/tokenization';
import { tokenizeToString } from 'vs/editor/common/modes/textToHtmlTokenizer';
import { IModeService } from 'vs/editor/common/services/modeService';
import * as nls from 'vs/nls';
import { IEnvironmentService } from 'vs/platform/environment/common/environment';
import { ServicesAccessor } from 'vs/platform/instantiation/common/instantiation';
import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding';
import { IOpenerService } from 'vs/platform/opener/common/opener';
import { IRequestService } from 'vs/platform/request/node/request';
import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';
import { addGAParameters } from 'vs/platform/telemetry/node/telemetryNodeUtils';
import { IWebviewEditorService } from 'vs/workbench/parts/webview/electron-browser/webviewEditorService';
import { IEditorService, ACTIVE_GROUP } from 'vs/workbench/services/editor/common/editorService';
import { KeybindingIO } from 'vs/workbench/services/keybinding/common/keybindingIO';
import { WebviewEditorInput } from 'vs/workbench/parts/webview/electron-browser/webviewEditorInput';
function renderBody(
body: string,
css: string
): string {
const styleSheetPath = require.toUrl('./media/markdown.css').replace('file://', 'vscode-core-resource://');
return `<!DOCTYPE html>
<html>
<head>
<base href="https://code.visualstudio.com/raw/">
<meta http-equiv="Content-type" content="text/html;charset=UTF-8">
<meta http-equiv="Content-Security-Policy" content="default-src 'none'; img-src https: data:; media-src https:; script-src 'none'; style-src vscode-core-resource: https: 'unsafe-inline'; child-src 'none'; frame-src 'none';">
<link rel="stylesheet" type="text/css" href="${styleSheetPath}">
<style>${css}</style>
</head>
<body>${body}</body>
</html>`;
}
export class ReleaseNotesManager {
private _releaseNotesCache: { [version: string]: TPromise<string>; } = Object.create(null);
private _currentReleaseNotes: WebviewEditorInput | undefined = undefined;
public constructor(
@IEnvironmentService private readonly _environmentService: IEnvironmentService,
@IKeybindingService private readonly _keybindingService: IKeybindingService,
@IModeService private readonly _modeService: IModeService,
@IOpenerService private readonly _openerService: IOpenerService,
@IRequestService private readonly _requestService: IRequestService,
@ITelemetryService private readonly _telemetryService: ITelemetryService,
@IEditorService private readonly _editorService: IEditorService,
@IWebviewEditorService private readonly _webviewEditorService: IWebviewEditorService,
) { }
public async show(
accessor: ServicesAccessor,
version: string
): TPromise<boolean> {
const releaseNoteText = await this.loadReleaseNotes(version);
const html = await this.renderBody(releaseNoteText);
const title = nls.localize('releaseNotesInputName', "Release Notes: {0}", version);
const activeControl = this._editorService.activeControl;
if (this._currentReleaseNotes) {
this._currentReleaseNotes.setName(title);
this._currentReleaseNotes.html = html;
this._webviewEditorService.revealWebview(this._currentReleaseNotes, activeControl ? activeControl.group : undefined, false);
} else {
this._currentReleaseNotes = this._webviewEditorService.createWebview(
'releaseNotes',
title,
{ group: ACTIVE_GROUP, preserveFocus: false },
{ tryRestoreScrollPosition: true, enableFindWidget: true },
undefined, {
onDidClickLink: uri => this.onDidClickLink(uri),
onDispose: () => { this._currentReleaseNotes = undefined; }
});
this._currentReleaseNotes.html = html;
}
return true;
}
private loadReleaseNotes(
version: string
): TPromise<string> {
const match = /^(\d+\.\d+)\./.exec(version);
if (!match) {
return TPromise.wrapError<string>(new Error('not found'));
}
const versionLabel = match[1].replace(/\./g, '_');
const baseUrl = 'https://code.visualstudio.com/raw';
const url = `${baseUrl}/v${versionLabel}.md`;
const unassigned = nls.localize('unassigned', "unassigned");
const patchKeybindings = (text: string): string => {
const kb = (match: string, kb: string) => {
const keybinding = this._keybindingService.lookupKeybinding(kb);
if (!keybinding) {
return unassigned;
}
return keybinding.getLabel();
};
const kbstyle = (match: string, kb: string) => {
const keybinding = KeybindingIO.readKeybinding(kb, OS);
if (!keybinding) {
return unassigned;
}
const resolvedKeybindings = this._keybindingService.resolveKeybinding(keybinding);
if (resolvedKeybindings.length === 0) {
return unassigned;
}
return resolvedKeybindings[0].getLabel();
};
return text
.replace(/kb\(([a-z.\d\-]+)\)/gi, kb)
.replace(/kbstyle\(([^\)]+)\)/gi, kbstyle);
};
if (!this._releaseNotesCache[version]) {
this._releaseNotesCache[version] = this._requestService.request({ url })
.then(asText)
.then(text => patchKeybindings(text));
}
return this._releaseNotesCache[version];
}
private onDidClickLink(uri: URI) {
addGAParameters(this._telemetryService, this._environmentService, uri, 'ReleaseNotes')
.then(updated => this._openerService.open(updated))
.then(null, onUnexpectedError);
}
private async renderBody(text: string) {
const colorMap = TokenizationRegistry.getColorMap();
const css = generateTokensCSSForColorMap(colorMap);
const body = renderBody(await this.renderContent(text), css);
return body;
}
private async renderContent(text: string): TPromise<string> {
const renderer = await this.getRenderer(text);
return marked(text, { renderer });
}
private async getRenderer(text: string) {
const result: TPromise<IMode>[] = [];
const renderer = new marked.Renderer();
renderer.code = (code, lang) => {
const modeId = this._modeService.getModeIdForLanguageName(lang);
result.push(this._modeService.getOrCreateMode(modeId));
return '';
};
marked(text, { renderer });
await TPromise.join(result);
renderer.code = (code, lang) => {
const modeId = this._modeService.getModeIdForLanguageName(lang);
return `<code>${tokenizeToString(code, modeId)}</code>`;
};
return renderer;
}
}
| src/vs/workbench/parts/update/electron-browser/releaseNotesEditor.ts | 0 | https://github.com/microsoft/vscode/commit/3d688527f93a1077a23032c55a829f3f4078d0db | [
0.00017797051987145096,
0.00017397559713572264,
0.00017006478447001427,
0.0001740316511131823,
0.000001917758709168993
] |
{
"id": 0,
"code_window": [
"\t\tconst commonlyUsed = resolveSettingsTree(commonlyUsedData, dividedGroups.core);\n",
"\t\tresolvedSettingsRoot.children.unshift(commonlyUsed);\n",
"\n",
"\t\tresolvedSettingsRoot.children.push(resolveExtensionsSettings(dividedGroups.extension || []));\n",
"\n",
"\t\tif (this.settingsTreeModel) {\n",
"\t\t\tthis.settingsTreeModel.update(resolvedSettingsRoot);\n",
"\t\t} else {\n",
"\t\t\tthis.settingsTreeModel = this.instantiationService.createInstance(SettingsTreeModel, this.viewState, resolvedSettingsRoot);\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tif (this.searchResultModel) {\n",
"\t\t\tthis.searchResultModel.updateChildren();\n",
"\t\t}\n",
"\n"
],
"file_path": "src/vs/workbench/parts/preferences/browser/settingsEditor2.ts",
"type": "add",
"edit_start_line_idx": 567
} | {
"": [
"--------------------------------------------------------------------------------------------",
"Copyright (c) Microsoft Corporation. All rights reserved.",
"Licensed under the MIT License. See License.txt in the project root for license information.",
"--------------------------------------------------------------------------------------------",
"Do not edit this file. It is machine generated."
],
"noWorkspace": "Açık Klasör Yok",
"explorerSection": "Dosya Gezgini Bölümü",
"noWorkspaceHelp": "Çalışma alanına hâlâ bir klasör eklemediniz.",
"addFolder": "Klasör Ekle",
"noFolderHelp": "Henüz bir klasör açmadınız.",
"openFolder": "Klasör Aç"
} | i18n/trk/src/vs/workbench/parts/files/electron-browser/views/emptyView.i18n.json | 0 | https://github.com/microsoft/vscode/commit/3d688527f93a1077a23032c55a829f3f4078d0db | [
0.00017861415108200163,
0.00017673775437287986,
0.00017486134311184287,
0.00017673775437287986,
0.0000018764039850793779
] |
{
"id": 1,
"code_window": [
"\t\t\tdelete this.rawSearchResults[type];\n",
"\t\t\treturn;\n",
"\t\t}\n",
"\n",
"\t\tthis.rawSearchResults[type] = result;\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep"
],
"after_edit": [
"\t\tthis.updateChildren();\n",
"\t}\n"
],
"file_path": "src/vs/workbench/parts/preferences/browser/settingsTree.ts",
"type": "add",
"edit_start_line_idx": 909
} | /*---------------------------------------------------------------------------------------------
* 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 { StandardKeyboardEvent } from 'vs/base/browser/keyboardEvent';
import { IMouseEvent } from 'vs/base/browser/mouseEvent';
import { Button } from 'vs/base/browser/ui/button/button';
import { Checkbox } from 'vs/base/browser/ui/checkbox/checkbox';
import { InputBox } from 'vs/base/browser/ui/inputbox/inputBox';
import { SelectBox } from 'vs/base/browser/ui/selectBox/selectBox';
import * as arrays from 'vs/base/common/arrays';
import { Color } from 'vs/base/common/color';
import { Emitter, Event } from 'vs/base/common/event';
import { KeyCode } from 'vs/base/common/keyCodes';
import { dispose, IDisposable } from 'vs/base/common/lifecycle';
import * as objects from 'vs/base/common/objects';
import { escapeRegExpCharacters } from 'vs/base/common/strings';
import URI from 'vs/base/common/uri';
import { TPromise } from 'vs/base/common/winjs.base';
import { IAccessibilityProvider, IDataSource, IFilter, IRenderer, ITree } from 'vs/base/parts/tree/browser/tree';
import { localize } from 'vs/nls';
import { ConfigurationTarget, IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { IContextViewService } from 'vs/platform/contextview/browser/contextView';
import { WorkbenchTree, WorkbenchTreeController } from 'vs/platform/list/browser/listService';
import { registerColor, selectBackground, selectBorder } from 'vs/platform/theme/common/colorRegistry';
import { attachButtonStyler, attachInputBoxStyler, attachSelectBoxStyler } from 'vs/platform/theme/common/styler';
import { ICssStyleCollector, ITheme, IThemeService, registerThemingParticipant } from 'vs/platform/theme/common/themeService';
import { SettingsTarget } from 'vs/workbench/parts/preferences/browser/preferencesWidgets';
import { ITOCEntry } from 'vs/workbench/parts/preferences/browser/settingsLayout';
import { ISearchResult, ISetting, ISettingsGroup } from 'vs/workbench/services/preferences/common/preferences';
const $ = DOM.$;
export const modifiedItemForeground = registerColor('settings.modifiedItemForeground', {
light: '#019001',
dark: '#73C991',
hc: '#73C991'
}, localize('modifiedItemForeground', "(For settings editor preview) The foreground color for a modified setting."));
registerThemingParticipant((theme: ITheme, collector: ICssStyleCollector) => {
const modifiedItemForegroundColor = theme.getColor(modifiedItemForeground);
if (modifiedItemForegroundColor) {
collector.addRule(`.settings-editor > .settings-body > .settings-tree-container .setting-item.is-configured .setting-item-is-configured-label { color: ${modifiedItemForegroundColor}; }`);
}
});
registerThemingParticipant((theme: ITheme, collector: ICssStyleCollector) => {
// TODO@roblou Hacks! Make checkbox background themeable
const selectBackgroundColor = theme.getColor(selectBackground);
if (selectBackgroundColor) {
collector.addRule(`.settings-editor > .settings-body > .settings-tree-container .setting-item-bool .setting-value-checkbox { background-color: ${selectBackgroundColor} !important; }`);
}
// TODO@roblou Hacks! Use proper inputbox theming instead of !important
const selectBorderColor = theme.getColor(selectBorder);
if (selectBorderColor) {
collector.addRule(`.settings-editor > .settings-body > .settings-tree-container .setting-item-bool .setting-value-checkbox { border-color: ${selectBorderColor} !important; }`);
collector.addRule(`.settings-editor > .settings-body > .settings-tree-container .setting-item .setting-item-control > .monaco-inputbox { border: solid 1px ${selectBorderColor} !important; }`);
}
});
export abstract class SettingsTreeElement {
id: string;
parent: any; // SearchResultModel or group element... TODO search should be more similar to the normal case
}
export class SettingsTreeGroupElement extends SettingsTreeElement {
children: (SettingsTreeGroupElement | SettingsTreeSettingElement)[];
label: string;
level: number;
}
export class SettingsTreeSettingElement extends SettingsTreeElement {
setting: ISetting;
isExpanded: boolean;
displayCategory: string;
displayLabel: string;
value: any;
isConfigured: boolean;
overriddenScopeList: string[];
description: string;
valueType?: string | string[];
enum?: string[];
}
export interface ITOCEntry {
id: string;
label: string;
children?: ITOCEntry[];
settings?: (string | ISetting)[];
}
export class SettingsTreeModel {
private _root: SettingsTreeGroupElement;
private _treeElementsById = new Map<string, SettingsTreeElement>();
constructor(
private _viewState: ISettingsEditorViewState,
private _tocRoot: ITOCEntry,
@IConfigurationService private _configurationService: IConfigurationService
) {
this.update(this._tocRoot);
}
get root(): SettingsTreeGroupElement {
return this._root;
}
update(newTocRoot = this._tocRoot): void {
const newRoot = this.createSettingsTreeGroupElement(newTocRoot);
if (this._root) {
this._root.children = newRoot.children;
} else {
this._root = newRoot;
}
}
getElementById(id: string): SettingsTreeElement {
return this._treeElementsById.get(id);
}
private createSettingsTreeGroupElement(tocEntry: ITOCEntry, parent?: SettingsTreeGroupElement): SettingsTreeGroupElement {
const element = new SettingsTreeGroupElement();
element.id = tocEntry.id;
element.label = tocEntry.label;
element.parent = parent;
element.level = this.getDepth(element);
if (tocEntry.children) {
element.children = tocEntry.children.map(child => this.createSettingsTreeGroupElement(child, element));
} else if (tocEntry.settings) {
element.children = tocEntry.settings.map(s => this.createSettingsTreeSettingElement(<ISetting>s, element));
}
this._treeElementsById.set(element.id, element);
return element;
}
private getDepth(element: SettingsTreeElement): number {
if (element.parent) {
return 1 + this.getDepth(element.parent);
} else {
return 0;
}
}
private createSettingsTreeSettingElement(setting: ISetting, parent: SettingsTreeGroupElement): SettingsTreeSettingElement {
const element = createSettingsTreeSettingElement(setting, parent, this._viewState.settingsTarget, this._configurationService);
this._treeElementsById.set(element.id, element);
return element;
}
}
function sanitizeId(id: string): string {
return id.replace(/[\.\/]/, '_');
}
function createSettingsTreeSettingElement(setting: ISetting, parent: any, settingsTarget: SettingsTarget, configurationService: IConfigurationService): SettingsTreeSettingElement {
const element = new SettingsTreeSettingElement();
element.id = sanitizeId(parent.id + '_' + setting.key);
element.parent = parent;
const { isConfigured, inspected, targetSelector } = inspectSetting(setting.key, settingsTarget, configurationService);
const displayValue = isConfigured ? inspected[targetSelector] : inspected.default;
const overriddenScopeList = [];
if (targetSelector === 'user' && typeof inspected.workspace !== 'undefined') {
overriddenScopeList.push(localize('workspace', "Workspace"));
}
if (targetSelector === 'workspace' && typeof inspected.user !== 'undefined') {
overriddenScopeList.push(localize('user', "User"));
}
const displayKeyFormat = settingKeyToDisplayFormat(setting.key, parent.id);
element.setting = setting;
element.displayLabel = displayKeyFormat.label;
element.displayCategory = displayKeyFormat.category;
element.isExpanded = false;
element.value = displayValue;
element.isConfigured = isConfigured;
element.overriddenScopeList = overriddenScopeList;
element.description = setting.description.join('\n');
element.enum = setting.enum;
element.valueType = setting.type;
return element;
}
function inspectSetting(key: string, target: SettingsTarget, configurationService: IConfigurationService): { isConfigured: boolean, inspected: any, targetSelector: string } {
const inspectOverrides = URI.isUri(target) ? { resource: target } : undefined;
const inspected = configurationService.inspect(key, inspectOverrides);
const targetSelector = target === ConfigurationTarget.USER ? 'user' :
target === ConfigurationTarget.WORKSPACE ? 'workspace' :
'workspaceFolder';
const isConfigured = typeof inspected[targetSelector] !== 'undefined';
return { isConfigured, inspected, targetSelector };
}
export function resolveSettingsTree(tocData: ITOCEntry, coreSettingsGroups: ISettingsGroup[]): ITOCEntry {
return _resolveSettingsTree(tocData, getFlatSettings(coreSettingsGroups));
}
export function resolveExtensionsSettings(groups: ISettingsGroup[]): ITOCEntry {
const settingsGroupToEntry = (group: ISettingsGroup) => {
const flatSettings = arrays.flatten(
group.sections.map(section => section.settings));
return {
id: group.id,
label: group.title,
settings: flatSettings
};
};
const extGroups = groups
.sort((a, b) => a.title.localeCompare(b.title))
.map(g => settingsGroupToEntry(g));
return {
id: 'extensions',
label: localize('extensions', "Extensions"),
children: extGroups
};
}
function _resolveSettingsTree(tocData: ITOCEntry, allSettings: Set<ISetting>): ITOCEntry {
if (tocData.settings) {
return <ITOCEntry>{
id: tocData.id,
label: tocData.label,
settings: arrays.flatten(tocData.settings.map(pattern => getMatchingSettings(allSettings, <string>pattern)))
};
} else if (tocData.children) {
return <ITOCEntry>{
id: tocData.id,
label: tocData.label,
children: tocData.children.map(child => _resolveSettingsTree(child, allSettings))
};
}
return null;
}
function getMatchingSettings(allSettings: Set<ISetting>, pattern: string): ISetting[] {
const result: ISetting[] = [];
allSettings.forEach(s => {
if (settingMatches(s, pattern)) {
result.push(s);
allSettings.delete(s);
}
});
return result.sort((a, b) => a.key.localeCompare(b.key));
}
function settingMatches(s: ISetting, pattern: string): boolean {
pattern = escapeRegExpCharacters(pattern)
.replace(/\\\*/g, '.*');
const regexp = new RegExp(`^${pattern}`, 'i');
return regexp.test(s.key);
}
function getFlatSettings(settingsGroups: ISettingsGroup[]) {
const result: Set<ISetting> = new Set();
for (let group of settingsGroups) {
for (let section of group.sections) {
for (let s of section.settings) {
result.add(s);
}
}
}
return result;
}
export class SettingsDataSource implements IDataSource {
getId(tree: ITree, element: SettingsTreeElement): string {
return element.id;
}
hasChildren(tree: ITree, element: SettingsTreeElement): boolean {
if (element instanceof SearchResultModel) {
return true;
}
if (element instanceof SettingsTreeGroupElement) {
return true;
}
return false;
}
getChildren(tree: ITree, element: SettingsTreeElement): TPromise<any, any> {
return TPromise.as(this._getChildren(element));
}
private _getChildren(element: SettingsTreeElement): SettingsTreeElement[] {
if (element instanceof SearchResultModel) {
return element.getChildren();
} else if (element instanceof SettingsTreeGroupElement) {
return element.children;
} else {
// No children...
return null;
}
}
getParent(tree: ITree, element: SettingsTreeElement): TPromise<any, any> {
return TPromise.wrap(element.parent);
}
shouldAutoexpand(): boolean {
return true;
}
}
export function settingKeyToDisplayFormat(key: string, groupId = ''): { category: string, label: string } {
let label = wordifyKey(key);
const lastDotIdx = label.lastIndexOf('.');
let category = '';
if (lastDotIdx >= 0) {
category = label.substr(0, lastDotIdx);
label = label.substr(lastDotIdx + 1);
}
groupId = wordifyKey(groupId.replace(/\//g, '.'));
category = trimCategoryForGroup(category, groupId);
return { category, label };
}
function wordifyKey(key: string): string {
return key
.replace(/\.([a-z])/g, (match, p1) => `.${p1.toUpperCase()}`)
.replace(/([a-z])([A-Z])/g, '$1 $2') // fooBar => foo Bar
.replace(/^[a-z]/g, match => match.toUpperCase()); // foo => Foo
}
function trimCategoryForGroup(category: string, groupId: string): string {
const doTrim = forward => {
const parts = groupId.split('.');
while (parts.length) {
const reg = new RegExp(`^${parts.join('\\.')}(\\.|$)`, 'i');
if (reg.test(category)) {
return category.replace(reg, '');
}
if (forward) {
parts.pop();
} else {
parts.shift();
}
}
return null;
};
let trimmed = doTrim(true);
if (trimmed === null) {
trimmed = doTrim(false);
}
if (trimmed === null) {
trimmed = category;
}
return trimmed;
}
export interface ISettingsEditorViewState {
settingsTarget: SettingsTarget;
showConfiguredOnly?: boolean;
filterToCategory?: SettingsTreeGroupElement;
}
interface IDisposableTemplate {
toDispose: IDisposable[];
}
interface ISettingItemTemplate extends IDisposableTemplate {
parent: HTMLElement;
containerElement: HTMLElement;
categoryElement: HTMLElement;
labelElement: HTMLElement;
descriptionElement: HTMLElement;
controlElement: HTMLElement;
isConfiguredElement: HTMLElement;
otherOverridesElement: HTMLElement;
}
interface ISettingBoolItemTemplate extends IDisposableTemplate {
parent: HTMLElement;
onChange?: (newState: boolean) => void;
containerElement: HTMLElement;
categoryElement: HTMLElement;
labelElement: HTMLElement;
descriptionElement: HTMLElement;
checkbox: Checkbox;
isConfiguredElement: HTMLElement;
otherOverridesElement: HTMLElement;
}
interface IGroupTitleTemplate extends IDisposableTemplate {
context?: SettingsTreeGroupElement;
parent: HTMLElement;
}
const SETTINGS_ELEMENT_TEMPLATE_ID = 'settings.entry.template';
const SETTINGS_BOOL_TEMPLATE_ID = 'settings.bool.template';
const SETTINGS_GROUP_ELEMENT_TEMPLATE_ID = 'settings.group.template';
export interface ISettingChangeEvent {
key: string;
value: any; // undefined => reset/unconfigure
}
export class SettingsRenderer implements IRenderer {
private static readonly SETTING_ROW_HEIGHT = 94;
private static readonly SETTING_BOOL_ROW_HEIGHT = 61;
private readonly _onDidChangeSetting: Emitter<ISettingChangeEvent> = new Emitter<ISettingChangeEvent>();
public readonly onDidChangeSetting: Event<ISettingChangeEvent> = this._onDidChangeSetting.event;
private readonly _onDidOpenSettings: Emitter<void> = new Emitter<void>();
public readonly onDidOpenSettings: Event<void> = this._onDidOpenSettings.event;
private measureContainer: HTMLElement;
constructor(
_measureContainer: HTMLElement,
@IThemeService private themeService: IThemeService,
@IContextViewService private contextViewService: IContextViewService
) {
this.measureContainer = DOM.append(_measureContainer, $('.setting-measure-container.monaco-tree-row'));
}
getHeight(tree: ITree, element: SettingsTreeElement): number {
if (element instanceof SettingsTreeGroupElement) {
return 40 + (7 * element.level);
}
if (element instanceof SettingsTreeSettingElement) {
const isSelected = this.elementIsSelected(tree, element);
if (isSelected) {
return this.measureSettingElementHeight(tree, element);
} else {
return this._getUnexpandedSettingHeight(element);
}
}
return 0;
}
_getUnexpandedSettingHeight(element: SettingsTreeSettingElement): number {
if (element.valueType === 'boolean') {
return SettingsRenderer.SETTING_BOOL_ROW_HEIGHT;
} else {
return SettingsRenderer.SETTING_ROW_HEIGHT;
}
}
private measureSettingElementHeight(tree: ITree, element: SettingsTreeSettingElement): number {
const measureHelper = DOM.append(this.measureContainer, $('.setting-measure-helper'));
const templateId = this.getTemplateId(tree, element);
const template = this.renderTemplate(tree, templateId, measureHelper);
this.renderElement(tree, element, templateId, template);
const height = this.measureContainer.offsetHeight;
this.measureContainer.removeChild(this.measureContainer.firstChild);
return Math.max(height, this._getUnexpandedSettingHeight(element));
}
getTemplateId(tree: ITree, element: SettingsTreeElement): string {
if (element instanceof SettingsTreeGroupElement) {
return SETTINGS_GROUP_ELEMENT_TEMPLATE_ID;
}
if (element instanceof SettingsTreeSettingElement) {
if (element.valueType === 'boolean') {
return SETTINGS_BOOL_TEMPLATE_ID;
}
return SETTINGS_ELEMENT_TEMPLATE_ID;
}
return '';
}
renderTemplate(tree: ITree, templateId: string, container: HTMLElement) {
if (templateId === SETTINGS_GROUP_ELEMENT_TEMPLATE_ID) {
return this.renderGroupTitleTemplate(container);
}
if (templateId === SETTINGS_ELEMENT_TEMPLATE_ID) {
return this.renderSettingTemplate(tree, container);
}
if (templateId === SETTINGS_BOOL_TEMPLATE_ID) {
return this.renderSettingBoolTemplate(tree, container);
}
return null;
}
private renderGroupTitleTemplate(container: HTMLElement): IGroupTitleTemplate {
DOM.addClass(container, 'group-title');
const toDispose = [];
const template: IGroupTitleTemplate = {
parent: container,
toDispose
};
return template;
}
private renderSettingTemplate(tree: ITree, container: HTMLElement): ISettingItemTemplate {
DOM.addClass(container, 'setting-item');
const titleElement = DOM.append(container, $('.setting-item-title'));
const categoryElement = DOM.append(titleElement, $('span.setting-item-category'));
const labelElement = DOM.append(titleElement, $('span.setting-item-label'));
const isConfiguredElement = DOM.append(titleElement, $('span.setting-item-is-configured-label'));
const otherOverridesElement = DOM.append(titleElement, $('span.setting-item-overrides'));
const descriptionElement = DOM.append(container, $('.setting-item-description'));
const valueElement = DOM.append(container, $('.setting-item-value'));
const controlElement = DOM.append(valueElement, $('div'));
const resetButtonElement = DOM.append(valueElement, $('.reset-button-container'));
const toDispose = [];
const template: ISettingItemTemplate = {
parent: container,
toDispose,
containerElement: container,
categoryElement,
labelElement,
descriptionElement,
controlElement,
isConfiguredElement,
otherOverridesElement
};
// Prevent clicks from being handled by list
toDispose.push(DOM.addDisposableListener(controlElement, 'mousedown', (e: IMouseEvent) => e.stopPropagation()));
toDispose.push(DOM.addDisposableListener(resetButtonElement, 'mousedown', (e: IMouseEvent) => e.stopPropagation()));
toDispose.push(DOM.addStandardDisposableListener(valueElement, 'keydown', (e: StandardKeyboardEvent) => {
if (e.keyCode === KeyCode.Escape) {
tree.domFocus();
e.browserEvent.stopPropagation();
}
}));
return template;
}
private renderSettingBoolTemplate(tree: ITree, container: HTMLElement): ISettingBoolItemTemplate {
DOM.addClass(container, 'setting-item');
DOM.addClass(container, 'setting-item-bool');
const titleElement = DOM.append(container, $('.setting-item-title'));
const categoryElement = DOM.append(titleElement, $('span.setting-item-category'));
const labelElement = DOM.append(titleElement, $('span.setting-item-label'));
const isConfiguredElement = DOM.append(titleElement, $('span.setting-item-is-configured-label'));
const otherOverridesElement = DOM.append(titleElement, $('span.setting-item-overrides'));
const descriptionAndValueElement = DOM.append(container, $('.setting-item-value-description'));
const controlElement = DOM.append(descriptionAndValueElement, $('.setting-item-bool-control'));
const descriptionElement = DOM.append(descriptionAndValueElement, $('.setting-item-description'));
const toDispose = [];
const checkbox = new Checkbox({ actionClassName: 'setting-value-checkbox', isChecked: true, title: '', inputActiveOptionBorder: null });
controlElement.appendChild(checkbox.domNode);
toDispose.push(checkbox);
toDispose.push(checkbox.onChange(() => {
if (template.onChange) {
template.onChange(checkbox.checked);
}
}));
const template: ISettingBoolItemTemplate = {
parent: container,
toDispose,
containerElement: container,
categoryElement,
labelElement,
checkbox,
descriptionElement,
isConfiguredElement,
otherOverridesElement
};
// Prevent clicks from being handled by list
toDispose.push(DOM.addDisposableListener(controlElement, 'mousedown', (e: IMouseEvent) => e.stopPropagation()));
toDispose.push(DOM.addStandardDisposableListener(controlElement, 'keydown', (e: StandardKeyboardEvent) => {
if (e.keyCode === KeyCode.Escape) {
tree.domFocus();
e.browserEvent.stopPropagation();
}
}));
return template;
}
renderElement(tree: ITree, element: SettingsTreeElement, templateId: string, template: any): void {
if (templateId === SETTINGS_ELEMENT_TEMPLATE_ID) {
return this.renderSettingElement(tree, <SettingsTreeSettingElement>element, template);
}
if (templateId === SETTINGS_BOOL_TEMPLATE_ID) {
return this.renderSettingElement(tree, <SettingsTreeSettingElement>element, template);
}
if (templateId === SETTINGS_GROUP_ELEMENT_TEMPLATE_ID) {
return this.renderGroupElement(<SettingsTreeGroupElement>element, template);
}
}
private renderGroupElement(element: SettingsTreeGroupElement, template: IGroupTitleTemplate): void {
template.parent.innerHTML = '';
const labelElement = DOM.append(template.parent, $('div.settings-group-title-label'));
labelElement.classList.add(`settings-group-level-${element.level}`);
labelElement.textContent = (<SettingsTreeGroupElement>element).label;
}
private elementIsSelected(tree: ITree, element: SettingsTreeElement): boolean {
const selection = tree.getSelection();
const selectedElement: SettingsTreeElement = selection && selection[0];
return selectedElement && selectedElement.id === element.id;
}
private renderSettingElement(tree: ITree, element: SettingsTreeSettingElement, template: ISettingItemTemplate | ISettingBoolItemTemplate): void {
const isSelected = !!this.elementIsSelected(tree, element);
const setting = element.setting;
DOM.toggleClass(template.parent, 'is-configured', element.isConfigured);
DOM.toggleClass(template.parent, 'is-expanded', isSelected);
template.containerElement.id = element.id.replace(/\./g, '_');
const titleTooltip = setting.key;
template.categoryElement.textContent = element.displayCategory && (element.displayCategory + ': ');
template.categoryElement.title = titleTooltip;
template.labelElement.textContent = element.displayLabel;
template.labelElement.title = titleTooltip;
template.descriptionElement.textContent = element.description;
this.renderValue(element, isSelected, <ISettingItemTemplate>template);
template.isConfiguredElement.textContent = element.isConfigured ? localize('configured', "Modified") : '';
if (element.overriddenScopeList.length) {
let otherOverridesLabel = element.isConfigured ?
localize('alsoConfiguredIn', "Also modified in") :
localize('configuredIn', "Modified in");
template.otherOverridesElement.textContent = `(${otherOverridesLabel}: ${element.overriddenScopeList.join(', ')})`;
}
}
private renderValue(element: SettingsTreeSettingElement, isSelected: boolean, template: ISettingItemTemplate | ISettingBoolItemTemplate): void {
const onChange = value => this._onDidChangeSetting.fire({ key: element.setting.key, value });
if (element.valueType === 'boolean') {
this.renderBool(element, isSelected, <ISettingBoolItemTemplate>template, onChange);
} else {
return this._renderValue(element, isSelected, <ISettingItemTemplate>template, onChange);
}
}
private _renderValue(element: SettingsTreeSettingElement, isSelected: boolean, template: ISettingItemTemplate, onChange: (value: any) => void): void {
const valueControlElement = template.controlElement;
valueControlElement.innerHTML = '';
valueControlElement.setAttribute('class', 'setting-item-control');
if (element.enum && (element.valueType === 'string' || !element.valueType)) {
valueControlElement.classList.add('setting-type-enum');
this.renderEnum(element, isSelected, template, valueControlElement, onChange);
} else if (element.valueType === 'string') {
valueControlElement.classList.add('setting-type-string');
this.renderText(element, isSelected, template, valueControlElement, onChange);
} else if (element.valueType === 'number' || element.valueType === 'integer') {
valueControlElement.classList.add('setting-type-number');
const parseFn = element.valueType === 'integer' ? parseInt : parseFloat;
this.renderText(element, isSelected, template, valueControlElement, value => onChange(parseFn(value)));
} else {
valueControlElement.classList.add('setting-type-complex');
this.renderEditInSettingsJson(element, isSelected, template, valueControlElement);
}
}
private renderBool(dataElement: SettingsTreeSettingElement, isSelected: boolean, template: ISettingBoolItemTemplate, onChange: (value: boolean) => void): void {
template.onChange = null;
template.checkbox.checked = dataElement.value;
template.onChange = onChange;
template.checkbox.domNode.tabIndex = isSelected ? 0 : -1;
}
private renderEnum(dataElement: SettingsTreeSettingElement, isSelected: boolean, template: ISettingItemTemplate, element: HTMLElement, onChange: (value: string) => void): void {
const idx = dataElement.enum.indexOf(dataElement.value);
const displayOptions = dataElement.enum.map(escapeInvisibleChars);
const selectBox = new SelectBox(displayOptions, idx, this.contextViewService);
template.toDispose.push(attachSelectBoxStyler(selectBox, this.themeService));
selectBox.render(element);
if (element.firstElementChild) {
element.firstElementChild.setAttribute('tabindex', isSelected ? '0' : '-1');
}
template.toDispose.push(
selectBox.onDidSelect(e => onChange(dataElement.enum[e.index])));
}
private renderText(dataElement: SettingsTreeSettingElement, isSelected: boolean, template: ISettingItemTemplate, element: HTMLElement, onChange: (value: string) => void): void {
const inputBox = new InputBox(element, this.contextViewService);
template.toDispose.push(attachInputBoxStyler(inputBox, this.themeService));
template.toDispose.push(inputBox);
inputBox.value = dataElement.value;
inputBox.inputElement.tabIndex = isSelected ? 0 : -1;
template.toDispose.push(
inputBox.onDidChange(e => onChange(e)));
}
private renderEditInSettingsJson(dataElement: SettingsTreeSettingElement, isSelected: boolean, template: ISettingItemTemplate, element: HTMLElement): void {
const openSettingsButton = new Button(element, { title: true, buttonBackground: null, buttonHoverBackground: null });
openSettingsButton.onDidClick(() => this._onDidOpenSettings.fire());
openSettingsButton.label = localize('editInSettingsJson', "Edit in settings.json");
openSettingsButton.element.classList.add('edit-in-settings-button');
openSettingsButton.element.tabIndex = isSelected ? 0 : -1;
template.toDispose.push(openSettingsButton);
template.toDispose.push(attachButtonStyler(openSettingsButton, this.themeService, {
buttonBackground: Color.transparent.toString(),
buttonHoverBackground: Color.transparent.toString(),
buttonForeground: 'foreground'
}));
}
disposeTemplate(tree: ITree, templateId: string, template: IDisposableTemplate): void {
dispose(template.toDispose);
}
}
function escapeInvisibleChars(enumValue: string): string {
return enumValue && enumValue
.replace(/\n/g, '\\n')
.replace(/\r/g, '\\r');
}
export class SettingsTreeFilter implements IFilter {
constructor(
private viewState: ISettingsEditorViewState,
@IConfigurationService private configurationService: IConfigurationService
) { }
isVisible(tree: ITree, element: SettingsTreeElement): boolean {
if (this.viewState.filterToCategory && element instanceof SettingsTreeSettingElement) {
if (!this.settingContainedInGroup(element.setting, this.viewState.filterToCategory)) {
return false;
}
}
if (element instanceof SettingsTreeSettingElement && this.viewState.showConfiguredOnly) {
return element.isConfigured;
}
if (element instanceof SettingsTreeGroupElement && this.viewState.showConfiguredOnly) {
return this.groupHasConfiguredSetting(element);
}
return true;
}
private settingContainedInGroup(setting: ISetting, group: SettingsTreeGroupElement): boolean {
return group.children.some(child => {
if (child instanceof SettingsTreeGroupElement) {
return this.settingContainedInGroup(setting, child);
} else if (child instanceof SettingsTreeSettingElement) {
return child.setting.key === setting.key;
} else {
return false;
}
});
}
private groupHasConfiguredSetting(element: SettingsTreeGroupElement): boolean {
for (let child of element.children) {
if (child instanceof SettingsTreeSettingElement) {
const { isConfigured } = inspectSetting(child.setting.key, this.viewState.settingsTarget, this.configurationService);
if (isConfigured) {
return true;
}
} else {
if (child instanceof SettingsTreeGroupElement) {
return this.groupHasConfiguredSetting(child);
}
}
}
return false;
}
}
export class SettingsTreeController extends WorkbenchTreeController {
constructor(
@IConfigurationService configurationService: IConfigurationService
) {
super({}, configurationService);
}
}
export class SettingsAccessibilityProvider implements IAccessibilityProvider {
getAriaLabel(tree: ITree, element: SettingsTreeElement): string {
if (!element) {
return '';
}
if (element instanceof SettingsTreeSettingElement) {
return localize('settingRowAriaLabel', "{0} {1}, Setting", element.displayCategory, element.displayLabel);
}
if (element instanceof SettingsTreeGroupElement) {
return localize('groupRowAriaLabel', "{0}, group", element.label);
}
return '';
}
}
export enum SearchResultIdx {
Local = 0,
Remote = 1
}
export class SearchResultModel {
private rawSearchResults: ISearchResult[];
private cachedUniqueSearchResults: ISearchResult[];
private children: SettingsTreeSettingElement[];
readonly id = 'searchResultModel';
constructor(
private _viewState: ISettingsEditorViewState,
@IConfigurationService private _configurationService: IConfigurationService
) { }
getChildren(): SettingsTreeSettingElement[] {
return this.children;
}
getUniqueResults(): ISearchResult[] {
if (this.cachedUniqueSearchResults) {
return this.cachedUniqueSearchResults;
}
if (!this.rawSearchResults) {
return [];
}
const localMatchKeys = new Set();
const localResult = objects.deepClone(this.rawSearchResults[SearchResultIdx.Local]);
if (localResult) {
localResult.filterMatches.forEach(m => localMatchKeys.add(m.setting.key));
}
const remoteResult = objects.deepClone(this.rawSearchResults[SearchResultIdx.Remote]);
if (remoteResult) {
remoteResult.filterMatches = remoteResult.filterMatches.filter(m => !localMatchKeys.has(m.setting.key));
}
this.cachedUniqueSearchResults = [localResult, remoteResult];
return this.cachedUniqueSearchResults;
}
getRawResults(): ISearchResult[] {
return this.rawSearchResults;
}
setResult(type: SearchResultIdx, result: ISearchResult): void {
this.cachedUniqueSearchResults = null;
this.rawSearchResults = this.rawSearchResults || [];
if (!result) {
delete this.rawSearchResults[type];
return;
}
this.rawSearchResults[type] = result;
// Recompute children
this.children = this.getFlatSettings()
.map(s => createSettingsTreeSettingElement(s, result, this._viewState.settingsTarget, this._configurationService));
}
private getFlatSettings(): ISetting[] {
const flatSettings: ISetting[] = [];
this.getUniqueResults()
.filter(r => !!r)
.forEach(r => {
flatSettings.push(
...r.filterMatches.map(m => m.setting));
});
return flatSettings;
}
}
export class NonExpandableTree extends WorkbenchTree {
expand(): TPromise<any, any> {
return TPromise.wrap(null);
}
collapse(): TPromise<any, any> {
return TPromise.wrap(null);
}
}
| src/vs/workbench/parts/preferences/browser/settingsTree.ts | 1 | https://github.com/microsoft/vscode/commit/3d688527f93a1077a23032c55a829f3f4078d0db | [
0.997108519077301,
0.010996117256581783,
0.00016426407091785222,
0.00017301979823969305,
0.10226013511419296
] |
{
"id": 1,
"code_window": [
"\t\t\tdelete this.rawSearchResults[type];\n",
"\t\t\treturn;\n",
"\t\t}\n",
"\n",
"\t\tthis.rawSearchResults[type] = result;\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep"
],
"after_edit": [
"\t\tthis.updateChildren();\n",
"\t}\n"
],
"file_path": "src/vs/workbench/parts/preferences/browser/settingsTree.ts",
"type": "add",
"edit_start_line_idx": 909
} | {
"": [
"--------------------------------------------------------------------------------------------",
"Copyright (c) Microsoft Corporation. All rights reserved.",
"Licensed under the MIT License. See License.txt in the project root for license information.",
"--------------------------------------------------------------------------------------------",
"Do not edit this file. It is machine generated."
],
"json.bower.default": "bower.json predefinito",
"json.bower.error.repoaccess": "La richiesta al repository Bower non è riuscita: {0}",
"json.bower.latest.version": "più recente"
} | i18n/ita/extensions/javascript/out/features/bowerJSONContribution.i18n.json | 0 | https://github.com/microsoft/vscode/commit/3d688527f93a1077a23032c55a829f3f4078d0db | [
0.00017741546616889536,
0.00017694718553684652,
0.00017647889035288244,
0.00017694718553684652,
4.682879080064595e-7
] |
{
"id": 1,
"code_window": [
"\t\t\tdelete this.rawSearchResults[type];\n",
"\t\t\treturn;\n",
"\t\t}\n",
"\n",
"\t\tthis.rawSearchResults[type] = result;\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep"
],
"after_edit": [
"\t\tthis.updateChildren();\n",
"\t}\n"
],
"file_path": "src/vs/workbench/parts/preferences/browser/settingsTree.ts",
"type": "add",
"edit_start_line_idx": 909
} | {
"": [
"--------------------------------------------------------------------------------------------",
"Copyright (c) Microsoft Corporation. All rights reserved.",
"Licensed under the MIT License. See License.txt in the project root for license information.",
"--------------------------------------------------------------------------------------------",
"Do not edit this file. It is machine generated."
],
"telemetryConfigurationTitle": "Telemetria",
"telemetry.enableTelemetry": "Consente l'invio di errori e dati sull'utilizzo a Microsoft."
} | i18n/ita/src/vs/platform/telemetry/common/telemetryService.i18n.json | 0 | https://github.com/microsoft/vscode/commit/3d688527f93a1077a23032c55a829f3f4078d0db | [
0.00018227932741865516,
0.00017981136625166982,
0.0001773434050846845,
0.00017981136625166982,
0.000002467961166985333
] |
{
"id": 1,
"code_window": [
"\t\t\tdelete this.rawSearchResults[type];\n",
"\t\t\treturn;\n",
"\t\t}\n",
"\n",
"\t\tthis.rawSearchResults[type] = result;\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep"
],
"after_edit": [
"\t\tthis.updateChildren();\n",
"\t}\n"
],
"file_path": "src/vs/workbench/parts/preferences/browser/settingsTree.ts",
"type": "add",
"edit_start_line_idx": 909
} | {
"": [
"--------------------------------------------------------------------------------------------",
"Copyright (c) Microsoft Corporation. All rights reserved.",
"Licensed under the MIT License. See License.txt in the project root for license information.",
"--------------------------------------------------------------------------------------------",
"Do not edit this file. It is machine generated."
],
"plainText.alias": "プレーンテキスト"
} | i18n/jpn/src/vs/editor/common/modes/modesRegistry.i18n.json | 0 | https://github.com/microsoft/vscode/commit/3d688527f93a1077a23032c55a829f3f4078d0db | [
0.00018163012282457203,
0.0001797672302927822,
0.00017790435231290758,
0.0001797672302927822,
0.000001862885255832225
] |
{
"id": 2,
"code_window": [
"\n",
"\t\t// Recompute children\n",
"\t\tthis.children = this.getFlatSettings()\n"
],
"labels": [
"keep",
"replace",
"keep"
],
"after_edit": [
"\tupdateChildren(): void {\n"
],
"file_path": "src/vs/workbench/parts/preferences/browser/settingsTree.ts",
"type": "replace",
"edit_start_line_idx": 910
} | /*---------------------------------------------------------------------------------------------
* 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 { Button } from 'vs/base/browser/ui/button/button';
import * as arrays from 'vs/base/common/arrays';
import { Delayer, ThrottledDelayer } from 'vs/base/common/async';
import { CancellationToken } from 'vs/base/common/cancellation';
import * as collections from 'vs/base/common/collections';
import { Color } from 'vs/base/common/color';
import { getErrorMessage, isPromiseCanceledError } from 'vs/base/common/errors';
import URI from 'vs/base/common/uri';
import { TPromise } from 'vs/base/common/winjs.base';
import { ITree, ITreeConfiguration } from 'vs/base/parts/tree/browser/tree';
import { DefaultTreestyler, OpenMode } from 'vs/base/parts/tree/browser/treeDefaults';
import 'vs/css!./media/settingsEditor2';
import { localize } from 'vs/nls';
import { ConfigurationTarget, IConfigurationOverrides, IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { IContextKey, IContextKeyService } from 'vs/platform/contextkey/common/contextkey';
import { IEnvironmentService } from 'vs/platform/environment/common/environment';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { WorkbenchTree, WorkbenchTreeController } from 'vs/platform/list/browser/listService';
import { ILogService } from 'vs/platform/log/common/log';
import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';
import { editorBackground, foreground, listActiveSelectionBackground, listInactiveSelectionBackground } from 'vs/platform/theme/common/colorRegistry';
import { attachButtonStyler, attachStyler } from 'vs/platform/theme/common/styler';
import { ICssStyleCollector, ITheme, IThemeService, registerThemingParticipant } from 'vs/platform/theme/common/themeService';
import { BaseEditor } from 'vs/workbench/browser/parts/editor/baseEditor';
import { EditorOptions, IEditor } from 'vs/workbench/common/editor';
import { SearchWidget, SettingsTarget, SettingsTargetsWidget } from 'vs/workbench/parts/preferences/browser/preferencesWidgets';
import { commonlyUsedData, tocData } from 'vs/workbench/parts/preferences/browser/settingsLayout';
import { ISettingsEditorViewState, NonExpandableTree, resolveExtensionsSettings, resolveSettingsTree, SearchResultIdx, SearchResultModel, SettingsAccessibilityProvider, SettingsDataSource, SettingsRenderer, SettingsTreeController, SettingsTreeElement, SettingsTreeFilter, SettingsTreeGroupElement, SettingsTreeModel, SettingsTreeSettingElement } from 'vs/workbench/parts/preferences/browser/settingsTree';
import { TOCDataSource, TOCRenderer, TOCTreeModel } from 'vs/workbench/parts/preferences/browser/tocTree';
import { CONTEXT_SETTINGS_EDITOR, CONTEXT_SETTINGS_FIRST_ROW_FOCUS, CONTEXT_SETTINGS_SEARCH_FOCUS, IPreferencesSearchService, ISearchProvider } from 'vs/workbench/parts/preferences/common/preferences';
import { IPreferencesService, ISearchResult, ISettingsEditorModel } from 'vs/workbench/services/preferences/common/preferences';
import { SettingsEditor2Input } from 'vs/workbench/services/preferences/common/preferencesEditorInput';
import { DefaultSettingsEditorModel } from 'vs/workbench/services/preferences/common/preferencesModels';
const $ = DOM.$;
export class SettingsEditor2 extends BaseEditor {
public static readonly ID: string = 'workbench.editor.settings2';
private defaultSettingsEditorModel: DefaultSettingsEditorModel;
private rootElement: HTMLElement;
private headerContainer: HTMLElement;
private searchWidget: SearchWidget;
private settingsTargetsWidget: SettingsTargetsWidget;
private showConfiguredSettingsOnlyCheckbox: HTMLInputElement;
private settingsTreeContainer: HTMLElement;
private settingsTree: WorkbenchTree;
private treeDataSource: SettingsDataSource;
private tocTreeModel: TOCTreeModel;
private settingsTreeModel: SettingsTreeModel;
private tocTreeContainer: HTMLElement;
private tocTree: WorkbenchTree;
private delayedFilterLogging: Delayer<void>;
private localSearchDelayer: Delayer<void>;
private remoteSearchThrottle: ThrottledDelayer<void>;
private searchInProgress: TPromise<void>;
private settingUpdateDelayer: Delayer<void>;
private pendingSettingUpdate: { key: string, value: any };
private selectedElement: SettingsTreeElement;
private viewState: ISettingsEditorViewState;
private searchResultModel: SearchResultModel;
private firstRowFocused: IContextKey<boolean>;
private inSettingsEditorContextKey: IContextKey<boolean>;
private searchFocusContextKey: IContextKey<boolean>;
constructor(
@ITelemetryService telemetryService: ITelemetryService,
@IConfigurationService private configurationService: IConfigurationService,
@IThemeService themeService: IThemeService,
@IPreferencesService private preferencesService: IPreferencesService,
@IInstantiationService private instantiationService: IInstantiationService,
@IPreferencesSearchService private preferencesSearchService: IPreferencesSearchService,
@ILogService private logService: ILogService,
@IEnvironmentService private environmentService: IEnvironmentService,
@IContextKeyService contextKeyService: IContextKeyService
) {
super(SettingsEditor2.ID, telemetryService, themeService);
this.delayedFilterLogging = new Delayer<void>(1000);
this.localSearchDelayer = new Delayer(100);
this.remoteSearchThrottle = new ThrottledDelayer(200);
this.viewState = { settingsTarget: ConfigurationTarget.USER };
this.settingUpdateDelayer = new Delayer<void>(500);
this.inSettingsEditorContextKey = CONTEXT_SETTINGS_EDITOR.bindTo(contextKeyService);
this.searchFocusContextKey = CONTEXT_SETTINGS_SEARCH_FOCUS.bindTo(contextKeyService);
this.firstRowFocused = CONTEXT_SETTINGS_FIRST_ROW_FOCUS.bindTo(contextKeyService);
this._register(configurationService.onDidChangeConfiguration(e => {
this.onConfigUpdate();
if (e.affectsConfiguration('workbench.settings.tocVisible')) {
this.updateTOCVisible();
}
}));
}
createEditor(parent: HTMLElement): void {
this.rootElement = DOM.append(parent, $('.settings-editor'));
this.createHeader(this.rootElement);
this.createBody(this.rootElement);
}
setInput(input: SettingsEditor2Input, options: EditorOptions, token: CancellationToken): Thenable<void> {
this.inSettingsEditorContextKey.set(true);
return super.setInput(input, options, token)
.then(() => {
this.render(token);
});
}
clearInput(): void {
this.inSettingsEditorContextKey.set(false);
super.clearInput();
}
layout(dimension: DOM.Dimension): void {
this.searchWidget.layout(dimension);
this.layoutSettingsList(dimension);
}
focus(): void {
this.focusSearch();
}
focusSettings(): void {
const selection = this.settingsTree.getSelection();
if (selection && selection[0]) {
this.settingsTree.setFocus(selection[0]);
} else {
this.settingsTree.focusFirst();
}
this.settingsTree.domFocus();
}
focusSearch(): void {
this.searchWidget.focus();
}
editSelectedSetting(): void {
const focus = this.settingsTree.getFocus();
if (focus instanceof SettingsTreeSettingElement) {
const itemId = focus.id.replace(/\./g, '_');
this.focusEditControlForRow(itemId);
}
}
clearSearchResults(): void {
this.searchWidget.clear();
}
private createHeader(parent: HTMLElement): void {
this.headerContainer = DOM.append(parent, $('.settings-header'));
const previewHeader = DOM.append(this.headerContainer, $('.settings-preview-header'));
const previewAlert = DOM.append(previewHeader, $('span.settings-preview-warning'));
previewAlert.textContent = localize('previewWarning', "Preview");
const previewTextLabel = DOM.append(previewHeader, $('span.settings-preview-label'));
previewTextLabel.textContent = localize('previewLabel', "This is a preview of our new settings editor");
const searchContainer = DOM.append(this.headerContainer, $('.search-container'));
this.searchWidget = this._register(this.instantiationService.createInstance(SearchWidget, searchContainer, {
ariaLabel: localize('SearchSettings.AriaLabel', "Search settings"),
placeholder: localize('SearchSettings.Placeholder', "Search settings"),
focusKey: this.searchFocusContextKey
}));
this._register(this.searchWidget.onDidChange(() => this.onSearchInputChanged()));
const advancedCustomization = DOM.append(this.headerContainer, $('.settings-advanced-customization'));
const advancedCustomizationLabel = DOM.append(advancedCustomization, $('span.settings-advanced-customization-label'));
advancedCustomizationLabel.textContent = localize('advancedCustomizationLabel', "For advanced customizations open and edit") + ' ';
const openSettingsButton = this._register(new Button(advancedCustomization, { title: true, buttonBackground: null, buttonHoverBackground: null }));
this._register(attachButtonStyler(openSettingsButton, this.themeService, {
buttonBackground: Color.transparent.toString(),
buttonHoverBackground: Color.transparent.toString(),
buttonForeground: foreground
}));
openSettingsButton.label = localize('openSettingsLabel', "settings.json");
openSettingsButton.element.classList.add('open-settings-button');
this._register(openSettingsButton.onDidClick(() => this.openSettingsFile()));
const headerControlsContainer = DOM.append(this.headerContainer, $('.settings-header-controls'));
const targetWidgetContainer = DOM.append(headerControlsContainer, $('.settings-target-container'));
this.settingsTargetsWidget = this._register(this.instantiationService.createInstance(SettingsTargetsWidget, targetWidgetContainer));
this.settingsTargetsWidget.settingsTarget = ConfigurationTarget.USER;
this.settingsTargetsWidget.onDidTargetChange(() => {
this.viewState.settingsTarget = this.settingsTargetsWidget.settingsTarget;
this.settingsTreeModel.update();
this.refreshTreeAndMaintainFocus();
});
this.createHeaderControls(headerControlsContainer);
}
private createHeaderControls(parent: HTMLElement): void {
const headerControlsContainerRight = DOM.append(parent, $('.settings-header-controls-right'));
this.showConfiguredSettingsOnlyCheckbox = DOM.append(headerControlsContainerRight, $('input#configured-only-checkbox'));
this.showConfiguredSettingsOnlyCheckbox.type = 'checkbox';
const showConfiguredSettingsOnlyLabel = <HTMLLabelElement>DOM.append(headerControlsContainerRight, $('label.configured-only-label'));
showConfiguredSettingsOnlyLabel.textContent = localize('showOverriddenOnly', "Show modified only");
showConfiguredSettingsOnlyLabel.htmlFor = 'configured-only-checkbox';
this._register(DOM.addDisposableListener(this.showConfiguredSettingsOnlyCheckbox, 'change', e => this.onShowConfiguredOnlyClicked()));
}
private openSettingsFile(): TPromise<IEditor> {
const currentSettingsTarget = this.settingsTargetsWidget.settingsTarget;
if (currentSettingsTarget === ConfigurationTarget.USER) {
return this.preferencesService.openGlobalSettings();
} else if (currentSettingsTarget === ConfigurationTarget.WORKSPACE) {
return this.preferencesService.openWorkspaceSettings();
} else {
return this.preferencesService.openFolderSettings(currentSettingsTarget);
}
}
private createBody(parent: HTMLElement): void {
const bodyContainer = DOM.append(parent, $('.settings-body'));
this.createTOC(bodyContainer);
this.createSettingsTree(bodyContainer);
if (this.environmentService.appQuality !== 'stable') {
this.createFeedbackButton(bodyContainer);
}
}
private createTOC(parent: HTMLElement): void {
this.tocTreeContainer = DOM.append(parent, $('.settings-toc-container'));
const tocDataSource = this.instantiationService.createInstance(TOCDataSource);
const tocRenderer = this.instantiationService.createInstance(TOCRenderer);
this.tocTreeModel = new TOCTreeModel();
this.tocTree = this.instantiationService.createInstance(WorkbenchTree, this.tocTreeContainer,
<ITreeConfiguration>{
dataSource: tocDataSource,
renderer: tocRenderer,
controller: this.instantiationService.createInstance(WorkbenchTreeController, { openMode: OpenMode.DOUBLE_CLICK }),
filter: this.instantiationService.createInstance(SettingsTreeFilter, this.viewState)
},
{
showLoading: false,
twistiePixels: 15
});
this._register(this.tocTree.onDidChangeSelection(e => {
if (this.searchResultModel) {
const element = e.selection[0];
this.viewState.filterToCategory = element;
this.refreshTreeAndMaintainFocus();
} else if (this.settingsTreeModel) {
const element = e.selection[0];
if (element && !e.payload.fromScroll) {
this.settingsTree.reveal(element, 0);
this.settingsTree.setSelection([element]);
this.settingsTree.setFocus(element);
this.settingsTree.domFocus();
}
}
}));
this.updateTOCVisible();
}
private updateTOCVisible(): void {
const visible = !!this.configurationService.getValue('workbench.settings.tocVisible');
DOM.toggleClass(this.tocTreeContainer, 'hidden', !visible);
}
private createSettingsTree(parent: HTMLElement): void {
this.settingsTreeContainer = DOM.append(parent, $('.settings-tree-container'));
this.treeDataSource = this.instantiationService.createInstance(SettingsDataSource, this.viewState);
const renderer = this.instantiationService.createInstance(SettingsRenderer, this.settingsTreeContainer);
this._register(renderer.onDidChangeSetting(e => this.onDidChangeSetting(e.key, e.value)));
this._register(renderer.onDidOpenSettings(() => this.openSettingsFile()));
const treeClass = 'settings-editor-tree';
this.settingsTree = this.instantiationService.createInstance(NonExpandableTree, this.settingsTreeContainer,
<ITreeConfiguration>{
dataSource: this.treeDataSource,
renderer,
controller: this.instantiationService.createInstance(SettingsTreeController),
accessibilityProvider: this.instantiationService.createInstance(SettingsAccessibilityProvider),
filter: this.instantiationService.createInstance(SettingsTreeFilter, this.viewState),
styler: new DefaultTreestyler(DOM.createStyleSheet(), treeClass)
},
{
ariaLabel: localize('treeAriaLabel', "Settings"),
showLoading: false,
indentPixels: 0,
twistiePixels: 0,
});
this._register(registerThemingParticipant((theme: ITheme, collector: ICssStyleCollector) => {
const activeBorderColor = theme.getColor(listActiveSelectionBackground);
if (activeBorderColor) {
collector.addRule(`.settings-editor > .settings-body > .settings-tree-container .monaco-tree:focus .monaco-tree-row.focused {outline: solid 1px ${activeBorderColor}; outline-offset: -1px; }`);
}
const inactiveBorderColor = theme.getColor(listInactiveSelectionBackground);
if (inactiveBorderColor) {
collector.addRule(`.settings-editor > .settings-body > .settings-tree-container .monaco-tree .monaco-tree-row.focused {outline: solid 1px ${inactiveBorderColor}; outline-offset: -1px; }`);
}
}));
this.settingsTree.getHTMLElement().classList.add(treeClass);
this._register(attachStyler(this.themeService, {
listActiveSelectionBackground: editorBackground,
listActiveSelectionForeground: foreground,
listFocusAndSelectionBackground: editorBackground,
listFocusAndSelectionForeground: foreground,
listFocusBackground: editorBackground,
listFocusForeground: foreground,
listHoverForeground: foreground,
listHoverBackground: editorBackground,
listInactiveSelectionBackground: editorBackground,
listInactiveSelectionForeground: foreground
}, colors => {
this.settingsTree.style(colors);
}));
this._register(this.settingsTree.onDidChangeFocus(e => {
this.settingsTree.setSelection([e.focus]);
if (this.selectedElement) {
this.settingsTree.refresh(this.selectedElement);
}
if (e.focus) {
this.settingsTree.refresh(e.focus);
}
this.selectedElement = e.focus;
}));
this._register(this.settingsTree.onDidChangeSelection(e => {
this.updateTreeScrollSync();
let firstRowFocused = false;
const selection: SettingsTreeElement = e.selection[0];
if (selection) {
if (this.searchResultModel) {
firstRowFocused = selection.id === this.searchResultModel.getChildren()[0].id;
} else {
const firstRowId = this.settingsTreeModel.root.children[0] && this.settingsTreeModel.root.children[0].id;
firstRowFocused = selection.id === firstRowId;
}
}
this.firstRowFocused.set(firstRowFocused);
}));
this._register(this.settingsTree.onDidScroll(() => {
this.updateTreeScrollSync();
}));
}
private createFeedbackButton(parent: HTMLElement): void {
const feedbackButton = this._register(new Button(parent));
feedbackButton.label = localize('feedbackButtonLabel', "Provide Feedback");
feedbackButton.element.classList.add('settings-feedback-button');
this._register(attachButtonStyler(feedbackButton, this.themeService));
this._register(feedbackButton.onDidClick(() => {
// Github master issue
window.open('https://go.microsoft.com/fwlink/?linkid=2000807');
}));
}
private onShowConfiguredOnlyClicked(): void {
this.viewState.showConfiguredOnly = this.showConfiguredSettingsOnlyCheckbox.checked;
this.refreshTreeAndMaintainFocus();
this.tocTree.refresh();
this.settingsTree.setScrollPosition(0);
this.expandAll(this.settingsTree);
}
private onDidChangeSetting(key: string, value: any): void {
if (this.pendingSettingUpdate && this.pendingSettingUpdate.key !== key) {
this.updateChangedSetting(key, value);
}
this.pendingSettingUpdate = { key, value };
this.settingUpdateDelayer.trigger(() => this.updateChangedSetting(key, value));
}
private updateTreeScrollSync(): void {
if (this.searchResultModel) {
return;
}
if (!this.tocTree.getInput()) {
return;
}
let elementToSync = this.settingsTree.getFirstVisibleElement();
const selection = this.settingsTree.getSelection()[0];
if (selection) {
const selectionPos = this.settingsTree.getRelativeTop(selection);
if (selectionPos >= 0 && selectionPos <= 1) {
elementToSync = selection;
}
}
const element = elementToSync instanceof SettingsTreeSettingElement ? elementToSync.parent :
elementToSync instanceof SettingsTreeGroupElement ? elementToSync :
null;
if (element && this.tocTree.getSelection()[0] !== element) {
const elementTop = this.tocTree.getRelativeTop(element);
if (elementTop < 0) {
this.tocTree.reveal(element, 0);
} else if (elementTop > 1) {
this.tocTree.reveal(element, 1);
}
this.tocTree.setSelection([element], { fromScroll: true });
this.tocTree.setFocus(element);
}
}
private updateChangedSetting(key: string, value: any): TPromise<void> {
// ConfigurationService displays the error if this fails.
// Force a render afterwards because onDidConfigurationUpdate doesn't fire if the update doesn't result in an effective setting value change
const settingsTarget = this.settingsTargetsWidget.settingsTarget;
const resource = URI.isUri(settingsTarget) ? settingsTarget : undefined;
const configurationTarget = <ConfigurationTarget>(resource ? undefined : settingsTarget);
const overrides: IConfigurationOverrides = { resource };
// If the user is changing the value back to the default, do a 'reset' instead
const inspected = this.configurationService.inspect(key, overrides);
if (inspected.default === value) {
value = undefined;
}
return this.configurationService.updateValue(key, value, overrides, configurationTarget)
.then(() => this.refreshTreeAndMaintainFocus())
.then(() => {
const reportModifiedProps = {
key,
query: this.searchWidget.getValue(),
searchResults: this.searchResultModel && this.searchResultModel.getUniqueResults(),
rawResults: this.searchResultModel && this.searchResultModel.getRawResults(),
showConfiguredOnly: this.viewState.showConfiguredOnly,
isReset: typeof value === 'undefined',
settingsTarget: this.settingsTargetsWidget.settingsTarget as SettingsTarget
};
return this.reportModifiedSetting(reportModifiedProps);
});
}
private reportModifiedSetting(props: { key: string, query: string, searchResults: ISearchResult[], rawResults: ISearchResult[], showConfiguredOnly: boolean, isReset: boolean, settingsTarget: SettingsTarget }): void {
this.pendingSettingUpdate = null;
const remoteResult = props.searchResults && props.searchResults[SearchResultIdx.Remote];
const localResult = props.searchResults && props.searchResults[SearchResultIdx.Local];
let groupId = undefined;
let nlpIndex = undefined;
let displayIndex = undefined;
if (props.searchResults) {
const localIndex = arrays.firstIndex(localResult.filterMatches, m => m.setting.key === props.key);
groupId = localIndex >= 0 ?
'local' :
'remote';
displayIndex = localIndex >= 0 ?
localIndex :
remoteResult && (arrays.firstIndex(remoteResult.filterMatches, m => m.setting.key === props.key) + localResult.filterMatches.length);
if (this.searchResultModel) {
const rawResults = this.searchResultModel.getRawResults();
if (rawResults[SearchResultIdx.Remote]) {
const _nlpIndex = arrays.firstIndex(rawResults[SearchResultIdx.Remote].filterMatches, m => m.setting.key === props.key);
nlpIndex = _nlpIndex >= 0 ? _nlpIndex : undefined;
}
}
}
const reportedTarget = props.settingsTarget === ConfigurationTarget.USER ? 'user' :
props.settingsTarget === ConfigurationTarget.WORKSPACE ? 'workspace' :
'folder';
const data = {
key: props.key,
query: props.query,
groupId,
nlpIndex,
displayIndex,
showConfiguredOnly: props.showConfiguredOnly,
isReset: props.isReset,
target: reportedTarget
};
/* __GDPR__
"settingsEditor.settingModified" : {
"key" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" },
"query" : { "classification": "CustomerContent", "purpose": "FeatureInsight" },
"groupId" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" },
"nlpIndex" : { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true },
"displayIndex" : { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true },
"showConfiguredOnly" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" },
"isReset" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" },
"target" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" }
}
*/
this.telemetryService.publicLog('settingsEditor.settingModified', data);
}
private render(token: CancellationToken): TPromise<any> {
if (this.input) {
return this.input.resolve()
.then((model: DefaultSettingsEditorModel) => {
if (token.isCancellationRequested) {
return void 0;
}
this.defaultSettingsEditorModel = model;
this.onConfigUpdate();
});
}
return TPromise.as(null);
}
private toggleSearchMode(): void {
DOM.removeClass(this.rootElement, 'search-mode');
if (this.configurationService.getValue('workbench.settings.settingsSearchTocBehavior') === 'hide') {
DOM.toggleClass(this.rootElement, 'search-mode', !!this.searchResultModel);
}
}
private onConfigUpdate(): TPromise<void> {
const groups = this.defaultSettingsEditorModel.settingsGroups.slice(1); // Without commonlyUsed
const dividedGroups = collections.groupBy(groups, g => g.contributedByExtension ? 'extension' : 'core');
const resolvedSettingsRoot = resolveSettingsTree(tocData, dividedGroups.core);
const commonlyUsed = resolveSettingsTree(commonlyUsedData, dividedGroups.core);
resolvedSettingsRoot.children.unshift(commonlyUsed);
resolvedSettingsRoot.children.push(resolveExtensionsSettings(dividedGroups.extension || []));
if (this.settingsTreeModel) {
this.settingsTreeModel.update(resolvedSettingsRoot);
} else {
this.settingsTreeModel = this.instantiationService.createInstance(SettingsTreeModel, this.viewState, resolvedSettingsRoot);
this.settingsTree.setInput(this.settingsTreeModel.root);
this.tocTreeModel.settingsTreeRoot = this.settingsTreeModel.root as SettingsTreeGroupElement;
if (this.tocTree.getInput()) {
this.tocTree.refresh();
} else {
this.tocTree.setInput(this.tocTreeModel);
}
}
return this.refreshTreeAndMaintainFocus();
}
private refreshTreeAndMaintainFocus(): TPromise<any> {
// Sort of a hack to maintain focus on the focused control across a refresh
const focusedRowItem = DOM.findParentWithClass(<HTMLElement>document.activeElement, 'setting-item');
const focusedRowId = focusedRowItem && focusedRowItem.id;
const selection = focusedRowId && document.activeElement.tagName.toLowerCase() === 'input' ?
(<HTMLInputElement>document.activeElement).selectionStart :
null;
return this.settingsTree.refresh()
.then(() => {
if (focusedRowId) {
this.focusEditControlForRow(focusedRowId, selection);
}
})
.then(() => {
return this.tocTree.refresh();
});
}
private focusEditControlForRow(id: string, selection?: number): void {
const rowSelector = `.setting-item#${id}`;
const inputElementToFocus: HTMLElement = this.settingsTreeContainer.querySelector(`${rowSelector} input, ${rowSelector} select, ${rowSelector} a, ${rowSelector} .monaco-custom-checkbox`);
if (inputElementToFocus) {
inputElementToFocus.focus();
if (typeof selection === 'number') {
(<HTMLInputElement>inputElementToFocus).setSelectionRange(selection, selection);
}
}
}
private onSearchInputChanged(): void {
const query = this.searchWidget.getValue().trim();
this.delayedFilterLogging.cancel();
this.triggerSearch(query).then(() => {
if (query && this.searchResultModel) {
this.delayedFilterLogging.trigger(() => this.reportFilteringUsed(query, this.searchResultModel.getUniqueResults()));
}
});
}
private triggerSearch(query: string): TPromise<void> {
if (query) {
return this.searchInProgress = TPromise.join([
this.localSearchDelayer.trigger(() => this.localFilterPreferences(query)),
this.remoteSearchThrottle.trigger(() => this.remoteSearchPreferences(query), 500)
]).then(() => {
this.searchInProgress = null;
});
} else {
this.localSearchDelayer.cancel();
this.remoteSearchThrottle.cancel();
if (this.searchInProgress && this.searchInProgress.cancel) {
this.searchInProgress.cancel();
}
this.searchResultModel = null;
this.tocTreeModel.currentSearchModel = null;
this.viewState.filterToCategory = null;
this.tocTree.refresh();
this.toggleSearchMode();
this.settingsTree.setInput(this.settingsTreeModel.root);
return TPromise.wrap(null);
}
}
private expandAll(tree: ITree): void {
const nav = tree.getNavigator();
let cur;
while (cur = nav.next()) {
tree.expand(cur);
}
}
private reportFilteringUsed(query: string, results: ISearchResult[]): void {
const nlpResult = results[SearchResultIdx.Remote];
const nlpMetadata = nlpResult && nlpResult.metadata;
const durations = {};
durations['nlpResult'] = nlpMetadata && nlpMetadata.duration;
// Count unique results
const counts = {};
const filterResult = results[SearchResultIdx.Local];
counts['filterResult'] = filterResult.filterMatches.length;
if (nlpResult) {
counts['nlpResult'] = nlpResult.filterMatches.length;
}
const requestCount = nlpMetadata && nlpMetadata.requestCount;
const data = {
query,
durations,
counts,
requestCount
};
/* __GDPR__
"settingsEditor.filter" : {
"query": { "classification": "CustomerContent", "purpose": "FeatureInsight" },
"durations.nlpResult" : { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true },
"counts.nlpResult" : { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true },
"counts.filterResult" : { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true },
"requestCount" : { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }
}
*/
this.telemetryService.publicLog('settingsEditor.filter', data);
}
private localFilterPreferences(query: string): TPromise<void> {
const localSearchProvider = this.preferencesSearchService.getLocalSearchProvider(query);
return this.filterOrSearchPreferences(query, SearchResultIdx.Local, localSearchProvider);
}
private remoteSearchPreferences(query: string): TPromise<void> {
const remoteSearchProvider = this.preferencesSearchService.getRemoteSearchProvider(query);
return this.filterOrSearchPreferences(query, SearchResultIdx.Remote, remoteSearchProvider);
}
private filterOrSearchPreferences(query: string, type: SearchResultIdx, searchProvider: ISearchProvider): TPromise<void> {
const filterPs: TPromise<ISearchResult>[] = [this._filterOrSearchPreferencesModel(query, this.defaultSettingsEditorModel, searchProvider)];
let isCanceled = false;
return new TPromise(resolve => {
return TPromise.join(filterPs).then(results => {
if (isCanceled) {
// Handle cancellation like this because cancellation is lost inside the search provider due to async/await
return null;
}
const [result] = results;
if (!this.searchResultModel) {
this.searchResultModel = this.instantiationService.createInstance(SearchResultModel, this.viewState);
this.searchResultModel.setResult(type, result);
this.tocTreeModel.currentSearchModel = this.searchResultModel;
this.toggleSearchMode();
this.settingsTree.setInput(this.searchResultModel);
} else {
this.searchResultModel.setResult(type, result);
}
this.tocTreeModel.update();
resolve(this.refreshTreeAndMaintainFocus());
});
}, () => {
isCanceled = true;
});
}
private _filterOrSearchPreferencesModel(filter: string, model: ISettingsEditorModel, provider: ISearchProvider): TPromise<ISearchResult> {
const searchP = provider ? provider.searchModel(model) : TPromise.wrap(null);
return searchP
.then<ISearchResult>(null, err => {
if (isPromiseCanceledError(err)) {
return TPromise.wrapError(err);
} else {
/* __GDPR__
"settingsEditor.searchError" : {
"message": { "classification": "CallstackOrException", "purpose": "FeatureInsight" },
"filter": { "classification": "SystemMetaData", "purpose": "FeatureInsight" }
}
*/
const message = getErrorMessage(err).trim();
if (message && message !== 'Error') {
// "Error" = any generic network error
this.telemetryService.publicLog('settingsEditor.searchError', { message, filter });
this.logService.info('Setting search error: ' + message);
}
return null;
}
});
}
private layoutSettingsList(dimension: DOM.Dimension): void {
const listHeight = dimension.height - (DOM.getDomNodePagePosition(this.headerContainer).height + 12 /*padding*/);
this.settingsTreeContainer.style.height = `${listHeight}px`;
this.settingsTree.layout(listHeight, 800);
const tocHeight = listHeight - 5; // padding
this.tocTreeContainer.style.height = `${tocHeight}px`;
this.tocTree.layout(tocHeight, 175);
}
}
| src/vs/workbench/parts/preferences/browser/settingsEditor2.ts | 1 | https://github.com/microsoft/vscode/commit/3d688527f93a1077a23032c55a829f3f4078d0db | [
0.023323575034737587,
0.0005177342682145536,
0.0001621028350200504,
0.00016923459770623595,
0.0026282519102096558
] |
{
"id": 2,
"code_window": [
"\n",
"\t\t// Recompute children\n",
"\t\tthis.children = this.getFlatSettings()\n"
],
"labels": [
"keep",
"replace",
"keep"
],
"after_edit": [
"\tupdateChildren(): void {\n"
],
"file_path": "src/vs/workbench/parts/preferences/browser/settingsTree.ts",
"type": "replace",
"edit_start_line_idx": 910
} | {
"": [
"--------------------------------------------------------------------------------------------",
"Copyright (c) Microsoft Corporation. All rights reserved.",
"Licensed under the MIT License. See License.txt in the project root for license information.",
"--------------------------------------------------------------------------------------------",
"Do not edit this file. It is machine generated."
],
"extensionsDisabled": "Alle Erweiterungen sind deaktiviert.",
"extensionHostProcess.crash": "Der Erweiterungshost wurde unerwartet beendet.",
"extensionHostProcess.unresponsiveCrash": "Der Erweiterungshost wurde beendet, weil er nicht reagiert hat.",
"devTools": "Entwicklertools öffnen",
"restart": "Erweiterungshost neu starten",
"overwritingExtension": "Die Erweiterung \"{0}\" wird mit \"{1}\" überschrieben.",
"extensionUnderDevelopment": "Die Entwicklungserweiterung unter \"{0}\" wird geladen.",
"extensionCache.invalid": "Erweiterungen wurden auf der Festplatte geändert. Bitte laden Sie das Fenster erneut.",
"reloadWindow": "Fenster erneut laden"
} | i18n/deu/src/vs/workbench/services/extensions/electron-browser/extensionService.i18n.json | 0 | https://github.com/microsoft/vscode/commit/3d688527f93a1077a23032c55a829f3f4078d0db | [
0.00017393211601302028,
0.00017036979261320084,
0.0001668074692133814,
0.00017036979261320084,
0.0000035623233998194337
] |
{
"id": 2,
"code_window": [
"\n",
"\t\t// Recompute children\n",
"\t\tthis.children = this.getFlatSettings()\n"
],
"labels": [
"keep",
"replace",
"keep"
],
"after_edit": [
"\tupdateChildren(): void {\n"
],
"file_path": "src/vs/workbench/parts/preferences/browser/settingsTree.ts",
"type": "replace",
"edit_start_line_idx": 910
} | {
"": [
"--------------------------------------------------------------------------------------------",
"Copyright (c) Microsoft Corporation. All rights reserved.",
"Licensed under the MIT License. See License.txt in the project root for license information.",
"--------------------------------------------------------------------------------------------",
"Do not edit this file. It is machine generated."
],
"textEditor": "Editor de Texto",
"textDiffEditor": "Editor de Diferentes Textos",
"binaryDiffEditor": "Editor de Diferença Binária",
"sideBySideEditor": "Editor Lado a lado",
"groupOnePicker": "Mostrar editores no primeiro grupo",
"groupTwoPicker": "Mostrar editores no segundo grupo",
"groupThreePicker": "Mostrar editores no terceiro grupo",
"allEditorsPicker": "Mostrar todos editores abertos",
"view": "Exibir",
"file": "Arquivo",
"close": "Fechar",
"closeOthers": "Fechar Outros",
"closeRight": "Fechar à direita",
"closeAllSaved": "Fechar Salvos",
"closeAll": "Fechar todos",
"keepOpen": "Manter aberto",
"toggleInlineView": "Alternar para exibição embutida",
"showOpenedEditors": "Mostrar editores abertos",
"keepEditor": "Manter editor",
"closeEditorsInGroup": "Fechar todos editores no grupo",
"closeSavedEditors": "Fechar Editores Salvos em Grupo",
"closeOtherEditors": "Fechar outros editores",
"closeRightEditors": "Fechar editores à direita"
} | i18n/ptb/src/vs/workbench/browser/parts/editor/editor.contribution.i18n.json | 0 | https://github.com/microsoft/vscode/commit/3d688527f93a1077a23032c55a829f3f4078d0db | [
0.0001761809689924121,
0.00017331380513496697,
0.00017000397201627493,
0.00017353513976559043,
0.000002855286084013642
] |
{
"id": 2,
"code_window": [
"\n",
"\t\t// Recompute children\n",
"\t\tthis.children = this.getFlatSettings()\n"
],
"labels": [
"keep",
"replace",
"keep"
],
"after_edit": [
"\tupdateChildren(): void {\n"
],
"file_path": "src/vs/workbench/parts/preferences/browser/settingsTree.ts",
"type": "replace",
"edit_start_line_idx": 910
} | <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><defs><style>.icon-canvas-transparent,.icon-vs-out{fill:#2d2d30;}.icon-canvas-transparent{opacity:0;}.icon-vs-bg{fill:#c5c5c5;}</style></defs><title>ExpandChevronRight_md_16x</title><path class="icon-canvas-transparent" d="M16,0V16H0V0Z"/><path class="icon-vs-out" d="M13.225,8,5.78,15.444,3.306,12.97,8.275,8,3.306,3.03,5.78.556Z" style="display: none;"/><path class="icon-vs-bg" d="M11.811,8,5.78,14.03,4.72,12.97,9.689,8,4.72,3.03,5.78,1.97Z"/></svg> | src/vs/workbench/browser/parts/panel/media/right-inverse.svg | 0 | https://github.com/microsoft/vscode/commit/3d688527f93a1077a23032c55a829f3f4078d0db | [
0.00016824509657453746,
0.00016824509657453746,
0.00016824509657453746,
0.00016824509657453746,
0
] |
{
"id": 3,
"code_window": [
"\t\tthis.children = this.getFlatSettings()\n",
"\t\t\t.map(s => createSettingsTreeSettingElement(s, result, this._viewState.settingsTarget, this._configurationService));\n",
"\t}\n",
"\n",
"\tprivate getFlatSettings(): ISetting[] {\n"
],
"labels": [
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t.map(s => createSettingsTreeSettingElement(s, this, this._viewState.settingsTarget, this._configurationService));\n"
],
"file_path": "src/vs/workbench/parts/preferences/browser/settingsTree.ts",
"type": "replace",
"edit_start_line_idx": 912
} | /*---------------------------------------------------------------------------------------------
* 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 { StandardKeyboardEvent } from 'vs/base/browser/keyboardEvent';
import { IMouseEvent } from 'vs/base/browser/mouseEvent';
import { Button } from 'vs/base/browser/ui/button/button';
import { Checkbox } from 'vs/base/browser/ui/checkbox/checkbox';
import { InputBox } from 'vs/base/browser/ui/inputbox/inputBox';
import { SelectBox } from 'vs/base/browser/ui/selectBox/selectBox';
import * as arrays from 'vs/base/common/arrays';
import { Color } from 'vs/base/common/color';
import { Emitter, Event } from 'vs/base/common/event';
import { KeyCode } from 'vs/base/common/keyCodes';
import { dispose, IDisposable } from 'vs/base/common/lifecycle';
import * as objects from 'vs/base/common/objects';
import { escapeRegExpCharacters } from 'vs/base/common/strings';
import URI from 'vs/base/common/uri';
import { TPromise } from 'vs/base/common/winjs.base';
import { IAccessibilityProvider, IDataSource, IFilter, IRenderer, ITree } from 'vs/base/parts/tree/browser/tree';
import { localize } from 'vs/nls';
import { ConfigurationTarget, IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { IContextViewService } from 'vs/platform/contextview/browser/contextView';
import { WorkbenchTree, WorkbenchTreeController } from 'vs/platform/list/browser/listService';
import { registerColor, selectBackground, selectBorder } from 'vs/platform/theme/common/colorRegistry';
import { attachButtonStyler, attachInputBoxStyler, attachSelectBoxStyler } from 'vs/platform/theme/common/styler';
import { ICssStyleCollector, ITheme, IThemeService, registerThemingParticipant } from 'vs/platform/theme/common/themeService';
import { SettingsTarget } from 'vs/workbench/parts/preferences/browser/preferencesWidgets';
import { ITOCEntry } from 'vs/workbench/parts/preferences/browser/settingsLayout';
import { ISearchResult, ISetting, ISettingsGroup } from 'vs/workbench/services/preferences/common/preferences';
const $ = DOM.$;
export const modifiedItemForeground = registerColor('settings.modifiedItemForeground', {
light: '#019001',
dark: '#73C991',
hc: '#73C991'
}, localize('modifiedItemForeground', "(For settings editor preview) The foreground color for a modified setting."));
registerThemingParticipant((theme: ITheme, collector: ICssStyleCollector) => {
const modifiedItemForegroundColor = theme.getColor(modifiedItemForeground);
if (modifiedItemForegroundColor) {
collector.addRule(`.settings-editor > .settings-body > .settings-tree-container .setting-item.is-configured .setting-item-is-configured-label { color: ${modifiedItemForegroundColor}; }`);
}
});
registerThemingParticipant((theme: ITheme, collector: ICssStyleCollector) => {
// TODO@roblou Hacks! Make checkbox background themeable
const selectBackgroundColor = theme.getColor(selectBackground);
if (selectBackgroundColor) {
collector.addRule(`.settings-editor > .settings-body > .settings-tree-container .setting-item-bool .setting-value-checkbox { background-color: ${selectBackgroundColor} !important; }`);
}
// TODO@roblou Hacks! Use proper inputbox theming instead of !important
const selectBorderColor = theme.getColor(selectBorder);
if (selectBorderColor) {
collector.addRule(`.settings-editor > .settings-body > .settings-tree-container .setting-item-bool .setting-value-checkbox { border-color: ${selectBorderColor} !important; }`);
collector.addRule(`.settings-editor > .settings-body > .settings-tree-container .setting-item .setting-item-control > .monaco-inputbox { border: solid 1px ${selectBorderColor} !important; }`);
}
});
export abstract class SettingsTreeElement {
id: string;
parent: any; // SearchResultModel or group element... TODO search should be more similar to the normal case
}
export class SettingsTreeGroupElement extends SettingsTreeElement {
children: (SettingsTreeGroupElement | SettingsTreeSettingElement)[];
label: string;
level: number;
}
export class SettingsTreeSettingElement extends SettingsTreeElement {
setting: ISetting;
isExpanded: boolean;
displayCategory: string;
displayLabel: string;
value: any;
isConfigured: boolean;
overriddenScopeList: string[];
description: string;
valueType?: string | string[];
enum?: string[];
}
export interface ITOCEntry {
id: string;
label: string;
children?: ITOCEntry[];
settings?: (string | ISetting)[];
}
export class SettingsTreeModel {
private _root: SettingsTreeGroupElement;
private _treeElementsById = new Map<string, SettingsTreeElement>();
constructor(
private _viewState: ISettingsEditorViewState,
private _tocRoot: ITOCEntry,
@IConfigurationService private _configurationService: IConfigurationService
) {
this.update(this._tocRoot);
}
get root(): SettingsTreeGroupElement {
return this._root;
}
update(newTocRoot = this._tocRoot): void {
const newRoot = this.createSettingsTreeGroupElement(newTocRoot);
if (this._root) {
this._root.children = newRoot.children;
} else {
this._root = newRoot;
}
}
getElementById(id: string): SettingsTreeElement {
return this._treeElementsById.get(id);
}
private createSettingsTreeGroupElement(tocEntry: ITOCEntry, parent?: SettingsTreeGroupElement): SettingsTreeGroupElement {
const element = new SettingsTreeGroupElement();
element.id = tocEntry.id;
element.label = tocEntry.label;
element.parent = parent;
element.level = this.getDepth(element);
if (tocEntry.children) {
element.children = tocEntry.children.map(child => this.createSettingsTreeGroupElement(child, element));
} else if (tocEntry.settings) {
element.children = tocEntry.settings.map(s => this.createSettingsTreeSettingElement(<ISetting>s, element));
}
this._treeElementsById.set(element.id, element);
return element;
}
private getDepth(element: SettingsTreeElement): number {
if (element.parent) {
return 1 + this.getDepth(element.parent);
} else {
return 0;
}
}
private createSettingsTreeSettingElement(setting: ISetting, parent: SettingsTreeGroupElement): SettingsTreeSettingElement {
const element = createSettingsTreeSettingElement(setting, parent, this._viewState.settingsTarget, this._configurationService);
this._treeElementsById.set(element.id, element);
return element;
}
}
function sanitizeId(id: string): string {
return id.replace(/[\.\/]/, '_');
}
function createSettingsTreeSettingElement(setting: ISetting, parent: any, settingsTarget: SettingsTarget, configurationService: IConfigurationService): SettingsTreeSettingElement {
const element = new SettingsTreeSettingElement();
element.id = sanitizeId(parent.id + '_' + setting.key);
element.parent = parent;
const { isConfigured, inspected, targetSelector } = inspectSetting(setting.key, settingsTarget, configurationService);
const displayValue = isConfigured ? inspected[targetSelector] : inspected.default;
const overriddenScopeList = [];
if (targetSelector === 'user' && typeof inspected.workspace !== 'undefined') {
overriddenScopeList.push(localize('workspace', "Workspace"));
}
if (targetSelector === 'workspace' && typeof inspected.user !== 'undefined') {
overriddenScopeList.push(localize('user', "User"));
}
const displayKeyFormat = settingKeyToDisplayFormat(setting.key, parent.id);
element.setting = setting;
element.displayLabel = displayKeyFormat.label;
element.displayCategory = displayKeyFormat.category;
element.isExpanded = false;
element.value = displayValue;
element.isConfigured = isConfigured;
element.overriddenScopeList = overriddenScopeList;
element.description = setting.description.join('\n');
element.enum = setting.enum;
element.valueType = setting.type;
return element;
}
function inspectSetting(key: string, target: SettingsTarget, configurationService: IConfigurationService): { isConfigured: boolean, inspected: any, targetSelector: string } {
const inspectOverrides = URI.isUri(target) ? { resource: target } : undefined;
const inspected = configurationService.inspect(key, inspectOverrides);
const targetSelector = target === ConfigurationTarget.USER ? 'user' :
target === ConfigurationTarget.WORKSPACE ? 'workspace' :
'workspaceFolder';
const isConfigured = typeof inspected[targetSelector] !== 'undefined';
return { isConfigured, inspected, targetSelector };
}
export function resolveSettingsTree(tocData: ITOCEntry, coreSettingsGroups: ISettingsGroup[]): ITOCEntry {
return _resolveSettingsTree(tocData, getFlatSettings(coreSettingsGroups));
}
export function resolveExtensionsSettings(groups: ISettingsGroup[]): ITOCEntry {
const settingsGroupToEntry = (group: ISettingsGroup) => {
const flatSettings = arrays.flatten(
group.sections.map(section => section.settings));
return {
id: group.id,
label: group.title,
settings: flatSettings
};
};
const extGroups = groups
.sort((a, b) => a.title.localeCompare(b.title))
.map(g => settingsGroupToEntry(g));
return {
id: 'extensions',
label: localize('extensions', "Extensions"),
children: extGroups
};
}
function _resolveSettingsTree(tocData: ITOCEntry, allSettings: Set<ISetting>): ITOCEntry {
if (tocData.settings) {
return <ITOCEntry>{
id: tocData.id,
label: tocData.label,
settings: arrays.flatten(tocData.settings.map(pattern => getMatchingSettings(allSettings, <string>pattern)))
};
} else if (tocData.children) {
return <ITOCEntry>{
id: tocData.id,
label: tocData.label,
children: tocData.children.map(child => _resolveSettingsTree(child, allSettings))
};
}
return null;
}
function getMatchingSettings(allSettings: Set<ISetting>, pattern: string): ISetting[] {
const result: ISetting[] = [];
allSettings.forEach(s => {
if (settingMatches(s, pattern)) {
result.push(s);
allSettings.delete(s);
}
});
return result.sort((a, b) => a.key.localeCompare(b.key));
}
function settingMatches(s: ISetting, pattern: string): boolean {
pattern = escapeRegExpCharacters(pattern)
.replace(/\\\*/g, '.*');
const regexp = new RegExp(`^${pattern}`, 'i');
return regexp.test(s.key);
}
function getFlatSettings(settingsGroups: ISettingsGroup[]) {
const result: Set<ISetting> = new Set();
for (let group of settingsGroups) {
for (let section of group.sections) {
for (let s of section.settings) {
result.add(s);
}
}
}
return result;
}
export class SettingsDataSource implements IDataSource {
getId(tree: ITree, element: SettingsTreeElement): string {
return element.id;
}
hasChildren(tree: ITree, element: SettingsTreeElement): boolean {
if (element instanceof SearchResultModel) {
return true;
}
if (element instanceof SettingsTreeGroupElement) {
return true;
}
return false;
}
getChildren(tree: ITree, element: SettingsTreeElement): TPromise<any, any> {
return TPromise.as(this._getChildren(element));
}
private _getChildren(element: SettingsTreeElement): SettingsTreeElement[] {
if (element instanceof SearchResultModel) {
return element.getChildren();
} else if (element instanceof SettingsTreeGroupElement) {
return element.children;
} else {
// No children...
return null;
}
}
getParent(tree: ITree, element: SettingsTreeElement): TPromise<any, any> {
return TPromise.wrap(element.parent);
}
shouldAutoexpand(): boolean {
return true;
}
}
export function settingKeyToDisplayFormat(key: string, groupId = ''): { category: string, label: string } {
let label = wordifyKey(key);
const lastDotIdx = label.lastIndexOf('.');
let category = '';
if (lastDotIdx >= 0) {
category = label.substr(0, lastDotIdx);
label = label.substr(lastDotIdx + 1);
}
groupId = wordifyKey(groupId.replace(/\//g, '.'));
category = trimCategoryForGroup(category, groupId);
return { category, label };
}
function wordifyKey(key: string): string {
return key
.replace(/\.([a-z])/g, (match, p1) => `.${p1.toUpperCase()}`)
.replace(/([a-z])([A-Z])/g, '$1 $2') // fooBar => foo Bar
.replace(/^[a-z]/g, match => match.toUpperCase()); // foo => Foo
}
function trimCategoryForGroup(category: string, groupId: string): string {
const doTrim = forward => {
const parts = groupId.split('.');
while (parts.length) {
const reg = new RegExp(`^${parts.join('\\.')}(\\.|$)`, 'i');
if (reg.test(category)) {
return category.replace(reg, '');
}
if (forward) {
parts.pop();
} else {
parts.shift();
}
}
return null;
};
let trimmed = doTrim(true);
if (trimmed === null) {
trimmed = doTrim(false);
}
if (trimmed === null) {
trimmed = category;
}
return trimmed;
}
export interface ISettingsEditorViewState {
settingsTarget: SettingsTarget;
showConfiguredOnly?: boolean;
filterToCategory?: SettingsTreeGroupElement;
}
interface IDisposableTemplate {
toDispose: IDisposable[];
}
interface ISettingItemTemplate extends IDisposableTemplate {
parent: HTMLElement;
containerElement: HTMLElement;
categoryElement: HTMLElement;
labelElement: HTMLElement;
descriptionElement: HTMLElement;
controlElement: HTMLElement;
isConfiguredElement: HTMLElement;
otherOverridesElement: HTMLElement;
}
interface ISettingBoolItemTemplate extends IDisposableTemplate {
parent: HTMLElement;
onChange?: (newState: boolean) => void;
containerElement: HTMLElement;
categoryElement: HTMLElement;
labelElement: HTMLElement;
descriptionElement: HTMLElement;
checkbox: Checkbox;
isConfiguredElement: HTMLElement;
otherOverridesElement: HTMLElement;
}
interface IGroupTitleTemplate extends IDisposableTemplate {
context?: SettingsTreeGroupElement;
parent: HTMLElement;
}
const SETTINGS_ELEMENT_TEMPLATE_ID = 'settings.entry.template';
const SETTINGS_BOOL_TEMPLATE_ID = 'settings.bool.template';
const SETTINGS_GROUP_ELEMENT_TEMPLATE_ID = 'settings.group.template';
export interface ISettingChangeEvent {
key: string;
value: any; // undefined => reset/unconfigure
}
export class SettingsRenderer implements IRenderer {
private static readonly SETTING_ROW_HEIGHT = 94;
private static readonly SETTING_BOOL_ROW_HEIGHT = 61;
private readonly _onDidChangeSetting: Emitter<ISettingChangeEvent> = new Emitter<ISettingChangeEvent>();
public readonly onDidChangeSetting: Event<ISettingChangeEvent> = this._onDidChangeSetting.event;
private readonly _onDidOpenSettings: Emitter<void> = new Emitter<void>();
public readonly onDidOpenSettings: Event<void> = this._onDidOpenSettings.event;
private measureContainer: HTMLElement;
constructor(
_measureContainer: HTMLElement,
@IThemeService private themeService: IThemeService,
@IContextViewService private contextViewService: IContextViewService
) {
this.measureContainer = DOM.append(_measureContainer, $('.setting-measure-container.monaco-tree-row'));
}
getHeight(tree: ITree, element: SettingsTreeElement): number {
if (element instanceof SettingsTreeGroupElement) {
return 40 + (7 * element.level);
}
if (element instanceof SettingsTreeSettingElement) {
const isSelected = this.elementIsSelected(tree, element);
if (isSelected) {
return this.measureSettingElementHeight(tree, element);
} else {
return this._getUnexpandedSettingHeight(element);
}
}
return 0;
}
_getUnexpandedSettingHeight(element: SettingsTreeSettingElement): number {
if (element.valueType === 'boolean') {
return SettingsRenderer.SETTING_BOOL_ROW_HEIGHT;
} else {
return SettingsRenderer.SETTING_ROW_HEIGHT;
}
}
private measureSettingElementHeight(tree: ITree, element: SettingsTreeSettingElement): number {
const measureHelper = DOM.append(this.measureContainer, $('.setting-measure-helper'));
const templateId = this.getTemplateId(tree, element);
const template = this.renderTemplate(tree, templateId, measureHelper);
this.renderElement(tree, element, templateId, template);
const height = this.measureContainer.offsetHeight;
this.measureContainer.removeChild(this.measureContainer.firstChild);
return Math.max(height, this._getUnexpandedSettingHeight(element));
}
getTemplateId(tree: ITree, element: SettingsTreeElement): string {
if (element instanceof SettingsTreeGroupElement) {
return SETTINGS_GROUP_ELEMENT_TEMPLATE_ID;
}
if (element instanceof SettingsTreeSettingElement) {
if (element.valueType === 'boolean') {
return SETTINGS_BOOL_TEMPLATE_ID;
}
return SETTINGS_ELEMENT_TEMPLATE_ID;
}
return '';
}
renderTemplate(tree: ITree, templateId: string, container: HTMLElement) {
if (templateId === SETTINGS_GROUP_ELEMENT_TEMPLATE_ID) {
return this.renderGroupTitleTemplate(container);
}
if (templateId === SETTINGS_ELEMENT_TEMPLATE_ID) {
return this.renderSettingTemplate(tree, container);
}
if (templateId === SETTINGS_BOOL_TEMPLATE_ID) {
return this.renderSettingBoolTemplate(tree, container);
}
return null;
}
private renderGroupTitleTemplate(container: HTMLElement): IGroupTitleTemplate {
DOM.addClass(container, 'group-title');
const toDispose = [];
const template: IGroupTitleTemplate = {
parent: container,
toDispose
};
return template;
}
private renderSettingTemplate(tree: ITree, container: HTMLElement): ISettingItemTemplate {
DOM.addClass(container, 'setting-item');
const titleElement = DOM.append(container, $('.setting-item-title'));
const categoryElement = DOM.append(titleElement, $('span.setting-item-category'));
const labelElement = DOM.append(titleElement, $('span.setting-item-label'));
const isConfiguredElement = DOM.append(titleElement, $('span.setting-item-is-configured-label'));
const otherOverridesElement = DOM.append(titleElement, $('span.setting-item-overrides'));
const descriptionElement = DOM.append(container, $('.setting-item-description'));
const valueElement = DOM.append(container, $('.setting-item-value'));
const controlElement = DOM.append(valueElement, $('div'));
const resetButtonElement = DOM.append(valueElement, $('.reset-button-container'));
const toDispose = [];
const template: ISettingItemTemplate = {
parent: container,
toDispose,
containerElement: container,
categoryElement,
labelElement,
descriptionElement,
controlElement,
isConfiguredElement,
otherOverridesElement
};
// Prevent clicks from being handled by list
toDispose.push(DOM.addDisposableListener(controlElement, 'mousedown', (e: IMouseEvent) => e.stopPropagation()));
toDispose.push(DOM.addDisposableListener(resetButtonElement, 'mousedown', (e: IMouseEvent) => e.stopPropagation()));
toDispose.push(DOM.addStandardDisposableListener(valueElement, 'keydown', (e: StandardKeyboardEvent) => {
if (e.keyCode === KeyCode.Escape) {
tree.domFocus();
e.browserEvent.stopPropagation();
}
}));
return template;
}
private renderSettingBoolTemplate(tree: ITree, container: HTMLElement): ISettingBoolItemTemplate {
DOM.addClass(container, 'setting-item');
DOM.addClass(container, 'setting-item-bool');
const titleElement = DOM.append(container, $('.setting-item-title'));
const categoryElement = DOM.append(titleElement, $('span.setting-item-category'));
const labelElement = DOM.append(titleElement, $('span.setting-item-label'));
const isConfiguredElement = DOM.append(titleElement, $('span.setting-item-is-configured-label'));
const otherOverridesElement = DOM.append(titleElement, $('span.setting-item-overrides'));
const descriptionAndValueElement = DOM.append(container, $('.setting-item-value-description'));
const controlElement = DOM.append(descriptionAndValueElement, $('.setting-item-bool-control'));
const descriptionElement = DOM.append(descriptionAndValueElement, $('.setting-item-description'));
const toDispose = [];
const checkbox = new Checkbox({ actionClassName: 'setting-value-checkbox', isChecked: true, title: '', inputActiveOptionBorder: null });
controlElement.appendChild(checkbox.domNode);
toDispose.push(checkbox);
toDispose.push(checkbox.onChange(() => {
if (template.onChange) {
template.onChange(checkbox.checked);
}
}));
const template: ISettingBoolItemTemplate = {
parent: container,
toDispose,
containerElement: container,
categoryElement,
labelElement,
checkbox,
descriptionElement,
isConfiguredElement,
otherOverridesElement
};
// Prevent clicks from being handled by list
toDispose.push(DOM.addDisposableListener(controlElement, 'mousedown', (e: IMouseEvent) => e.stopPropagation()));
toDispose.push(DOM.addStandardDisposableListener(controlElement, 'keydown', (e: StandardKeyboardEvent) => {
if (e.keyCode === KeyCode.Escape) {
tree.domFocus();
e.browserEvent.stopPropagation();
}
}));
return template;
}
renderElement(tree: ITree, element: SettingsTreeElement, templateId: string, template: any): void {
if (templateId === SETTINGS_ELEMENT_TEMPLATE_ID) {
return this.renderSettingElement(tree, <SettingsTreeSettingElement>element, template);
}
if (templateId === SETTINGS_BOOL_TEMPLATE_ID) {
return this.renderSettingElement(tree, <SettingsTreeSettingElement>element, template);
}
if (templateId === SETTINGS_GROUP_ELEMENT_TEMPLATE_ID) {
return this.renderGroupElement(<SettingsTreeGroupElement>element, template);
}
}
private renderGroupElement(element: SettingsTreeGroupElement, template: IGroupTitleTemplate): void {
template.parent.innerHTML = '';
const labelElement = DOM.append(template.parent, $('div.settings-group-title-label'));
labelElement.classList.add(`settings-group-level-${element.level}`);
labelElement.textContent = (<SettingsTreeGroupElement>element).label;
}
private elementIsSelected(tree: ITree, element: SettingsTreeElement): boolean {
const selection = tree.getSelection();
const selectedElement: SettingsTreeElement = selection && selection[0];
return selectedElement && selectedElement.id === element.id;
}
private renderSettingElement(tree: ITree, element: SettingsTreeSettingElement, template: ISettingItemTemplate | ISettingBoolItemTemplate): void {
const isSelected = !!this.elementIsSelected(tree, element);
const setting = element.setting;
DOM.toggleClass(template.parent, 'is-configured', element.isConfigured);
DOM.toggleClass(template.parent, 'is-expanded', isSelected);
template.containerElement.id = element.id.replace(/\./g, '_');
const titleTooltip = setting.key;
template.categoryElement.textContent = element.displayCategory && (element.displayCategory + ': ');
template.categoryElement.title = titleTooltip;
template.labelElement.textContent = element.displayLabel;
template.labelElement.title = titleTooltip;
template.descriptionElement.textContent = element.description;
this.renderValue(element, isSelected, <ISettingItemTemplate>template);
template.isConfiguredElement.textContent = element.isConfigured ? localize('configured', "Modified") : '';
if (element.overriddenScopeList.length) {
let otherOverridesLabel = element.isConfigured ?
localize('alsoConfiguredIn', "Also modified in") :
localize('configuredIn', "Modified in");
template.otherOverridesElement.textContent = `(${otherOverridesLabel}: ${element.overriddenScopeList.join(', ')})`;
}
}
private renderValue(element: SettingsTreeSettingElement, isSelected: boolean, template: ISettingItemTemplate | ISettingBoolItemTemplate): void {
const onChange = value => this._onDidChangeSetting.fire({ key: element.setting.key, value });
if (element.valueType === 'boolean') {
this.renderBool(element, isSelected, <ISettingBoolItemTemplate>template, onChange);
} else {
return this._renderValue(element, isSelected, <ISettingItemTemplate>template, onChange);
}
}
private _renderValue(element: SettingsTreeSettingElement, isSelected: boolean, template: ISettingItemTemplate, onChange: (value: any) => void): void {
const valueControlElement = template.controlElement;
valueControlElement.innerHTML = '';
valueControlElement.setAttribute('class', 'setting-item-control');
if (element.enum && (element.valueType === 'string' || !element.valueType)) {
valueControlElement.classList.add('setting-type-enum');
this.renderEnum(element, isSelected, template, valueControlElement, onChange);
} else if (element.valueType === 'string') {
valueControlElement.classList.add('setting-type-string');
this.renderText(element, isSelected, template, valueControlElement, onChange);
} else if (element.valueType === 'number' || element.valueType === 'integer') {
valueControlElement.classList.add('setting-type-number');
const parseFn = element.valueType === 'integer' ? parseInt : parseFloat;
this.renderText(element, isSelected, template, valueControlElement, value => onChange(parseFn(value)));
} else {
valueControlElement.classList.add('setting-type-complex');
this.renderEditInSettingsJson(element, isSelected, template, valueControlElement);
}
}
private renderBool(dataElement: SettingsTreeSettingElement, isSelected: boolean, template: ISettingBoolItemTemplate, onChange: (value: boolean) => void): void {
template.onChange = null;
template.checkbox.checked = dataElement.value;
template.onChange = onChange;
template.checkbox.domNode.tabIndex = isSelected ? 0 : -1;
}
private renderEnum(dataElement: SettingsTreeSettingElement, isSelected: boolean, template: ISettingItemTemplate, element: HTMLElement, onChange: (value: string) => void): void {
const idx = dataElement.enum.indexOf(dataElement.value);
const displayOptions = dataElement.enum.map(escapeInvisibleChars);
const selectBox = new SelectBox(displayOptions, idx, this.contextViewService);
template.toDispose.push(attachSelectBoxStyler(selectBox, this.themeService));
selectBox.render(element);
if (element.firstElementChild) {
element.firstElementChild.setAttribute('tabindex', isSelected ? '0' : '-1');
}
template.toDispose.push(
selectBox.onDidSelect(e => onChange(dataElement.enum[e.index])));
}
private renderText(dataElement: SettingsTreeSettingElement, isSelected: boolean, template: ISettingItemTemplate, element: HTMLElement, onChange: (value: string) => void): void {
const inputBox = new InputBox(element, this.contextViewService);
template.toDispose.push(attachInputBoxStyler(inputBox, this.themeService));
template.toDispose.push(inputBox);
inputBox.value = dataElement.value;
inputBox.inputElement.tabIndex = isSelected ? 0 : -1;
template.toDispose.push(
inputBox.onDidChange(e => onChange(e)));
}
private renderEditInSettingsJson(dataElement: SettingsTreeSettingElement, isSelected: boolean, template: ISettingItemTemplate, element: HTMLElement): void {
const openSettingsButton = new Button(element, { title: true, buttonBackground: null, buttonHoverBackground: null });
openSettingsButton.onDidClick(() => this._onDidOpenSettings.fire());
openSettingsButton.label = localize('editInSettingsJson', "Edit in settings.json");
openSettingsButton.element.classList.add('edit-in-settings-button');
openSettingsButton.element.tabIndex = isSelected ? 0 : -1;
template.toDispose.push(openSettingsButton);
template.toDispose.push(attachButtonStyler(openSettingsButton, this.themeService, {
buttonBackground: Color.transparent.toString(),
buttonHoverBackground: Color.transparent.toString(),
buttonForeground: 'foreground'
}));
}
disposeTemplate(tree: ITree, templateId: string, template: IDisposableTemplate): void {
dispose(template.toDispose);
}
}
function escapeInvisibleChars(enumValue: string): string {
return enumValue && enumValue
.replace(/\n/g, '\\n')
.replace(/\r/g, '\\r');
}
export class SettingsTreeFilter implements IFilter {
constructor(
private viewState: ISettingsEditorViewState,
@IConfigurationService private configurationService: IConfigurationService
) { }
isVisible(tree: ITree, element: SettingsTreeElement): boolean {
if (this.viewState.filterToCategory && element instanceof SettingsTreeSettingElement) {
if (!this.settingContainedInGroup(element.setting, this.viewState.filterToCategory)) {
return false;
}
}
if (element instanceof SettingsTreeSettingElement && this.viewState.showConfiguredOnly) {
return element.isConfigured;
}
if (element instanceof SettingsTreeGroupElement && this.viewState.showConfiguredOnly) {
return this.groupHasConfiguredSetting(element);
}
return true;
}
private settingContainedInGroup(setting: ISetting, group: SettingsTreeGroupElement): boolean {
return group.children.some(child => {
if (child instanceof SettingsTreeGroupElement) {
return this.settingContainedInGroup(setting, child);
} else if (child instanceof SettingsTreeSettingElement) {
return child.setting.key === setting.key;
} else {
return false;
}
});
}
private groupHasConfiguredSetting(element: SettingsTreeGroupElement): boolean {
for (let child of element.children) {
if (child instanceof SettingsTreeSettingElement) {
const { isConfigured } = inspectSetting(child.setting.key, this.viewState.settingsTarget, this.configurationService);
if (isConfigured) {
return true;
}
} else {
if (child instanceof SettingsTreeGroupElement) {
return this.groupHasConfiguredSetting(child);
}
}
}
return false;
}
}
export class SettingsTreeController extends WorkbenchTreeController {
constructor(
@IConfigurationService configurationService: IConfigurationService
) {
super({}, configurationService);
}
}
export class SettingsAccessibilityProvider implements IAccessibilityProvider {
getAriaLabel(tree: ITree, element: SettingsTreeElement): string {
if (!element) {
return '';
}
if (element instanceof SettingsTreeSettingElement) {
return localize('settingRowAriaLabel', "{0} {1}, Setting", element.displayCategory, element.displayLabel);
}
if (element instanceof SettingsTreeGroupElement) {
return localize('groupRowAriaLabel', "{0}, group", element.label);
}
return '';
}
}
export enum SearchResultIdx {
Local = 0,
Remote = 1
}
export class SearchResultModel {
private rawSearchResults: ISearchResult[];
private cachedUniqueSearchResults: ISearchResult[];
private children: SettingsTreeSettingElement[];
readonly id = 'searchResultModel';
constructor(
private _viewState: ISettingsEditorViewState,
@IConfigurationService private _configurationService: IConfigurationService
) { }
getChildren(): SettingsTreeSettingElement[] {
return this.children;
}
getUniqueResults(): ISearchResult[] {
if (this.cachedUniqueSearchResults) {
return this.cachedUniqueSearchResults;
}
if (!this.rawSearchResults) {
return [];
}
const localMatchKeys = new Set();
const localResult = objects.deepClone(this.rawSearchResults[SearchResultIdx.Local]);
if (localResult) {
localResult.filterMatches.forEach(m => localMatchKeys.add(m.setting.key));
}
const remoteResult = objects.deepClone(this.rawSearchResults[SearchResultIdx.Remote]);
if (remoteResult) {
remoteResult.filterMatches = remoteResult.filterMatches.filter(m => !localMatchKeys.has(m.setting.key));
}
this.cachedUniqueSearchResults = [localResult, remoteResult];
return this.cachedUniqueSearchResults;
}
getRawResults(): ISearchResult[] {
return this.rawSearchResults;
}
setResult(type: SearchResultIdx, result: ISearchResult): void {
this.cachedUniqueSearchResults = null;
this.rawSearchResults = this.rawSearchResults || [];
if (!result) {
delete this.rawSearchResults[type];
return;
}
this.rawSearchResults[type] = result;
// Recompute children
this.children = this.getFlatSettings()
.map(s => createSettingsTreeSettingElement(s, result, this._viewState.settingsTarget, this._configurationService));
}
private getFlatSettings(): ISetting[] {
const flatSettings: ISetting[] = [];
this.getUniqueResults()
.filter(r => !!r)
.forEach(r => {
flatSettings.push(
...r.filterMatches.map(m => m.setting));
});
return flatSettings;
}
}
export class NonExpandableTree extends WorkbenchTree {
expand(): TPromise<any, any> {
return TPromise.wrap(null);
}
collapse(): TPromise<any, any> {
return TPromise.wrap(null);
}
}
| src/vs/workbench/parts/preferences/browser/settingsTree.ts | 1 | https://github.com/microsoft/vscode/commit/3d688527f93a1077a23032c55a829f3f4078d0db | [
0.9989705085754395,
0.022624928504228592,
0.0001645526645006612,
0.00018303768592886627,
0.14393427968025208
] |
{
"id": 3,
"code_window": [
"\t\tthis.children = this.getFlatSettings()\n",
"\t\t\t.map(s => createSettingsTreeSettingElement(s, result, this._viewState.settingsTarget, this._configurationService));\n",
"\t}\n",
"\n",
"\tprivate getFlatSettings(): ISetting[] {\n"
],
"labels": [
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t.map(s => createSettingsTreeSettingElement(s, this, this._viewState.settingsTarget, this._configurationService));\n"
],
"file_path": "src/vs/workbench/parts/preferences/browser/settingsTree.ts",
"type": "replace",
"edit_start_line_idx": 912
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
import * as nls from 'vs/nls';
import { Disposable, IDisposable, dispose } from 'vs/base/common/lifecycle';
import { KeyCode, KeyMod, KeyChord } from 'vs/base/common/keyCodes';
import { RunOnceScheduler } from 'vs/base/common/async';
import { ScrollType, IEditorContribution } from 'vs/editor/common/editorCommon';
import { FindMatch, TrackedRangeStickiness, OverviewRulerLane, ITextModel } from 'vs/editor/common/model';
import { EditorContextKeys } from 'vs/editor/common/editorContextKeys';
import { registerEditorAction, registerEditorContribution, ServicesAccessor, EditorAction } from 'vs/editor/browser/editorExtensions';
import { Range } from 'vs/editor/common/core/range';
import { Selection } from 'vs/editor/common/core/selection';
import { CursorChangeReason, ICursorSelectionChangedEvent } from 'vs/editor/common/controller/cursorEvents';
import { CursorMoveCommands } from 'vs/editor/common/controller/cursorMoveCommands';
import { RevealTarget } from 'vs/editor/common/controller/cursorCommon';
import { Constants } from 'vs/editor/common/core/uint';
import { DocumentHighlightProviderRegistry } from 'vs/editor/common/modes';
import { CommonFindController } from 'vs/editor/contrib/find/findController';
import { ModelDecorationOptions } from 'vs/editor/common/model/textModel';
import { overviewRulerSelectionHighlightForeground } from 'vs/platform/theme/common/colorRegistry';
import { themeColorFromId } from 'vs/platform/theme/common/themeService';
import { INewFindReplaceState, FindOptionOverride } from 'vs/editor/contrib/find/findState';
import { ICodeEditor } from 'vs/editor/browser/editorBrowser';
export class InsertCursorAbove extends EditorAction {
constructor() {
super({
id: 'editor.action.insertCursorAbove',
label: nls.localize('mutlicursor.insertAbove', "Add Cursor Above"),
alias: 'Add Cursor Above',
precondition: null,
kbOpts: {
kbExpr: EditorContextKeys.editorTextFocus,
primary: KeyMod.CtrlCmd | KeyMod.Alt | KeyCode.UpArrow,
linux: {
primary: KeyMod.Shift | KeyMod.Alt | KeyCode.UpArrow,
secondary: [KeyMod.CtrlCmd | KeyMod.Shift | KeyCode.UpArrow]
}
}
});
}
public run(accessor: ServicesAccessor, editor: ICodeEditor, args: any): void {
const useLogicalLine = (args && args.logicalLine === true);
const cursors = editor._getCursors();
const context = cursors.context;
if (context.config.readOnly) {
return;
}
context.model.pushStackElement();
cursors.setStates(
args.source,
CursorChangeReason.Explicit,
CursorMoveCommands.addCursorUp(context, cursors.getAll(), useLogicalLine)
);
cursors.reveal(true, RevealTarget.TopMost, ScrollType.Smooth);
}
}
export class InsertCursorBelow extends EditorAction {
constructor() {
super({
id: 'editor.action.insertCursorBelow',
label: nls.localize('mutlicursor.insertBelow', "Add Cursor Below"),
alias: 'Add Cursor Below',
precondition: null,
kbOpts: {
kbExpr: EditorContextKeys.editorTextFocus,
primary: KeyMod.CtrlCmd | KeyMod.Alt | KeyCode.DownArrow,
linux: {
primary: KeyMod.Shift | KeyMod.Alt | KeyCode.DownArrow,
secondary: [KeyMod.CtrlCmd | KeyMod.Shift | KeyCode.DownArrow]
}
}
});
}
public run(accessor: ServicesAccessor, editor: ICodeEditor, args: any): void {
const useLogicalLine = (args && args.logicalLine === true);
const cursors = editor._getCursors();
const context = cursors.context;
if (context.config.readOnly) {
return;
}
context.model.pushStackElement();
cursors.setStates(
args.source,
CursorChangeReason.Explicit,
CursorMoveCommands.addCursorDown(context, cursors.getAll(), useLogicalLine)
);
cursors.reveal(true, RevealTarget.BottomMost, ScrollType.Smooth);
}
}
class InsertCursorAtEndOfEachLineSelected extends EditorAction {
constructor() {
super({
id: 'editor.action.insertCursorAtEndOfEachLineSelected',
label: nls.localize('mutlicursor.insertAtEndOfEachLineSelected', "Add Cursors to Line Ends"),
alias: 'Add Cursors to Line Ends',
precondition: null,
kbOpts: {
kbExpr: EditorContextKeys.editorTextFocus,
primary: KeyMod.Shift | KeyMod.Alt | KeyCode.KEY_I
}
});
}
private getCursorsForSelection(selection: Selection, model: ITextModel, result: Selection[]): void {
if (selection.isEmpty()) {
return;
}
for (let i = selection.startLineNumber; i < selection.endLineNumber; i++) {
let currentLineMaxColumn = model.getLineMaxColumn(i);
result.push(new Selection(i, currentLineMaxColumn, i, currentLineMaxColumn));
}
if (selection.endColumn > 1) {
result.push(new Selection(selection.endLineNumber, selection.endColumn, selection.endLineNumber, selection.endColumn));
}
}
public run(accessor: ServicesAccessor, editor: ICodeEditor): void {
const model = editor.getModel();
const selections = editor.getSelections();
let newSelections: Selection[] = [];
selections.forEach((sel) => this.getCursorsForSelection(sel, model, newSelections));
if (newSelections.length > 0) {
editor.setSelections(newSelections);
}
}
}
export class MultiCursorSessionResult {
constructor(
public readonly selections: Selection[],
public readonly revealRange: Range,
public readonly revealScrollType: ScrollType
) { }
}
export class MultiCursorSession {
public static create(editor: ICodeEditor, findController: CommonFindController): MultiCursorSession {
const findState = findController.getState();
// Find widget owns entirely what we search for if:
// - focus is not in the editor (i.e. it is in the find widget)
// - and the search widget is visible
// - and the search string is non-empty
if (!editor.hasTextFocus() && findState.isRevealed && findState.searchString.length > 0) {
// Find widget owns what is searched for
return new MultiCursorSession(editor, findController, false, findState.searchString, findState.wholeWord, findState.matchCase, null);
}
// Otherwise, the selection gives the search text, and the find widget gives the search settings
// The exception is the find state disassociation case: when beginning with a single, collapsed selection
let isDisconnectedFromFindController = false;
let wholeWord: boolean;
let matchCase: boolean;
const selections = editor.getSelections();
if (selections.length === 1 && selections[0].isEmpty()) {
isDisconnectedFromFindController = true;
wholeWord = true;
matchCase = true;
} else {
wholeWord = findState.wholeWord;
matchCase = findState.matchCase;
}
// Selection owns what is searched for
const s = editor.getSelection();
let searchText: string;
let currentMatch: Selection = null;
if (s.isEmpty()) {
// selection is empty => expand to current word
const word = editor.getModel().getWordAtPosition(s.getStartPosition());
if (!word) {
return null;
}
searchText = word.word;
currentMatch = new Selection(s.startLineNumber, word.startColumn, s.startLineNumber, word.endColumn);
} else {
searchText = editor.getModel().getValueInRange(s).replace(/\r\n/g, '\n');
}
return new MultiCursorSession(editor, findController, isDisconnectedFromFindController, searchText, wholeWord, matchCase, currentMatch);
}
constructor(
private readonly _editor: ICodeEditor,
public readonly findController: CommonFindController,
public readonly isDisconnectedFromFindController: boolean,
public readonly searchText: string,
public readonly wholeWord: boolean,
public readonly matchCase: boolean,
public currentMatch: Selection
) { }
public addSelectionToNextFindMatch(): MultiCursorSessionResult {
const nextMatch = this._getNextMatch();
if (!nextMatch) {
return null;
}
const allSelections = this._editor.getSelections();
return new MultiCursorSessionResult(allSelections.concat(nextMatch), nextMatch, ScrollType.Smooth);
}
public moveSelectionToNextFindMatch(): MultiCursorSessionResult {
const nextMatch = this._getNextMatch();
if (!nextMatch) {
return null;
}
const allSelections = this._editor.getSelections();
return new MultiCursorSessionResult(allSelections.slice(0, allSelections.length - 1).concat(nextMatch), nextMatch, ScrollType.Smooth);
}
private _getNextMatch(): Selection {
if (this.currentMatch) {
const result = this.currentMatch;
this.currentMatch = null;
return result;
}
this.findController.highlightFindOptions();
const allSelections = this._editor.getSelections();
const lastAddedSelection = allSelections[allSelections.length - 1];
const nextMatch = this._editor.getModel().findNextMatch(this.searchText, lastAddedSelection.getEndPosition(), false, this.matchCase, this.wholeWord ? this._editor.getConfiguration().wordSeparators : null, false);
if (!nextMatch) {
return null;
}
return new Selection(nextMatch.range.startLineNumber, nextMatch.range.startColumn, nextMatch.range.endLineNumber, nextMatch.range.endColumn);
}
public addSelectionToPreviousFindMatch(): MultiCursorSessionResult {
const previousMatch = this._getPreviousMatch();
if (!previousMatch) {
return null;
}
const allSelections = this._editor.getSelections();
return new MultiCursorSessionResult(allSelections.concat(previousMatch), previousMatch, ScrollType.Smooth);
}
public moveSelectionToPreviousFindMatch(): MultiCursorSessionResult {
const previousMatch = this._getPreviousMatch();
if (!previousMatch) {
return null;
}
const allSelections = this._editor.getSelections();
return new MultiCursorSessionResult(allSelections.slice(0, allSelections.length - 1).concat(previousMatch), previousMatch, ScrollType.Smooth);
}
private _getPreviousMatch(): Selection {
if (this.currentMatch) {
const result = this.currentMatch;
this.currentMatch = null;
return result;
}
this.findController.highlightFindOptions();
const allSelections = this._editor.getSelections();
const lastAddedSelection = allSelections[allSelections.length - 1];
const previousMatch = this._editor.getModel().findPreviousMatch(this.searchText, lastAddedSelection.getStartPosition(), false, this.matchCase, this.wholeWord ? this._editor.getConfiguration().wordSeparators : null, false);
if (!previousMatch) {
return null;
}
return new Selection(previousMatch.range.startLineNumber, previousMatch.range.startColumn, previousMatch.range.endLineNumber, previousMatch.range.endColumn);
}
public selectAll(): FindMatch[] {
this.findController.highlightFindOptions();
return this._editor.getModel().findMatches(this.searchText, true, false, this.matchCase, this.wholeWord ? this._editor.getConfiguration().wordSeparators : null, false, Constants.MAX_SAFE_SMALL_INTEGER);
}
}
export class MultiCursorSelectionController extends Disposable implements IEditorContribution {
private static readonly ID = 'editor.contrib.multiCursorController';
private readonly _editor: ICodeEditor;
private _ignoreSelectionChange: boolean;
private _session: MultiCursorSession;
private _sessionDispose: IDisposable[];
public static get(editor: ICodeEditor): MultiCursorSelectionController {
return editor.getContribution<MultiCursorSelectionController>(MultiCursorSelectionController.ID);
}
constructor(editor: ICodeEditor) {
super();
this._editor = editor;
this._ignoreSelectionChange = false;
this._session = null;
this._sessionDispose = [];
}
public dispose(): void {
this._endSession();
super.dispose();
}
public getId(): string {
return MultiCursorSelectionController.ID;
}
private _beginSessionIfNeeded(findController: CommonFindController): void {
if (!this._session) {
// Create a new session
const session = MultiCursorSession.create(this._editor, findController);
if (!session) {
return;
}
this._session = session;
const newState: INewFindReplaceState = { searchString: this._session.searchText };
if (this._session.isDisconnectedFromFindController) {
newState.wholeWordOverride = FindOptionOverride.True;
newState.matchCaseOverride = FindOptionOverride.True;
newState.isRegexOverride = FindOptionOverride.False;
}
findController.getState().change(newState, false);
this._sessionDispose = [
this._editor.onDidChangeCursorSelection((e) => {
if (this._ignoreSelectionChange) {
return;
}
this._endSession();
}),
this._editor.onDidBlurEditorText(() => {
this._endSession();
}),
findController.getState().onFindReplaceStateChange((e) => {
if (e.matchCase || e.wholeWord) {
this._endSession();
}
})
];
}
}
private _endSession(): void {
this._sessionDispose = dispose(this._sessionDispose);
if (this._session && this._session.isDisconnectedFromFindController) {
const newState: INewFindReplaceState = {
wholeWordOverride: FindOptionOverride.NotSet,
matchCaseOverride: FindOptionOverride.NotSet,
isRegexOverride: FindOptionOverride.NotSet,
};
this._session.findController.getState().change(newState, false);
}
this._session = null;
}
private _setSelections(selections: Selection[]): void {
this._ignoreSelectionChange = true;
this._editor.setSelections(selections);
this._ignoreSelectionChange = false;
}
private _expandEmptyToWord(model: ITextModel, selection: Selection): Selection {
if (!selection.isEmpty()) {
return selection;
}
const word = model.getWordAtPosition(selection.getStartPosition());
if (!word) {
return selection;
}
return new Selection(selection.startLineNumber, word.startColumn, selection.startLineNumber, word.endColumn);
}
private _applySessionResult(result: MultiCursorSessionResult): void {
if (!result) {
return;
}
this._setSelections(result.selections);
if (result.revealRange) {
this._editor.revealRangeInCenterIfOutsideViewport(result.revealRange, result.revealScrollType);
}
}
public getSession(findController: CommonFindController): MultiCursorSession {
return this._session;
}
public addSelectionToNextFindMatch(findController: CommonFindController): void {
if (!this._session) {
// If there are multiple cursors, handle the case where they do not all select the same text.
const allSelections = this._editor.getSelections();
if (allSelections.length > 1) {
const findState = findController.getState();
const matchCase = findState.matchCase;
const selectionsContainSameText = modelRangesContainSameText(this._editor.getModel(), allSelections, matchCase);
if (!selectionsContainSameText) {
const model = this._editor.getModel();
let resultingSelections: Selection[] = [];
for (let i = 0, len = allSelections.length; i < len; i++) {
resultingSelections[i] = this._expandEmptyToWord(model, allSelections[i]);
}
this._editor.setSelections(resultingSelections);
return;
}
}
}
this._beginSessionIfNeeded(findController);
if (this._session) {
this._applySessionResult(this._session.addSelectionToNextFindMatch());
}
}
public addSelectionToPreviousFindMatch(findController: CommonFindController): void {
this._beginSessionIfNeeded(findController);
if (this._session) {
this._applySessionResult(this._session.addSelectionToPreviousFindMatch());
}
}
public moveSelectionToNextFindMatch(findController: CommonFindController): void {
this._beginSessionIfNeeded(findController);
if (this._session) {
this._applySessionResult(this._session.moveSelectionToNextFindMatch());
}
}
public moveSelectionToPreviousFindMatch(findController: CommonFindController): void {
this._beginSessionIfNeeded(findController);
if (this._session) {
this._applySessionResult(this._session.moveSelectionToPreviousFindMatch());
}
}
public selectAll(findController: CommonFindController): void {
let matches: FindMatch[] = null;
const findState = findController.getState();
// Special case: find widget owns entirely what we search for if:
// - focus is not in the editor (i.e. it is in the find widget)
// - and the search widget is visible
// - and the search string is non-empty
// - and we're searching for a regex
if (findState.isRevealed && findState.searchString.length > 0 && findState.isRegex) {
matches = this._editor.getModel().findMatches(findState.searchString, true, findState.isRegex, findState.matchCase, findState.wholeWord ? this._editor.getConfiguration().wordSeparators : null, false, Constants.MAX_SAFE_SMALL_INTEGER);
} else {
this._beginSessionIfNeeded(findController);
if (!this._session) {
return;
}
matches = this._session.selectAll();
}
if (matches.length > 0) {
const editorSelection = this._editor.getSelection();
// Have the primary cursor remain the one where the action was invoked
for (let i = 0, len = matches.length; i < len; i++) {
const match = matches[i];
const intersection = match.range.intersectRanges(editorSelection);
if (intersection) {
// bingo!
matches[i] = matches[0];
matches[0] = match;
break;
}
}
this._setSelections(matches.map(m => new Selection(m.range.startLineNumber, m.range.startColumn, m.range.endLineNumber, m.range.endColumn)));
}
}
}
export abstract class MultiCursorSelectionControllerAction extends EditorAction {
public run(accessor: ServicesAccessor, editor: ICodeEditor): void {
const multiCursorController = MultiCursorSelectionController.get(editor);
if (!multiCursorController) {
return;
}
const findController = CommonFindController.get(editor);
if (!findController) {
return null;
}
this._run(multiCursorController, findController);
}
protected abstract _run(multiCursorController: MultiCursorSelectionController, findController: CommonFindController): void;
}
export class AddSelectionToNextFindMatchAction extends MultiCursorSelectionControllerAction {
constructor() {
super({
id: 'editor.action.addSelectionToNextFindMatch',
label: nls.localize('addSelectionToNextFindMatch', "Add Selection To Next Find Match"),
alias: 'Add Selection To Next Find Match',
precondition: null,
kbOpts: {
kbExpr: EditorContextKeys.focus,
primary: KeyMod.CtrlCmd | KeyCode.KEY_D
}
});
}
protected _run(multiCursorController: MultiCursorSelectionController, findController: CommonFindController): void {
multiCursorController.addSelectionToNextFindMatch(findController);
}
}
export class AddSelectionToPreviousFindMatchAction extends MultiCursorSelectionControllerAction {
constructor() {
super({
id: 'editor.action.addSelectionToPreviousFindMatch',
label: nls.localize('addSelectionToPreviousFindMatch', "Add Selection To Previous Find Match"),
alias: 'Add Selection To Previous Find Match',
precondition: null
});
}
protected _run(multiCursorController: MultiCursorSelectionController, findController: CommonFindController): void {
multiCursorController.addSelectionToPreviousFindMatch(findController);
}
}
export class MoveSelectionToNextFindMatchAction extends MultiCursorSelectionControllerAction {
constructor() {
super({
id: 'editor.action.moveSelectionToNextFindMatch',
label: nls.localize('moveSelectionToNextFindMatch', "Move Last Selection To Next Find Match"),
alias: 'Move Last Selection To Next Find Match',
precondition: null,
kbOpts: {
kbExpr: EditorContextKeys.focus,
primary: KeyChord(KeyMod.CtrlCmd | KeyCode.KEY_K, KeyMod.CtrlCmd | KeyCode.KEY_D)
}
});
}
protected _run(multiCursorController: MultiCursorSelectionController, findController: CommonFindController): void {
multiCursorController.moveSelectionToNextFindMatch(findController);
}
}
export class MoveSelectionToPreviousFindMatchAction extends MultiCursorSelectionControllerAction {
constructor() {
super({
id: 'editor.action.moveSelectionToPreviousFindMatch',
label: nls.localize('moveSelectionToPreviousFindMatch', "Move Last Selection To Previous Find Match"),
alias: 'Move Last Selection To Previous Find Match',
precondition: null
});
}
protected _run(multiCursorController: MultiCursorSelectionController, findController: CommonFindController): void {
multiCursorController.moveSelectionToPreviousFindMatch(findController);
}
}
export class SelectHighlightsAction extends MultiCursorSelectionControllerAction {
constructor() {
super({
id: 'editor.action.selectHighlights',
label: nls.localize('selectAllOccurrencesOfFindMatch', "Select All Occurrences of Find Match"),
alias: 'Select All Occurrences of Find Match',
precondition: null,
kbOpts: {
kbExpr: EditorContextKeys.focus,
primary: KeyMod.CtrlCmd | KeyMod.Shift | KeyCode.KEY_L
}
});
}
protected _run(multiCursorController: MultiCursorSelectionController, findController: CommonFindController): void {
multiCursorController.selectAll(findController);
}
}
export class CompatChangeAll extends MultiCursorSelectionControllerAction {
constructor() {
super({
id: 'editor.action.changeAll',
label: nls.localize('changeAll.label', "Change All Occurrences"),
alias: 'Change All Occurrences',
precondition: EditorContextKeys.writable,
kbOpts: {
kbExpr: EditorContextKeys.editorTextFocus,
primary: KeyMod.CtrlCmd | KeyCode.F2
},
menuOpts: {
group: '1_modification',
order: 1.2
}
});
}
protected _run(multiCursorController: MultiCursorSelectionController, findController: CommonFindController): void {
multiCursorController.selectAll(findController);
}
}
class SelectionHighlighterState {
public readonly lastWordUnderCursor: Selection;
public readonly searchText: string;
public readonly matchCase: boolean;
public readonly wordSeparators: string;
constructor(lastWordUnderCursor: Selection, searchText: string, matchCase: boolean, wordSeparators: string) {
this.lastWordUnderCursor = lastWordUnderCursor;
this.searchText = searchText;
this.matchCase = matchCase;
this.wordSeparators = wordSeparators;
}
/**
* Everything equals except for `lastWordUnderCursor`
*/
public static softEquals(a: SelectionHighlighterState, b: SelectionHighlighterState): boolean {
if (!a && !b) {
return true;
}
if (!a || !b) {
return false;
}
return (
a.searchText === b.searchText
&& a.matchCase === b.matchCase
&& a.wordSeparators === b.wordSeparators
);
}
}
export class SelectionHighlighter extends Disposable implements IEditorContribution {
private static readonly ID = 'editor.contrib.selectionHighlighter';
private editor: ICodeEditor;
private _isEnabled: boolean;
private decorations: string[];
private updateSoon: RunOnceScheduler;
private state: SelectionHighlighterState;
constructor(editor: ICodeEditor) {
super();
this.editor = editor;
this._isEnabled = editor.getConfiguration().contribInfo.selectionHighlight;
this.decorations = [];
this.updateSoon = this._register(new RunOnceScheduler(() => this._update(), 300));
this.state = null;
this._register(editor.onDidChangeConfiguration((e) => {
this._isEnabled = editor.getConfiguration().contribInfo.selectionHighlight;
}));
this._register(editor.onDidChangeCursorSelection((e: ICursorSelectionChangedEvent) => {
if (!this._isEnabled) {
// Early exit if nothing needs to be done!
// Leave some form of early exit check here if you wish to continue being a cursor position change listener ;)
return;
}
if (e.selection.isEmpty()) {
if (e.reason === CursorChangeReason.Explicit) {
if (this.state && (!this.state.lastWordUnderCursor || !this.state.lastWordUnderCursor.containsPosition(e.selection.getStartPosition()))) {
// no longer valid
this._setState(null);
}
this.updateSoon.schedule();
} else {
this._setState(null);
}
} else {
this._update();
}
}));
this._register(editor.onDidChangeModel((e) => {
this._setState(null);
}));
this._register(CommonFindController.get(editor).getState().onFindReplaceStateChange((e) => {
this._update();
}));
}
public getId(): string {
return SelectionHighlighter.ID;
}
private _update(): void {
this._setState(SelectionHighlighter._createState(this._isEnabled, this.editor));
}
private static _createState(isEnabled: boolean, editor: ICodeEditor): SelectionHighlighterState {
if (!isEnabled) {
return null;
}
const model = editor.getModel();
if (!model) {
return null;
}
const s = editor.getSelection();
if (s.startLineNumber !== s.endLineNumber) {
// multiline forbidden for perf reasons
return null;
}
const multiCursorController = MultiCursorSelectionController.get(editor);
if (!multiCursorController) {
return null;
}
const findController = CommonFindController.get(editor);
if (!findController) {
return null;
}
let r = multiCursorController.getSession(findController);
if (!r) {
const allSelections = editor.getSelections();
if (allSelections.length > 1) {
const findState = findController.getState();
const matchCase = findState.matchCase;
const selectionsContainSameText = modelRangesContainSameText(editor.getModel(), allSelections, matchCase);
if (!selectionsContainSameText) {
return null;
}
}
r = MultiCursorSession.create(editor, findController);
}
if (!r) {
return null;
}
let lastWordUnderCursor: Selection = null;
const hasFindOccurrences = DocumentHighlightProviderRegistry.has(model);
if (r.currentMatch) {
// This is an empty selection
if (hasFindOccurrences) {
// Do not interfere with semantic word highlighting in the no selection case
return null;
}
const config = editor.getConfiguration();
if (!config.contribInfo.occurrencesHighlight) {
return null;
}
lastWordUnderCursor = r.currentMatch;
}
if (/^[ \t]+$/.test(r.searchText)) {
// whitespace only selection
return null;
}
if (r.searchText.length > 200) {
// very long selection
return null;
}
// TODO: better handling of this case
const findState = findController.getState();
const caseSensitive = findState.matchCase;
// Return early if the find widget shows the exact same matches
if (findState.isRevealed) {
let findStateSearchString = findState.searchString;
if (!caseSensitive) {
findStateSearchString = findStateSearchString.toLowerCase();
}
let mySearchString = r.searchText;
if (!caseSensitive) {
mySearchString = mySearchString.toLowerCase();
}
if (findStateSearchString === mySearchString && r.matchCase === findState.matchCase && r.wholeWord === findState.wholeWord && !findState.isRegex) {
return null;
}
}
return new SelectionHighlighterState(lastWordUnderCursor, r.searchText, r.matchCase, r.wholeWord ? editor.getConfiguration().wordSeparators : null);
}
private _setState(state: SelectionHighlighterState): void {
if (SelectionHighlighterState.softEquals(this.state, state)) {
this.state = state;
return;
}
this.state = state;
if (!this.state) {
this.decorations = this.editor.deltaDecorations(this.decorations, []);
return;
}
const model = this.editor.getModel();
if (model.isTooLargeForTokenization()) {
// the file is too large, so searching word under cursor in the whole document takes is blocking the UI.
return;
}
const hasFindOccurrences = DocumentHighlightProviderRegistry.has(model);
let allMatches = model.findMatches(this.state.searchText, true, false, this.state.matchCase, this.state.wordSeparators, false).map(m => m.range);
allMatches.sort(Range.compareRangesUsingStarts);
let selections = this.editor.getSelections();
selections.sort(Range.compareRangesUsingStarts);
// do not overlap with selection (issue #64 and #512)
let matches: Range[] = [];
for (let i = 0, j = 0, len = allMatches.length, lenJ = selections.length; i < len;) {
const match = allMatches[i];
if (j >= lenJ) {
// finished all editor selections
matches.push(match);
i++;
} else {
const cmp = Range.compareRangesUsingStarts(match, selections[j]);
if (cmp < 0) {
// match is before sel
if (selections[j].isEmpty() || !Range.areIntersecting(match, selections[j])) {
matches.push(match);
}
i++;
} else if (cmp > 0) {
// sel is before match
j++;
} else {
// sel is equal to match
i++;
j++;
}
}
}
const decorations = matches.map(r => {
return {
range: r,
// Show in overviewRuler only if model has no semantic highlighting
options: (hasFindOccurrences ? SelectionHighlighter._SELECTION_HIGHLIGHT : SelectionHighlighter._SELECTION_HIGHLIGHT_OVERVIEW)
};
});
this.decorations = this.editor.deltaDecorations(this.decorations, decorations);
}
private static readonly _SELECTION_HIGHLIGHT_OVERVIEW = ModelDecorationOptions.register({
stickiness: TrackedRangeStickiness.NeverGrowsWhenTypingAtEdges,
className: 'selectionHighlight',
overviewRuler: {
color: themeColorFromId(overviewRulerSelectionHighlightForeground),
darkColor: themeColorFromId(overviewRulerSelectionHighlightForeground),
position: OverviewRulerLane.Center
}
});
private static readonly _SELECTION_HIGHLIGHT = ModelDecorationOptions.register({
stickiness: TrackedRangeStickiness.NeverGrowsWhenTypingAtEdges,
className: 'selectionHighlight',
});
public dispose(): void {
this._setState(null);
super.dispose();
}
}
function modelRangesContainSameText(model: ITextModel, ranges: Range[], matchCase: boolean): boolean {
const selectedText = getValueInRange(model, ranges[0], !matchCase);
for (let i = 1, len = ranges.length; i < len; i++) {
const range = ranges[i];
if (range.isEmpty()) {
return false;
}
const thisSelectedText = getValueInRange(model, range, !matchCase);
if (selectedText !== thisSelectedText) {
return false;
}
}
return true;
}
function getValueInRange(model: ITextModel, range: Range, toLowerCase: boolean): string {
const text = model.getValueInRange(range);
return (toLowerCase ? text.toLowerCase() : text);
}
registerEditorContribution(MultiCursorSelectionController);
registerEditorContribution(SelectionHighlighter);
registerEditorAction(InsertCursorAbove);
registerEditorAction(InsertCursorBelow);
registerEditorAction(InsertCursorAtEndOfEachLineSelected);
registerEditorAction(AddSelectionToNextFindMatchAction);
registerEditorAction(AddSelectionToPreviousFindMatchAction);
registerEditorAction(MoveSelectionToNextFindMatchAction);
registerEditorAction(MoveSelectionToPreviousFindMatchAction);
registerEditorAction(SelectHighlightsAction);
registerEditorAction(CompatChangeAll);
| src/vs/editor/contrib/multicursor/multicursor.ts | 0 | https://github.com/microsoft/vscode/commit/3d688527f93a1077a23032c55a829f3f4078d0db | [
0.0023713805712759495,
0.00021622840722557157,
0.00016529287677258253,
0.00017287046648561954,
0.00027522339951246977
] |
{
"id": 3,
"code_window": [
"\t\tthis.children = this.getFlatSettings()\n",
"\t\t\t.map(s => createSettingsTreeSettingElement(s, result, this._viewState.settingsTarget, this._configurationService));\n",
"\t}\n",
"\n",
"\tprivate getFlatSettings(): ISetting[] {\n"
],
"labels": [
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t.map(s => createSettingsTreeSettingElement(s, this, this._viewState.settingsTarget, this._configurationService));\n"
],
"file_path": "src/vs/workbench/parts/preferences/browser/settingsTree.ts",
"type": "replace",
"edit_start_line_idx": 912
} | {
"": [
"--------------------------------------------------------------------------------------------",
"Copyright (c) Microsoft Corporation. All rights reserved.",
"Licensed under the MIT License. See License.txt in the project root for license information.",
"--------------------------------------------------------------------------------------------",
"Do not edit this file. It is machine generated."
],
"editorSuggestWidgetBackground": "제안 위젯의 배경색입니다.",
"editorSuggestWidgetBorder": "제안 위젯의 테두리 색입니다.",
"editorSuggestWidgetForeground": "제안 위젯의 전경색입니다.",
"editorSuggestWidgetSelectedBackground": "제한 위젯에서 선택된 항목의 배경색입니다.",
"editorSuggestWidgetHighlightForeground": "제안 위젯의 일치 항목 강조 표시 색입니다.",
"readMore": "자세히 알아보기...{0}",
"suggestionWithDetailsAriaLabel": "{0}, 제안, 세부 정보 있음",
"suggestionAriaLabel": "{0}, 제안",
"readLess": "간단히 보기...{0}",
"suggestWidget.loading": "로드 중...",
"suggestWidget.noSuggestions": "제안 항목이 없습니다.",
"suggestionAriaAccepted": "{0}, 수락됨",
"ariaCurrentSuggestionWithDetails": "{0}, 제안, 세부 정보 있음",
"ariaCurrentSuggestion": "{0}, 제안"
} | i18n/kor/src/vs/editor/contrib/suggest/suggestWidget.i18n.json | 0 | https://github.com/microsoft/vscode/commit/3d688527f93a1077a23032c55a829f3f4078d0db | [
0.00017354413284920156,
0.00017105675942730159,
0.00016659240645822138,
0.00017303373897448182,
0.0000031636436688131653
] |
{
"id": 3,
"code_window": [
"\t\tthis.children = this.getFlatSettings()\n",
"\t\t\t.map(s => createSettingsTreeSettingElement(s, result, this._viewState.settingsTarget, this._configurationService));\n",
"\t}\n",
"\n",
"\tprivate getFlatSettings(): ISetting[] {\n"
],
"labels": [
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t.map(s => createSettingsTreeSettingElement(s, this, this._viewState.settingsTarget, this._configurationService));\n"
],
"file_path": "src/vs/workbench/parts/preferences/browser/settingsTree.ts",
"type": "replace",
"edit_start_line_idx": 912
} | <svg width="16" height="16" xmlns="http://www.w3.org/2000/svg"><title>Layer 1</title><rect height="3" width="11" y="7" x="3" fill="#C5C5C5"/></svg> | extensions/git/resources/icons/dark/unstage.svg | 0 | https://github.com/microsoft/vscode/commit/3d688527f93a1077a23032c55a829f3f4078d0db | [
0.0001734280085656792,
0.0001734280085656792,
0.0001734280085656792,
0.0001734280085656792,
0
] |
{
"id": 0,
"code_window": [
" pipeline:\n",
" jobs:\n",
" - checkout:\n",
" filters:\n",
" branches:\n",
" ignore:\n",
" - l10n\n",
" - /dependabot\\//\n",
" - test_unit:\n",
" requires:\n",
" - checkout\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" # Ideally we only run this pipeline if the base branch is `master` or `next`.\n",
" # CircleCI doesn't support it because branch filters are based on target branch.\n",
" # We approximate it by running on `master`, `next` and any PR (assuming they always target master or next).\n",
" only:\n",
" - master\n",
" - next\n",
" # pull requests have its branch name following the `pull/$CIRCLE_PR_NUMBER` scheme.\n",
" - /pull\\/.*/\n"
],
"file_path": ".circleci/config.yml",
"type": "replace",
"edit_start_line_idx": 232
} | version: 2.1
defaults: &defaults
parameters:
react-dist-tag:
description: The dist-tag of react to be used
type: string
default: stable
environment:
# expose it globally otherwise we have to thread it from each job to the install command
REACT_DIST_TAG: << parameters.react-dist-tag >>
working_directory: /tmp/material-ui
docker:
- image: circleci/node:10
# CircleCI has disabled the cache across forks for security reasons.
# Following their official statement, it was a quick solution, they
# are working on providing this feature back with appropriate security measures.
# https://discuss.circleci.com/t/saving-cache-stopped-working-warning-skipping-this-step-disabled-in-configuration/24423/21
#
# restore_repo: &restore_repo
# restore_cache:
# key: v1-repo-{{ .Branch }}-{{ .Revision }}
commands:
install_js:
steps:
- run:
name: View install environment
command: |
node --version
yarn --version
- run:
name: Resolve react version
command: |
node scripts/use-react-dist-tag
# log a patch for maintainers who want to check out this change
git --no-pager diff HEAD
- restore_cache:
keys:
- v2-yarn-sha-{{ checksum "yarn.lock" }}
- v2-yarn-sha-
- run:
name: Install js dependencies
command: yarn
prepare_chrome_headless:
steps:
- run:
name: Install dependencies for Chrome Headless
# From https://github.com/GoogleChrome/puppeteer/blob/811415bc8c47f7882375629b57b3fe186ad61ed4/docs/troubleshooting.md#chrome-headless-doesnt-launch
command: |
sudo apt-get update
sudo apt-get install -y --force-yes gconf-service libasound2 libatk1.0-0 libc6 libcairo2 libcups2 libdbus-1-3 libexpat1 libfontconfig1 libgcc1 libgconf-2-4 libgdk-pixbuf2.0-0 libglib2.0-0 libgtk-3-0 libnspr4 libpango-1.0-0 libpangocairo-1.0-0 libstdc++6 libx11-6 libx11-xcb1 libxcb1 libxcomposite1 libxcursor1 libxdamage1 libxext6 libxfixes3 libxi6 libxrandr2 libxrender1 libxss1 libxtst6 ca-certificates fonts-liberation libappindicator1 libnss3 lsb-release xdg-utils wget
jobs:
checkout:
<<: *defaults
steps:
- checkout
- install_js
- run:
name: Should not have any git not staged
command: git diff --exit-code
- run:
name: Check for duplicated packages
command: yarn deduplicate
- save_cache:
key: v2-yarn-sha-{{ checksum "yarn.lock" }}
paths:
- ~/.cache/yarn/v4
test_unit:
<<: *defaults
steps:
- checkout
- install_js
- run:
name: Tests fake browser
command: yarn test:coverage
- run:
name: Check coverage generated
command: |
if ! [[ -s coverage/lcov.info ]]
then
exit 1
fi
- run:
name: material-ui-icons
command: |
# latest commit
LATEST_COMMIT=$(git rev-parse HEAD)
# latest commit where packages/material-ui-icons was changed
FOLDER_COMMIT=$(git log -1 --format=format:%H --full-diff packages/material-ui-icons)
if [ $FOLDER_COMMIT = $LATEST_COMMIT ]; then
echo "changes, let's run the tests"
yarn workspace @material-ui/icons build:typings
yarn workspace @material-ui/icons test:built-typings
else
echo "no changes"
fi
- run:
name: typescript-to-proptypes
command: |
# latest commit
LATEST_COMMIT=$(git rev-parse HEAD)
# latest commit where packages/typescript-to-proptypes was changed
FOLDER_COMMIT=$(git log -1 --format=format:%H --full-diff packages/typescript-to-proptypes)
if [ $FOLDER_COMMIT = $LATEST_COMMIT ]; then
echo "changes, let's run the tests"
yarn workspace typescript-to-proptypes test
else
echo "no changes"
fi
- run:
name: Coverage
command: bash <(curl -s https://codecov.io/bash) -Z -C $CIRCLE_SHA1
test_static:
<<: *defaults
steps:
- checkout
- install_js
- run:
name: '`yarn prettier` changes committed?'
command: yarn prettier check-changed
- run:
name: Generate PropTypes
command: yarn proptypes
- run:
name: '`yarn proptypes` changes committed?'
command: git diff --exit-code
- run:
name: Generate the documentation
command: yarn docs:api
- run:
name: '`yarn docs:api` changes committed?'
command: git diff --exit-code
- run:
name: Generate the framer components
command: yarn workspace framer build
- run:
name: '`yarn workspace framer build` changes committed?'
command: git diff --exit-code
- run:
name: Lint
command: yarn lint:ci
- run:
name: Lint JSON
command: yarn jsonlint
- run:
name: '`yarn extract-error-codes` changes committed?'
command: |
yarn extract-error-codes
git diff --exit-code
test_types:
<<: *defaults
steps:
- checkout
- install_js
- run:
name: Transpile TypeScript demos
command: yarn docs:typescript:formatted --disable-cache
- run:
name: '`yarn docs:typescript:formatted` changes committed?'
command: git add -A && git diff --exit-code --staged
- run:
name: Tests TypeScript definitions
command: yarn typescript
test_types_next:
<<: *defaults
steps:
- checkout
- run:
name: Resolve typescript version
environment:
TYPESCRIPT_DIST_TAG: next
command: |
node scripts/use-typescript-dist-tag
# log a patch for maintainers who want to check out this change
git --no-pager diff HEAD
- install_js
- run:
name: Tests TypeScript definitions
command: |
# ignore build failures
# it's expected that typescript@next fails since the lines of the errors
# change frequently. This build is monitored regardless of its status
set +e
# we want to see errors in all packages.
# without --no-bail we only see at most a single failing package
yarn typescript --no-bail
exit 0
test_browser:
<<: *defaults
steps:
- checkout
- install_js
- prepare_chrome_headless
- run:
name: Tests real browsers
command: yarn test:karma
- store_artifacts:
# hardcoded in karma-webpack
path: /tmp/_karma_webpack_
destination: artifact-file
- run:
name: Can we generate the @material-ui/core umd build?
command: yarn workspace @material-ui/core build:umd
- run:
name: Test umd release
command: yarn test:umd
test_regressions:
<<: *defaults
docker:
- image: circleci/node:10
- image: selenium/standalone-chrome:3.11.0
steps:
- checkout
- install_js
- run:
name: Visual regression tests
command: |
DOCKER_TEST_URL=http://$(ip addr show lo | grep "inet\b" | awk '{print $2}' | cut -d/ -f1):3090 yarn test:regressions
yarn argos
workflows:
version: 2
pipeline:
jobs:
- checkout:
filters:
branches:
ignore:
- l10n
- /dependabot\//
- test_unit:
requires:
- checkout
- test_static:
requires:
- checkout
- test_types:
requires:
- checkout
- test_browser:
requires:
- checkout
- test_regressions:
requires:
- test_unit
- test_static
- test_types
- test_browser
react-next:
triggers:
- schedule:
cron: '0 0 * * *'
filters:
branches:
only:
- master
- next
jobs:
- test_unit:
react-dist-tag: next
- test_browser:
react-dist-tag: next
- test_regressions:
requires:
- test_unit
- test_browser
react-dist-tag: next
typescript-next:
triggers:
- schedule:
cron: '0 0 * * *'
filters:
branches:
only:
- master
- next
jobs:
- test_types_next
| .circleci/config.yml | 1 | https://github.com/mui/material-ui/commit/835a93d74b0e1f8888003166eea81a4a82794462 | [
0.020634055137634277,
0.0015709314029663801,
0.00016436151054222137,
0.00019689514010678977,
0.004034007433801889
] |
{
"id": 0,
"code_window": [
" pipeline:\n",
" jobs:\n",
" - checkout:\n",
" filters:\n",
" branches:\n",
" ignore:\n",
" - l10n\n",
" - /dependabot\\//\n",
" - test_unit:\n",
" requires:\n",
" - checkout\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" # Ideally we only run this pipeline if the base branch is `master` or `next`.\n",
" # CircleCI doesn't support it because branch filters are based on target branch.\n",
" # We approximate it by running on `master`, `next` and any PR (assuming they always target master or next).\n",
" only:\n",
" - master\n",
" - next\n",
" # pull requests have its branch name following the `pull/$CIRCLE_PR_NUMBER` scheme.\n",
" - /pull\\/.*/\n"
],
"file_path": ".circleci/config.yml",
"type": "replace",
"edit_start_line_idx": 232
} | import * as React from 'react';
export interface NoSsrProps {
/**
* You can wrap a node.
*/
children?: React.ReactNode;
/**
* If `true`, the component will not only prevent server-side rendering.
* It will also defer the rendering of the children into a different screen frame.
* @default false
*/
defer?: boolean;
/**
* The fallback content to display.
* @default null
*/
fallback?: React.ReactNode;
}
/**
* NoSsr purposely removes components from the subject of Server Side Rendering (SSR).
*
* This component can be useful in a variety of situations:
*
* - Escape hatch for broken dependencies not supporting SSR.
* - Improve the time-to-first paint on the client by only rendering above the fold.
* - Reduce the rendering time on the server.
* - Under too heavy server load, you can turn on service degradation.
* Demos:
*
* - [No Ssr](https://material-ui.com/components/no-ssr/)
*
* API:
*
* - [NoSsr API](https://material-ui.com/api/no-ssr/)
*/
export default function NoSsr(props: NoSsrProps): JSX.Element;
| packages/material-ui/src/NoSsr/NoSsr.d.ts | 0 | https://github.com/mui/material-ui/commit/835a93d74b0e1f8888003166eea81a4a82794462 | [
0.00016921556380111724,
0.00016587780555710196,
0.0001596788060851395,
0.00016730843344703317,
0.000003671483227662975
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.