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": 9,
"code_window": [
"\n",
" onDismiss(callback: Function) {\n",
" this._onDismiss = callback;\n",
" }\n",
"\n",
" dismiss(data?: any, role?: any) {\n",
" return this._nav.remove(this._nav.indexOf(this), 1, this._leavingOpts).then(() => {\n",
" this._onDismiss && this._onDismiss(data, role);\n",
" return data;\n",
" });\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" dismiss(data?: any, role?: any, navOptions: NavOptions = {}) {\n",
" let options = merge({}, this._leavingOpts, navOptions);\n",
" return this._nav.remove(this._nav.indexOf(this), 1, options).then(() => {\n"
],
"file_path": "src/components/nav/view-controller.ts",
"type": "replace",
"edit_start_line_idx": 127
} | <ion-toolbar>
<ion-title>Datetime</ion-title>
</ion-toolbar>
<ion-content class="outer-content">
<ion-item>
<ion-label>YYYY</ion-label>
<ion-datetime displayFormat="YYYY" min="1981" max="2002" [(ngModel)]="wwwInvented"></ion-datetime>
</ion-item>
<ion-item>
<ion-label>MMMM YY</ion-label>
<ion-datetime displayFormat="MMMM YY" min="1989-06-04" max="2004-08-23" [(ngModel)]="netscapeReleased"></ion-datetime>
</ion-item>
<ion-item>
<ion-label>MM/DD/YYYY</ion-label>
<ion-datetime displayFormat="MM/DD/YYYY" min="1994-03-14" max="2012-12-09" [(ngModel)]="firefoxReleased" class="e2eOpenMMDDYYYY"></ion-datetime>
</ion-item>
<ion-item>
<ion-label>DDD. MMM DD, YY (custom locale)</ion-label>
<ion-datetime [(ngModel)]="operaReleased" min="1990-02" max="2000"
displayFormat="DDD. MMM DD, YY"
monthShortNames="jan, feb, mar, apr, mai, jun, jul, aug, sep, okt, nov, des"
[dayShortNames]="customShortDay"></ion-datetime>
</ion-item>
<ion-item>
<ion-label>D MMM YYYY H:mm</ion-label>
<ion-datetime displayFormat="D MMM YYYY H:mm" min="1997" max="2010" [(ngModel)]="webkitOpenSourced"></ion-datetime>
</ion-item>
<ion-item>
<ion-label>DDDD MMM D, YYYY</ion-label>
<ion-datetime displayFormat="DDDD MMM D, YYYY" min="2005" max="2016" [(ngModel)]="chromeReleased"></ion-datetime>
</ion-item>
<ion-item>
<ion-label>HH:mm</ion-label>
<ion-datetime displayFormat="HH:mm" [(ngModel)]="time"></ion-datetime>
</ion-item>
<ion-item>
<ion-label>h:mm a</ion-label>
<ion-datetime displayFormat="h:mm a" [(ngModel)]="time"></ion-datetime>
</ion-item>
<ion-item>
<ion-label>hh:mm A (15 min steps)</ion-label>
<ion-datetime displayFormat="h:mm A" minuteValues="0,15,30,45"></ion-datetime>
</ion-item>
<ion-item>
<ion-label>Leap years, summer months</ion-label>
<ion-datetime displayFormat="MM/YYYY" pickerFormat="MMMM YYYY" [yearValues]="leapYearsArray" monthValues="6,7,8" [(ngModel)]="leapYearsSummerMonths"></ion-datetime>
</ion-item>
<p aria-hidden="true" padding>
<code>wwwInvented: {{wwwInvented}}</code><br>
<code>netscapeReleased: {{netscapeReleased}}</code><br>
<code>operaReleased: {{operaReleased}}</code><br>
<code>firefoxReleased: {{firefoxReleased}}</code><br>
<code>webkitOpenSourced: {{webkitOpenSourced}}</code><br>
<code>chromeReleased: {{chromeReleased}}</code><br>
<code>time: {{time}}</code><br>
<code>Leap year, summer months: {{leapYearsSummerMonths}}</code><br>
</p>
</ion-content>
| src/components/datetime/test/basic/main.html | 0 | https://github.com/ionic-team/ionic-framework/commit/9a86e4bdf89669aac5800fb9f7c0e0d087772fc3 | [
0.0001774315460352227,
0.0001747829664964229,
0.00017360736092086881,
0.00017458446382079273,
0.0000011338291869833483
] |
{
"id": 9,
"code_window": [
"\n",
" onDismiss(callback: Function) {\n",
" this._onDismiss = callback;\n",
" }\n",
"\n",
" dismiss(data?: any, role?: any) {\n",
" return this._nav.remove(this._nav.indexOf(this), 1, this._leavingOpts).then(() => {\n",
" this._onDismiss && this._onDismiss(data, role);\n",
" return data;\n",
" });\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" dismiss(data?: any, role?: any, navOptions: NavOptions = {}) {\n",
" let options = merge({}, this._leavingOpts, navOptions);\n",
" return this._nav.remove(this._nav.indexOf(this), 1, options).then(() => {\n"
],
"file_path": "src/components/nav/view-controller.ts",
"type": "replace",
"edit_start_line_idx": 127
} |
<!-- Text -->
<ion-tabs no-navbar>
<ion-tab tabTitle="Recents" [root]="root"></ion-tab>
<ion-tab tabTitle="Favorites" [root]="root"></ion-tab>
<ion-tab tabTitle="Settings" [root]="root"></ion-tab>
</ion-tabs>
<!-- Icons -->
<ion-tabs no-navbar selectedIndex="1">
<ion-tab tabIcon="call" [root]="root"></ion-tab>
<ion-tab tabIcon="heart" [root]="root"></ion-tab>
<ion-tab tabIcon="settings" [root]="root"></ion-tab>
</ion-tabs>
<!-- Icons on top of text -->
<ion-tabs no-navbar selectedIndex="2">
<ion-tab tabTitle="Location" tabIcon="navigate" [root]="root"></ion-tab>
<ion-tab tabTitle="Favorites" tabIcon="star" [root]="root"></ion-tab>
<ion-tab tabTitle="Radio" tabIcon="musical-notes" [root]="root"></ion-tab>
</ion-tabs>
<!-- Icons below text -->
<ion-tabs tabbarLayout="icon-bottom" no-navbar selectedIndex="1">
<ion-tab tabTitle="Recents" tabIcon="call" [root]="root"></ion-tab>
<ion-tab tabTitle="Favorites" tabIcon="heart" [root]="root"></ion-tab>
<ion-tab tabTitle="Settings" tabIcon="settings" [root]="root"></ion-tab>
</ion-tabs>
<!-- Icons right of text -->
<ion-tabs tabbarLayout="icon-right" no-navbar selectedIndex="0">
<ion-tab tabTitle="Recents" tabIcon="call" [root]="root"></ion-tab>
<ion-tab tabTitle="Favorites" tabIcon="heart" [root]="root"></ion-tab>
<ion-tab tabTitle="Settings" tabIcon="settings" [root]="root"></ion-tab>
</ion-tabs>
<!-- Icons left of text -->
<ion-tabs tabbarLayout="icon-left" no-navbar>
<ion-tab tabTitle="Recents" tabIcon="call" [root]="root"></ion-tab>
<ion-tab tabTitle="Favorites" tabIcon="heart" [root]="root"></ion-tab>
<ion-tab tabTitle="Settings" tabIcon="settings" [root]="root"></ion-tab>
</ion-tabs>
<!-- No icons -->
<ion-tabs tabbarLayout="icon-hide" no-navbar>
<ion-tab tabTitle="Recents" tabIcon="call" [root]="root"></ion-tab>
<ion-tab tabTitle="Favorites" tabIcon="heart" [root]="root"></ion-tab>
<ion-tab tabTitle="Settings" tabIcon="settings" [root]="root"></ion-tab>
</ion-tabs>
<!-- No title -->
<ion-tabs tabbarLayout="title-hide" secondary no-navbar>
<ion-tab tabTitle="Recents" tabIcon="call" [root]="root"></ion-tab>
<ion-tab tabTitle="Favorites" tabIcon="heart" [root]="root"></ion-tab>
<ion-tab tabTitle="Radio" tabIcon="musical-notes" [root]="root"></ion-tab>
<ion-tab tabTitle="Messages" tabIcon="chatboxes" [root]="root"></ion-tab>
<ion-tab tabTitle="Settings" tabIcon="settings" [root]="root"></ion-tab>
</ion-tabs>
<!-- No overflow text -->
<ion-tabs no-navbar>
<ion-tab tabTitle="Indiana Jones and the Raiders of the Lost Ark" [root]="root"></ion-tab>
<ion-tab tabTitle="Indiana Jones and the Temple of Doom" [root]="root"></ion-tab>
<ion-tab tabTitle="Indiana Jones and the Last Crusade" [root]="root"></ion-tab>
</ion-tabs>
| src/components/tabs/test/tab-bar-scenarios/main.html | 0 | https://github.com/ionic-team/ionic-framework/commit/9a86e4bdf89669aac5800fb9f7c0e0d087772fc3 | [
0.0001725393085507676,
0.00017080805264413357,
0.00016659383254591376,
0.00017126899911090732,
0.0000018149795550925774
] |
{
"id": 0,
"code_window": [
"\n",
"# Include sources from lib, but not map files.\n",
"!lib/**/*.js\n",
"# Exclude injected files. A preprocessed version of these is included via lib/generated.\n",
"# See src/server/injected/README.md.\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep"
],
"after_edit": [
"# Include web assets for recorder, trace viewer, etc.\n",
"!lib/**/*.html\n",
"!lib/**/*.png\n",
"!lib/**/*.ttf\n"
],
"file_path": "packages/common/.npmignore",
"type": "add",
"edit_start_line_idx": 10
} | /**
* Copyright (c) Microsoft Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import * as os from 'os';
import * as fs from 'fs';
import * as path from 'path';
import * as util from 'util';
import { CRPage } from '../../chromium/crPage';
import { Page } from '../../page';
import { ProgressController } from '../../progress';
import { createPlaywright } from '../../playwright';
import { EventEmitter } from 'events';
import { DEFAULT_ARGS } from '../../chromium/chromium';
const readFileAsync = util.promisify(fs.readFile);
export type Mode = 'inspecting' | 'recording' | 'none';
export type EventData = {
event: 'clear' | 'resume' | 'setMode',
params: any
};
declare global {
interface Window {
playwrightSetMode: (mode: Mode) => void;
playwrightSetPaused: (paused: boolean) => void;
playwrightSetSource: (params: { text: string, language: string }) => void;
dispatch(data: EventData): Promise<void>;
}
}
export class RecorderApp extends EventEmitter {
private _page: Page;
constructor(page: Page) {
super();
this.setMaxListeners(0);
this._page = page;
}
async close() {
await this._page.context().close();
}
private async _init() {
const icon = await readFileAsync(require.resolve('../../../../lib/web/recorder/app_icon.png'));
const crPopup = this._page._delegate as CRPage;
await crPopup._mainFrameSession._client.send('Browser.setDockTile', {
image: icon.toString('base64')
});
await this._page._setServerRequestInterceptor(async route => {
if (route.request().url().startsWith('https://playwright/')) {
const uri = route.request().url().substring('https://playwright/'.length);
const file = require.resolve('../../../../lib/web/recorder/' + uri);
const buffer = await readFileAsync(file);
await route.fulfill({
status: 200,
headers: [
{ name: 'Content-Type', value: extensionToMime[path.extname(file)] }
],
body: buffer.toString('base64'),
isBase64: true
});
return;
}
await route.continue();
});
await this._page.exposeBinding('dispatch', false, (_, data: any) => this.emit('event', data));
this._page.once('close', () => {
this.emit('close');
this._page.context().close().catch(e => console.error(e));
});
await this._page.mainFrame().goto(new ProgressController(), 'https://playwright/index.html');
}
static async open(): Promise<RecorderApp> {
const recorderPlaywright = createPlaywright(true);
const context = await recorderPlaywright.chromium.launchPersistentContext('', {
ignoreAllDefaultArgs: true,
args: [
...DEFAULT_ARGS,
`--user-data-dir=${path.join(os.homedir(),'.playwright-app')}`,
'--remote-debugging-pipe',
'--app=data:text/html,',
`--window-size=300,800`,
],
noDefaultViewport: true
});
const controller = new ProgressController();
await controller.run(async progress => {
await context._browser._defaultContext!._loadDefaultContextAsIs(progress);
});
const [page] = context.pages();
const result = new RecorderApp(page);
await result._init();
return result;
}
async setMode(mode: 'none' | 'recording' | 'inspecting'): Promise<void> {
await this._page.mainFrame()._evaluateExpression(((mode: Mode) => {
window.playwrightSetMode(mode);
}).toString(), true, mode, 'main').catch(() => {});
}
async setPaused(paused: boolean): Promise<void> {
await this._page.mainFrame()._evaluateExpression(((paused: boolean) => {
window.playwrightSetPaused(paused);
}).toString(), true, paused, 'main').catch(() => {});
}
async setSource(text: string, language: string): Promise<void> {
await this._page.mainFrame()._evaluateExpression(((param: { text: string, language: string }) => {
window.playwrightSetSource(param);
}).toString(), true, { text, language }, 'main').catch(() => {});
}
async bringToFront() {
await this._page.bringToFront();
}
}
const extensionToMime: { [key: string]: string } = {
'.css': 'text/css',
'.html': 'text/html',
'.jpeg': 'image/jpeg',
'.js': 'application/javascript',
'.png': 'image/png',
'.ttf': 'font/ttf',
'.svg': 'image/svg+xml',
'.webp': 'image/webp',
'.woff': 'font/woff',
'.woff2': 'font/woff2',
};
| src/server/supplements/recorder/recorderApp.ts | 1 | https://github.com/microsoft/playwright/commit/983e04374a881e4e0fbaf39ef6a57181fd951f1a | [
0.00020125826995354146,
0.00017057149671018124,
0.00016664943541400135,
0.0001679048000369221,
0.00000805785930424463
] |
{
"id": 0,
"code_window": [
"\n",
"# Include sources from lib, but not map files.\n",
"!lib/**/*.js\n",
"# Exclude injected files. A preprocessed version of these is included via lib/generated.\n",
"# See src/server/injected/README.md.\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep"
],
"after_edit": [
"# Include web assets for recorder, trace viewer, etc.\n",
"!lib/**/*.html\n",
"!lib/**/*.png\n",
"!lib/**/*.ttf\n"
],
"file_path": "packages/common/.npmignore",
"type": "add",
"edit_start_line_idx": 10
} | /**
* 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.
*/
import { it, expect } from './fixtures';
it('should select textarea', async ({ page, server, isFirefox }) => {
await page.goto(server.PREFIX + '/input/textarea.html');
const textarea = await page.$('textarea');
await textarea.evaluate(textarea => textarea.value = 'some value');
await textarea.selectText();
if (isFirefox) {
expect(await textarea.evaluate(el => el.selectionStart)).toBe(0);
expect(await textarea.evaluate(el => el.selectionEnd)).toBe(10);
} else {
expect(await page.evaluate(() => window.getSelection().toString())).toBe('some value');
}
});
it('should select input', async ({ page, server, isFirefox }) => {
await page.goto(server.PREFIX + '/input/textarea.html');
const input = await page.$('input');
await input.evaluate(input => input.value = 'some value');
await input.selectText();
if (isFirefox) {
expect(await input.evaluate(el => el.selectionStart)).toBe(0);
expect(await input.evaluate(el => el.selectionEnd)).toBe(10);
} else {
expect(await page.evaluate(() => window.getSelection().toString())).toBe('some value');
}
});
it('should select plain div', async ({ page, server }) => {
await page.goto(server.PREFIX + '/input/textarea.html');
const div = await page.$('div.plain');
await div.selectText();
expect(await page.evaluate(() => window.getSelection().toString())).toBe('Plain div');
});
it('should timeout waiting for invisible element', async ({ page, server }) => {
await page.goto(server.PREFIX + '/input/textarea.html');
const textarea = await page.$('textarea');
await textarea.evaluate(e => e.style.display = 'none');
const error = await textarea.selectText({ timeout: 3000 }).catch(e => e);
expect(error.message).toContain('element is not visible');
});
it('should wait for visible', async ({ page, server }) => {
await page.goto(server.PREFIX + '/input/textarea.html');
const textarea = await page.$('textarea');
await textarea.evaluate(textarea => textarea.value = 'some value');
await textarea.evaluate(e => e.style.display = 'none');
let done = false;
const promise = textarea.selectText({ timeout: 3000 }).then(() => done = true);
await page.evaluate(() => new Promise(f => setTimeout(f, 1000)));
expect(done).toBe(false);
await textarea.evaluate(e => e.style.display = 'block');
await promise;
});
| test/elementhandle-select-text.spec.ts | 0 | https://github.com/microsoft/playwright/commit/983e04374a881e4e0fbaf39ef6a57181fd951f1a | [
0.00017213489627465606,
0.00016780375153757632,
0.00016419216990470886,
0.00016773770039435476,
0.000002926568640759797
] |
{
"id": 0,
"code_window": [
"\n",
"# Include sources from lib, but not map files.\n",
"!lib/**/*.js\n",
"# Exclude injected files. A preprocessed version of these is included via lib/generated.\n",
"# See src/server/injected/README.md.\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep"
],
"after_edit": [
"# Include web assets for recorder, trace viewer, etc.\n",
"!lib/**/*.html\n",
"!lib/**/*.png\n",
"!lib/**/*.ttf\n"
],
"file_path": "packages/common/.npmignore",
"type": "add",
"edit_start_line_idx": 10
} | /*
* Copyright (C) 2010 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*/
@class WKWebView;
@interface BrowserWindowController : NSWindowController
- (IBAction)goBack:(id)sender;
- (IBAction)goForward:(id)sender;
- (IBAction)reload:(id)sender;
- (IBAction)saveAsPDF:(id)sender;
- (IBAction)saveAsWebArchive:(id)sender;
- (IBAction)zoomIn:(id)sender;
- (IBAction)zoomOut:(id)sender;
- (IBAction)resetZoom:(id)sender;
- (IBAction)showHideWebInspector:(id)sender;
- (IBAction)setPageScale:(id)sender;
- (IBAction)setViewScale:(id)sender;
- (instancetype)initWithConfiguration:(WKWebViewConfiguration *)configuration;
- (void)loadURLString:(NSString *)urlString;
- (WKWebView *)webView;
@end
| browser_patches/webkit/embedder/Playwright/mac/BrowserWindowController.h | 0 | https://github.com/microsoft/playwright/commit/983e04374a881e4e0fbaf39ef6a57181fd951f1a | [
0.0001726815098663792,
0.00016681538545526564,
0.0001627509918762371,
0.00016573697212152183,
0.000003295910801170976
] |
{
"id": 0,
"code_window": [
"\n",
"# Include sources from lib, but not map files.\n",
"!lib/**/*.js\n",
"# Exclude injected files. A preprocessed version of these is included via lib/generated.\n",
"# See src/server/injected/README.md.\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep"
],
"after_edit": [
"# Include web assets for recorder, trace viewer, etc.\n",
"!lib/**/*.html\n",
"!lib/**/*.png\n",
"!lib/**/*.ttf\n"
],
"file_path": "packages/common/.npmignore",
"type": "add",
"edit_start_line_idx": 10
} | /**
* 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 { it, expect } from './fixtures';
import { attachFrame } from './utils';
import type { ConsoleMessage } from '..';
it('Page.workers', async function({page, server}) {
await Promise.all([
page.waitForEvent('worker'),
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 = page.waitForEvent('worker');
const workerObj = await page.evaluateHandle(() => new Worker(URL.createObjectURL(new Blob(['1'], {type: 'application/javascript'}))));
const worker = await workerCreatedPromise;
const workerThisObj = await worker.evaluateHandle(() => this);
const workerDestroyedPromise = new Promise(x => worker.once('close', 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([
page.waitForEvent('console'),
page.evaluate(() => new Worker(URL.createObjectURL(new Blob(['console.log(1)'], {type: 'application/javascript'})))),
]);
expect(message.text()).toBe('1');
// Firefox's juggler had an issue that reported worker blob urls as frame urls.
expect(page.url()).not.toContain('blob');
});
it('should have JSHandles for console logs', async function({page}) {
const logPromise = new Promise<ConsoleMessage>(x => page.on('console', x));
await page.evaluate(() => new Worker(URL.createObjectURL(new Blob(['console.log(1,2,3,this)'], {type: 'application/javascript'}))));
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 = page.waitForEvent('worker');
await page.evaluate(() => new Worker(URL.createObjectURL(new Blob(['console.log(1)'], {type: 'application/javascript'}))));
const worker = await workerCreatedPromise;
expect(await worker.evaluate('1+1')).toBe(2);
});
it('should report errors', async function({page}) {
const errorPromise = new Promise<Error>(x => page.on('pageerror', x));
await page.evaluate(() => new Worker(URL.createObjectURL(new Blob([`
setTimeout(() => {
// Do a console.log just to check that we do not confuse it with an error.
console.log('hey');
throw new Error('this is my error');
})
`], {type: 'application/javascript'}))));
const errorLog = await errorPromise;
expect(errorLog.message).toContain('this is my error');
});
it('should clear upon navigation', async function({server, page}) {
await page.goto(server.EMPTY_PAGE);
const workerCreatedPromise = page.waitForEvent('worker');
await page.evaluate(() => new Worker(URL.createObjectURL(new Blob(['console.log(1)'], {type: 'application/javascript'}))));
const worker = await workerCreatedPromise;
expect(page.workers().length).toBe(1);
let destroyed = false;
worker.once('close', () => destroyed = true);
await page.goto(server.PREFIX + '/one-style.html');
expect(destroyed).toBe(true);
expect(page.workers().length).toBe(0);
});
it('should clear upon cross-process navigation', async function({server, page}) {
await page.goto(server.EMPTY_PAGE);
const workerCreatedPromise = page.waitForEvent('worker');
await page.evaluate(() => new Worker(URL.createObjectURL(new Blob(['console.log(1)'], {type: 'application/javascript'}))));
const worker = await workerCreatedPromise;
expect(page.workers().length).toBe(1);
let destroyed = false;
worker.once('close', () => destroyed = true);
await page.goto(server.CROSS_PROCESS_PREFIX + '/empty.html');
expect(destroyed).toBe(true);
expect(page.workers().length).toBe(0);
});
it('should attribute network activity for worker inside iframe to the iframe', (test, {browserName}) => {
test.fixme(browserName === 'firefox' || browserName === 'chromium');
}, async function({page, server}) {
await page.goto(server.PREFIX + '/empty.html');
const [worker, frame] = await Promise.all([
page.waitForEvent('worker'),
attachFrame(page, 'frame1', server.PREFIX + '/worker/worker.html'),
]);
const url = server.PREFIX + '/one-style.css';
const [request] = await Promise.all([
page.waitForRequest(url),
worker.evaluate(url => fetch(url).then(response => response.text()).then(console.log), url),
]);
expect(request.url()).toBe(url);
expect(request.frame()).toBe(frame);
});
it('should report network activity', async function({page, server}) {
const [worker] = await Promise.all([
page.waitForEvent('worker'),
page.goto(server.PREFIX + '/worker/worker.html'),
]);
const url = server.PREFIX + '/one-style.css';
const requestPromise = page.waitForRequest(url);
const responsePromise = page.waitForResponse(url);
await worker.evaluate(url => fetch(url).then(response => response.text()).then(console.log), url);
const request = await requestPromise;
const response = await responsePromise;
expect(request.url()).toBe(url);
expect(response.request()).toBe(request);
expect(response.ok()).toBe(true);
});
it('should report network activity on worker creation', async function({page, server}) {
// Chromium needs waitForDebugger enabled for this one.
await page.goto(server.EMPTY_PAGE);
const url = server.PREFIX + '/one-style.css';
const requestPromise = page.waitForRequest(url);
const responsePromise = page.waitForResponse(url);
await page.evaluate(url => new Worker(URL.createObjectURL(new Blob([`
fetch("${url}").then(response => response.text()).then(console.log);
`], {type: 'application/javascript'}))), url);
const request = await requestPromise;
const response = await responsePromise;
expect(request.url()).toBe(url);
expect(response.request()).toBe(request);
expect(response.ok()).toBe(true);
});
it('should format number using context locale', async ({browser, server}) => {
const context = await browser.newContext({ locale: 'ru-RU' });
const page = await context.newPage();
await page.goto(server.EMPTY_PAGE);
const [worker] = await Promise.all([
page.waitForEvent('worker'),
page.evaluate(() => new Worker(URL.createObjectURL(new Blob(['console.log(1)'], {type: 'application/javascript'})))),
]);
expect(await worker.evaluate(() => (10000.20).toLocaleString())).toBe('10\u00A0000,2');
await context.close();
});
| test/workers.spec.ts | 0 | https://github.com/microsoft/playwright/commit/983e04374a881e4e0fbaf39ef6a57181fd951f1a | [
0.00017946447769645602,
0.0001700938300928101,
0.00016550594591535628,
0.00016962125664576888,
0.0000031949598451319616
] |
{
"id": 1,
"code_window": [
"# Exclude injected files. A preprocessed version of these is included via lib/generated.\n",
"# See src/server/injected/README.md.\n",
"lib/server/injected/\n",
"# Include all binaries that we ship with the package.\n",
"!bin/*\n",
"# Include FFMPEG\n"
],
"labels": [
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"lib/**/injected/\n"
],
"file_path": "packages/common/.npmignore",
"type": "replace",
"edit_start_line_idx": 12
} | # NOTE: theoretically, we can remove this file, because we always create
# a directory for each package and only copy necessary files there.
# However, we keep it to double check the list of files.
#
# This ignores everything by default, except for package.json and LICENSE and README.md.
# See https://docs.npmjs.com/misc/developers
**/*
# Include sources from lib, but not map files.
!lib/**/*.js
# Exclude injected files. A preprocessed version of these is included via lib/generated.
# See src/server/injected/README.md.
lib/server/injected/
# Include all binaries that we ship with the package.
!bin/*
# Include FFMPEG
!third_party/ffmpeg/*
# Include generated types and entrypoint.
!types/*
!index.d.ts
# Include main entrypoint.
!index.js
# Include main entrypoint for ES Modules.
!index.mjs
# Include installer.
!install.js
# Include essentials.
!README.md
!LICENSE
!NOTICE
# Include protocol and api docs, so that dependent packages can consume them.
!api.json
!protocol.yml
# Include browser descriptors.
!browsers.json
# Include commit info
!commitinfo
| packages/common/.npmignore | 1 | https://github.com/microsoft/playwright/commit/983e04374a881e4e0fbaf39ef6a57181fd951f1a | [
0.9699391722679138,
0.2426675707101822,
0.00017038224905263633,
0.0002803662500809878,
0.41989046335220337
] |
{
"id": 1,
"code_window": [
"# Exclude injected files. A preprocessed version of these is included via lib/generated.\n",
"# See src/server/injected/README.md.\n",
"lib/server/injected/\n",
"# Include all binaries that we ship with the package.\n",
"!bin/*\n",
"# Include FFMPEG\n"
],
"labels": [
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"lib/**/injected/\n"
],
"file_path": "packages/common/.npmignore",
"type": "replace",
"edit_start_line_idx": 12
} | /**
* 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.
*/
import { it, expect } from './fixtures';
it('should select textarea', async ({ page, server, isFirefox }) => {
await page.goto(server.PREFIX + '/input/textarea.html');
const textarea = await page.$('textarea');
await textarea.evaluate(textarea => textarea.value = 'some value');
await textarea.selectText();
if (isFirefox) {
expect(await textarea.evaluate(el => el.selectionStart)).toBe(0);
expect(await textarea.evaluate(el => el.selectionEnd)).toBe(10);
} else {
expect(await page.evaluate(() => window.getSelection().toString())).toBe('some value');
}
});
it('should select input', async ({ page, server, isFirefox }) => {
await page.goto(server.PREFIX + '/input/textarea.html');
const input = await page.$('input');
await input.evaluate(input => input.value = 'some value');
await input.selectText();
if (isFirefox) {
expect(await input.evaluate(el => el.selectionStart)).toBe(0);
expect(await input.evaluate(el => el.selectionEnd)).toBe(10);
} else {
expect(await page.evaluate(() => window.getSelection().toString())).toBe('some value');
}
});
it('should select plain div', async ({ page, server }) => {
await page.goto(server.PREFIX + '/input/textarea.html');
const div = await page.$('div.plain');
await div.selectText();
expect(await page.evaluate(() => window.getSelection().toString())).toBe('Plain div');
});
it('should timeout waiting for invisible element', async ({ page, server }) => {
await page.goto(server.PREFIX + '/input/textarea.html');
const textarea = await page.$('textarea');
await textarea.evaluate(e => e.style.display = 'none');
const error = await textarea.selectText({ timeout: 3000 }).catch(e => e);
expect(error.message).toContain('element is not visible');
});
it('should wait for visible', async ({ page, server }) => {
await page.goto(server.PREFIX + '/input/textarea.html');
const textarea = await page.$('textarea');
await textarea.evaluate(textarea => textarea.value = 'some value');
await textarea.evaluate(e => e.style.display = 'none');
let done = false;
const promise = textarea.selectText({ timeout: 3000 }).then(() => done = true);
await page.evaluate(() => new Promise(f => setTimeout(f, 1000)));
expect(done).toBe(false);
await textarea.evaluate(e => e.style.display = 'block');
await promise;
});
| test/elementhandle-select-text.spec.ts | 0 | https://github.com/microsoft/playwright/commit/983e04374a881e4e0fbaf39ef6a57181fd951f1a | [
0.00017310932162217796,
0.00016906735254451632,
0.00016312215302605182,
0.00016974045138340443,
0.0000034315553421038203
] |
{
"id": 1,
"code_window": [
"# Exclude injected files. A preprocessed version of these is included via lib/generated.\n",
"# See src/server/injected/README.md.\n",
"lib/server/injected/\n",
"# Include all binaries that we ship with the package.\n",
"!bin/*\n",
"# Include FFMPEG\n"
],
"labels": [
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"lib/**/injected/\n"
],
"file_path": "packages/common/.npmignore",
"type": "replace",
"edit_start_line_idx": 12
} | // Copyright (C) 2010-2017 Apple Inc. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include? "../../../../Internal/Configurations/HaveInternalSDK.xcconfig"
#include "SDKVariant.xcconfig"
USE_INTERNAL_SDK = $(USE_INTERNAL_SDK_$(CONFIGURATION));
USE_INTERNAL_SDK_Production = YES;
USE_INTERNAL_SDK_Debug = $(HAVE_INTERNAL_SDK);
USE_INTERNAL_SDK_Release = $(HAVE_INTERNAL_SDK);
GCC_PREPROCESSOR_DEFINITIONS = DISABLE_LEGACY_WEBKIT_DEPRECATIONS $(inherited);
CLANG_CXX_LANGUAGE_STANDARD = gnu++1z;
CLANG_CXX_LIBRARY = libc++;
CLANG_ENABLE_OBJC_WEAK = YES;
DEBUG_INFORMATION_FORMAT = dwarf-with-dsym;
PREBINDING = NO
GCC_C_LANGUAGE_STANDARD = gnu99
GCC_ENABLE_CPP_EXCEPTIONS = NO;
GCC_PRECOMPILE_PREFIX_HEADER = YES
ENABLE_STRICT_OBJC_MSGSEND = YES;
GCC_TREAT_WARNINGS_AS_ERRORS = YES
CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
CLANG_WARN_BOOL_CONVERSION = YES;
CLANG_WARN_COMMA = YES;
CLANG_WARN_CONSTANT_CONVERSION = YES;
CLANG_WARN_EMPTY_BODY = YES;
CLANG_WARN_ENUM_CONVERSION = YES;
CLANG_WARN_INFINITE_RECURSION = YES;
CLANG_WARN_INT_CONVERSION = YES;
CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
CLANG_WARN_STRICT_PROTOTYPES = YES;
CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
CLANG_WARN_SUSPICIOUS_MOVE = YES;
CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;
CLANG_WARN_UNREACHABLE_CODE = YES;
GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
GCC_WARN_ABOUT_DEPRECATED_FUNCTIONS = NO;
GCC_WARN_ABOUT_RETURN_TYPE = YES;
GCC_WARN_UNINITIALIZED_AUTOS = YES;
GCC_WARN_UNUSED_FUNCTION = YES
GCC_WARN_UNUSED_VARIABLE = YES
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
GCC_WARN_UNDECLARED_SELECTOR = YES;
CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;
CLANG_ANALYZER_LOCALIZABILITY_NONLOCALIZED = YES;
GCC_VERSION = com.apple.compilers.llvm.clang.1_0;
WARNING_CFLAGS = -Wall -W -Wno-unused-parameter
GCC_NO_COMMON_BLOCKS = YES;
SUPPORTED_PLATFORMS = iphoneos iphonesimulator macosx tvos tvsimulator watchos watchsimulator;
TARGET_MAC_OS_X_VERSION_MAJOR = $(TARGET_MAC_OS_X_VERSION_MAJOR$(MACOSX_DEPLOYMENT_TARGET:suffix:identifier));
TARGET_MAC_OS_X_VERSION_MAJOR_13 = 101300;
TARGET_MAC_OS_X_VERSION_MAJOR_14 = 101400;
TARGET_MAC_OS_X_VERSION_MAJOR_15 = 101500;
TARGET_MAC_OS_X_VERSION_MAJOR_16 = 101600;
SDKROOT = macosx.internal;
OTHER_CFLAGS = $(ASAN_OTHER_CFLAGS);
OTHER_CPLUSPLUSFLAGS = $(ASAN_OTHER_CPLUSPLUSFLAGS);
OTHER_LDFLAGS = $(ASAN_OTHER_LDFLAGS);
CODE_SIGN_IDENTITY = -;
| browser_patches/webkit/embedder/Playwright/Configurations/Base.xcconfig | 0 | https://github.com/microsoft/playwright/commit/983e04374a881e4e0fbaf39ef6a57181fd951f1a | [
0.0188608281314373,
0.0064445678144693375,
0.0001671019708737731,
0.005332255735993385,
0.006111115217208862
] |
{
"id": 1,
"code_window": [
"# Exclude injected files. A preprocessed version of these is included via lib/generated.\n",
"# See src/server/injected/README.md.\n",
"lib/server/injected/\n",
"# Include all binaries that we ship with the package.\n",
"!bin/*\n",
"# Include FFMPEG\n"
],
"labels": [
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"lib/**/injected/\n"
],
"file_path": "packages/common/.npmignore",
"type": "replace",
"edit_start_line_idx": 12
} | <style>
button {
position: absolute;
width: 100px;
height: 20px;
margin: 0;
}
body, html {
margin: 0;
padding: 0;
height: 100%;
width: 100%;
position: relative;
}
div {
position: absolute;
left: 0;
top: 0;
right: 0;
bottom: 0;
}
#btn0 { right: 0px; top: 0; }
#btn1 { right: -10px; top: 25px; }
#btn2 { right: -20px; top: 50px; }
#btn3 { right: -30px; top: 75px; }
#btn4 { right: -40px; top: 100px; }
#btn5 { right: -50px; top: 125px; }
#btn6 { right: -60px; top: 150px; }
#btn7 { right: -70px; top: 175px; }
#btn8 { right: -80px; top: 200px; }
#btn9 { right: -90px; top: 225px; }
#btn10 { right: -100px; top: 250px; }
</style>
<div>
<button id=btn0>0</button>
<button id=btn1>1</button>
<button id=btn2>2</button>
<button id=btn3>3</button>
<button id=btn4>4</button>
<button id=btn5>5</button>
<button id=btn6>6</button>
<button id=btn7>7</button>
<button id=btn8>8</button>
<button id=btn9>9</button>
<button id=btn10>10</button>
</div>
<script>
window.addEventListener('DOMContentLoaded', () => {
for (const button of Array.from(document.querySelectorAll('button')))
button.addEventListener('click', () => console.log('button #' + button.textContent + ' clicked'), false);
}, false);
</script>
| test/assets/offscreenbuttons.html | 0 | https://github.com/microsoft/playwright/commit/983e04374a881e4e0fbaf39ef6a57181fd951f1a | [
0.00017521466361358762,
0.00017235377163160592,
0.0001671886711847037,
0.00017284389468841255,
0.0000025013946469698567
] |
{
"id": 2,
"code_window": [
" library: 'pwExport',\n",
" libraryExport: 'default',\n",
" filename: 'consoleApiSource.js',\n",
" path: path.resolve(__dirname, '../../../lib/server/injected/packed')\n",
" },\n",
" plugins: [\n",
" new InlineSource(path.join(__dirname, '..', '..', '..', 'generated', 'consoleApiSource.ts')),\n",
" ]\n",
"};"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" path: path.resolve(__dirname, '../../../../lib/server/injected/packed')\n"
],
"file_path": "src/server/supplements/injected/consoleApi.webpack.config.js",
"type": "replace",
"edit_start_line_idx": 44
} | # NOTE: theoretically, we can remove this file, because we always create
# a directory for each package and only copy necessary files there.
# However, we keep it to double check the list of files.
#
# This ignores everything by default, except for package.json and LICENSE and README.md.
# See https://docs.npmjs.com/misc/developers
**/*
# Include sources from lib, but not map files.
!lib/**/*.js
# Exclude injected files. A preprocessed version of these is included via lib/generated.
# See src/server/injected/README.md.
lib/server/injected/
# Include all binaries that we ship with the package.
!bin/*
# Include FFMPEG
!third_party/ffmpeg/*
# Include generated types and entrypoint.
!types/*
!index.d.ts
# Include main entrypoint.
!index.js
# Include main entrypoint for ES Modules.
!index.mjs
# Include installer.
!install.js
# Include essentials.
!README.md
!LICENSE
!NOTICE
# Include protocol and api docs, so that dependent packages can consume them.
!api.json
!protocol.yml
# Include browser descriptors.
!browsers.json
# Include commit info
!commitinfo
| packages/common/.npmignore | 1 | https://github.com/microsoft/playwright/commit/983e04374a881e4e0fbaf39ef6a57181fd951f1a | [
0.00036340259248390794,
0.00021630182163789868,
0.00016482795763295144,
0.00016848836094141006,
0.00008494735084241256
] |
{
"id": 2,
"code_window": [
" library: 'pwExport',\n",
" libraryExport: 'default',\n",
" filename: 'consoleApiSource.js',\n",
" path: path.resolve(__dirname, '../../../lib/server/injected/packed')\n",
" },\n",
" plugins: [\n",
" new InlineSource(path.join(__dirname, '..', '..', '..', 'generated', 'consoleApiSource.ts')),\n",
" ]\n",
"};"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" path: path.resolve(__dirname, '../../../../lib/server/injected/packed')\n"
],
"file_path": "src/server/supplements/injected/consoleApi.webpack.config.js",
"type": "replace",
"edit_start_line_idx": 44
} | /**
* Copyright 2018 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.
*/
import { it, expect, folio } from './fixtures';
it('should have default url when launching browser', async ({browserType, browserOptions, createUserDataDir}) => {
const browserContext = await browserType.launchPersistentContext(await createUserDataDir(), {...browserOptions, headless: false });
const urls = browserContext.pages().map(page => page.url());
expect(urls).toEqual(['about:blank']);
await browserContext.close();
});
it('headless should be able to read cookies written by headful', (test, { browserName, platform }) => {
test.slow();
}, async ({browserType, browserOptions, server, createUserDataDir}) => {
// see https://github.com/microsoft/playwright/issues/717
const userDataDir = await createUserDataDir();
// Write a cookie in headful chrome
const headfulContext = await browserType.launchPersistentContext(userDataDir, {...browserOptions, headless: false});
const headfulPage = await headfulContext.newPage();
await headfulPage.goto(server.EMPTY_PAGE);
await headfulPage.evaluate(() => document.cookie = 'foo=true; expires=Fri, 31 Dec 9999 23:59:59 GMT');
await headfulContext.close();
// Read the cookie from headless chrome
const headlessContext = await browserType.launchPersistentContext(userDataDir, {...browserOptions, headless: true});
const headlessPage = await headlessContext.newPage();
await headlessPage.goto(server.EMPTY_PAGE);
const cookie = await headlessPage.evaluate(() => document.cookie);
await headlessContext.close();
expect(cookie).toBe('foo=true');
});
it('should close browser with beforeunload page', (test, parameters) => {
test.slow();
}, async ({browserType, browserOptions, server, createUserDataDir}) => {
const browserContext = await browserType.launchPersistentContext(await createUserDataDir(), {...browserOptions, headless: false});
const page = await browserContext.newPage();
await page.goto(server.PREFIX + '/beforeunload.html');
// We have to interact with a page so that 'beforeunload' handlers
// fire.
await page.click('body');
await browserContext.close();
});
it('should not crash when creating second context', async ({browserType, browserOptions}) => {
const browser = await browserType.launch({...browserOptions, headless: false });
{
const browserContext = await browser.newContext();
await browserContext.newPage();
await browserContext.close();
}
{
const browserContext = await browser.newContext();
await browserContext.newPage();
await browserContext.close();
}
await browser.close();
});
it('should click background tab', async ({browserType, browserOptions, server}) => {
const browser = await browserType.launch({...browserOptions, headless: false });
const page = await browser.newPage();
await page.setContent(`<button>Hello</button><a target=_blank href="${server.EMPTY_PAGE}">empty.html</a>`);
await page.click('a');
await page.click('button');
await browser.close();
});
it('should close browser after context menu was triggered', async ({browserType, browserOptions, server}) => {
const browser = await browserType.launch({...browserOptions, headless: false });
const page = await browser.newPage();
await page.goto(server.PREFIX + '/grid.html');
await page.click('body', {button: 'right'});
await browser.close();
});
it('should(not) block third party cookies', async ({browserType, browserOptions, server, isChromium, isFirefox}) => {
const browser = await browserType.launch({...browserOptions, headless: false });
const page = await browser.newPage();
await page.goto(server.EMPTY_PAGE);
await page.evaluate(src => {
let fulfill;
const promise = new Promise(x => fulfill = x);
const iframe = document.createElement('iframe');
document.body.appendChild(iframe);
iframe.onload = fulfill;
iframe.src = src;
return promise;
}, server.CROSS_PROCESS_PREFIX + '/grid.html');
const documentCookie = await page.frames()[1].evaluate(() => {
document.cookie = 'username=John Doe';
return document.cookie;
});
await page.waitForTimeout(2000);
const allowsThirdParty = isChromium || isFirefox;
expect(documentCookie).toBe(allowsThirdParty ? 'username=John Doe' : '');
const cookies = await page.context().cookies(server.CROSS_PROCESS_PREFIX + '/grid.html');
if (allowsThirdParty) {
expect(cookies).toEqual([
{
'domain': '127.0.0.1',
'expires': -1,
'httpOnly': false,
'name': 'username',
'path': '/',
'sameSite': 'None',
'secure': false,
'value': 'John Doe'
}
]);
} else {
expect(cookies).toEqual([]);
}
await browser.close();
});
it('should not override viewport size when passed null', (test, { browserName }) => {
test.fixme(browserName === 'webkit');
}, async function({browserType, browserOptions, server}) {
// Our WebKit embedder does not respect window features.
const browser = await browserType.launch({...browserOptions, headless: false });
const context = await browser.newContext({ viewport: null });
const page = await context.newPage();
await page.goto(server.EMPTY_PAGE);
const [popup] = await Promise.all([
page.waitForEvent('popup'),
page.evaluate(() => {
const win = window.open(window.location.href, 'Title', 'toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes,width=600,height=300,top=0,left=0');
win.resizeTo(500, 450);
}),
]);
await popup.waitForLoadState();
await popup.waitForFunction(() => window.outerWidth === 500 && window.outerHeight === 450);
await context.close();
await browser.close();
});
it('Page.bringToFront should work', async ({browserType, browserOptions}) => {
const browser = await browserType.launch({...browserOptions, headless: false });
const page1 = await browser.newPage();
await page1.setContent('Page1');
const page2 = await browser.newPage();
await page2.setContent('Page2');
await page1.bringToFront();
expect(await page1.evaluate('document.visibilityState')).toBe('visible');
expect(await page2.evaluate('document.visibilityState')).toBe('visible');
await page2.bringToFront();
expect(await page1.evaluate('document.visibilityState')).toBe('visible');
expect(await page2.evaluate('document.visibilityState')).toBe(
'visible'
);
await browser.close();
});
const fixtures = folio.extend();
fixtures.testParametersPathSegment.override(async ({ browserName, platform }, run) => {
await run(browserName + '-' + platform);
});
fixtures.build().it('focused input should produce the same screenshot', (test, { browserName, platform }) => {
test.fail(browserName === 'firefox' && platform === 'darwin', 'headless has thinner outline');
test.fail(browserName === 'firefox' && platform === 'linux', 'headless has no outline');
test.skip(browserName === 'webkit' && platform === 'linux', 'gtk vs wpe');
}, async ({browserType, browserOptions}) => {
const headful = await browserType.launch({...browserOptions, headless: false });
const headfulPage = await headful.newPage();
await headfulPage.setContent('<input>');
await headfulPage.focus('input');
const headfulScreenshot = await headfulPage.screenshot();
await headful.close();
const headless = await browserType.launch({...browserOptions, headless: true });
const headlessPage = await headless.newPage();
await headlessPage.setContent('<input>');
await headlessPage.focus('input');
const headlessScreenshot = await headlessPage.screenshot();
await headless.close();
expect(headfulScreenshot).toMatchSnapshot('focused-input.png');
expect(headlessScreenshot).toMatchSnapshot('focused-input.png');
});
| test/headful.spec.ts | 0 | https://github.com/microsoft/playwright/commit/983e04374a881e4e0fbaf39ef6a57181fd951f1a | [
0.00017579703126102686,
0.00017153273802250624,
0.0001660983107285574,
0.00017158908303827047,
0.0000027231601507082814
] |
{
"id": 2,
"code_window": [
" library: 'pwExport',\n",
" libraryExport: 'default',\n",
" filename: 'consoleApiSource.js',\n",
" path: path.resolve(__dirname, '../../../lib/server/injected/packed')\n",
" },\n",
" plugins: [\n",
" new InlineSource(path.join(__dirname, '..', '..', '..', 'generated', 'consoleApiSource.ts')),\n",
" ]\n",
"};"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" path: path.resolve(__dirname, '../../../../lib/server/injected/packed')\n"
],
"file_path": "src/server/supplements/injected/consoleApi.webpack.config.js",
"type": "replace",
"edit_start_line_idx": 44
} | <style>
body, html { margin: 0; padding: 0; }
@keyframes move {
from { marign-left: 0; }
to { margin-left: 100px; }
}
</style>
<script>
function addButton() {
const button = document.createElement('button');
button.textContent = 'Click me';
button.style.animation = '3s linear move';
button.style.animationIterationCount = 'infinite';
button.addEventListener('click', () => window.clicked = true);
document.body.appendChild(button);
}
function stopButton(remove) {
const button = document.querySelector('button');
button.style.marginLeft = button.getBoundingClientRect().left + 'px';
button.style.animation = '';
if (remove)
button.remove();
}
let x = 0;
function jump() {
x += 300;
const button = document.querySelector('button');
button.style.marginLeft = x + 'px';
}
function startJumping() {
x = 0;
const moveIt = () => {
jump();
requestAnimationFrame(moveIt);
};
setInterval(jump, 0);
moveIt();
}
</script>
| test/assets/input/animating-button.html | 0 | https://github.com/microsoft/playwright/commit/983e04374a881e4e0fbaf39ef6a57181fd951f1a | [
0.00017433542234357446,
0.000171405597939156,
0.0001664563169470057,
0.0001724036264931783,
0.000002653126557561336
] |
{
"id": 2,
"code_window": [
" library: 'pwExport',\n",
" libraryExport: 'default',\n",
" filename: 'consoleApiSource.js',\n",
" path: path.resolve(__dirname, '../../../lib/server/injected/packed')\n",
" },\n",
" plugins: [\n",
" new InlineSource(path.join(__dirname, '..', '..', '..', 'generated', 'consoleApiSource.ts')),\n",
" ]\n",
"};"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" path: path.resolve(__dirname, '../../../../lib/server/injected/packed')\n"
],
"file_path": "src/server/supplements/injected/consoleApi.webpack.config.js",
"type": "replace",
"edit_start_line_idx": 44
} | <div id="outer" name="value"><div id="inner">Text,
more text</div></div><input id="check" type=checkbox checked foo="bar"">
| test/assets/dom.html | 0 | https://github.com/microsoft/playwright/commit/983e04374a881e4e0fbaf39ef6a57181fd951f1a | [
0.00017022278916556388,
0.00017022278916556388,
0.00017022278916556388,
0.00017022278916556388,
0
] |
{
"id": 3,
"code_window": [
" library: 'pwExport',\n",
" libraryExport: 'default',\n",
" filename: 'recorderSource.js',\n",
" path: path.resolve(__dirname, '../../../lib/server/injected/packed')\n",
" },\n",
" plugins: [\n",
" new InlineSource(path.join(__dirname, '..', '..', '..', 'generated', 'recorderSource.ts')),\n",
" ]\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" path: path.resolve(__dirname, '../../../../lib/server/injected/packed')\n"
],
"file_path": "src/server/supplements/injected/recorder.webpack.config.js",
"type": "replace",
"edit_start_line_idx": 44
} | /**
* Copyright (c) Microsoft Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import * as os from 'os';
import * as fs from 'fs';
import * as path from 'path';
import * as util from 'util';
import { CRPage } from '../../chromium/crPage';
import { Page } from '../../page';
import { ProgressController } from '../../progress';
import { createPlaywright } from '../../playwright';
import { EventEmitter } from 'events';
import { DEFAULT_ARGS } from '../../chromium/chromium';
const readFileAsync = util.promisify(fs.readFile);
export type Mode = 'inspecting' | 'recording' | 'none';
export type EventData = {
event: 'clear' | 'resume' | 'setMode',
params: any
};
declare global {
interface Window {
playwrightSetMode: (mode: Mode) => void;
playwrightSetPaused: (paused: boolean) => void;
playwrightSetSource: (params: { text: string, language: string }) => void;
dispatch(data: EventData): Promise<void>;
}
}
export class RecorderApp extends EventEmitter {
private _page: Page;
constructor(page: Page) {
super();
this.setMaxListeners(0);
this._page = page;
}
async close() {
await this._page.context().close();
}
private async _init() {
const icon = await readFileAsync(require.resolve('../../../../lib/web/recorder/app_icon.png'));
const crPopup = this._page._delegate as CRPage;
await crPopup._mainFrameSession._client.send('Browser.setDockTile', {
image: icon.toString('base64')
});
await this._page._setServerRequestInterceptor(async route => {
if (route.request().url().startsWith('https://playwright/')) {
const uri = route.request().url().substring('https://playwright/'.length);
const file = require.resolve('../../../../lib/web/recorder/' + uri);
const buffer = await readFileAsync(file);
await route.fulfill({
status: 200,
headers: [
{ name: 'Content-Type', value: extensionToMime[path.extname(file)] }
],
body: buffer.toString('base64'),
isBase64: true
});
return;
}
await route.continue();
});
await this._page.exposeBinding('dispatch', false, (_, data: any) => this.emit('event', data));
this._page.once('close', () => {
this.emit('close');
this._page.context().close().catch(e => console.error(e));
});
await this._page.mainFrame().goto(new ProgressController(), 'https://playwright/index.html');
}
static async open(): Promise<RecorderApp> {
const recorderPlaywright = createPlaywright(true);
const context = await recorderPlaywright.chromium.launchPersistentContext('', {
ignoreAllDefaultArgs: true,
args: [
...DEFAULT_ARGS,
`--user-data-dir=${path.join(os.homedir(),'.playwright-app')}`,
'--remote-debugging-pipe',
'--app=data:text/html,',
`--window-size=300,800`,
],
noDefaultViewport: true
});
const controller = new ProgressController();
await controller.run(async progress => {
await context._browser._defaultContext!._loadDefaultContextAsIs(progress);
});
const [page] = context.pages();
const result = new RecorderApp(page);
await result._init();
return result;
}
async setMode(mode: 'none' | 'recording' | 'inspecting'): Promise<void> {
await this._page.mainFrame()._evaluateExpression(((mode: Mode) => {
window.playwrightSetMode(mode);
}).toString(), true, mode, 'main').catch(() => {});
}
async setPaused(paused: boolean): Promise<void> {
await this._page.mainFrame()._evaluateExpression(((paused: boolean) => {
window.playwrightSetPaused(paused);
}).toString(), true, paused, 'main').catch(() => {});
}
async setSource(text: string, language: string): Promise<void> {
await this._page.mainFrame()._evaluateExpression(((param: { text: string, language: string }) => {
window.playwrightSetSource(param);
}).toString(), true, { text, language }, 'main').catch(() => {});
}
async bringToFront() {
await this._page.bringToFront();
}
}
const extensionToMime: { [key: string]: string } = {
'.css': 'text/css',
'.html': 'text/html',
'.jpeg': 'image/jpeg',
'.js': 'application/javascript',
'.png': 'image/png',
'.ttf': 'font/ttf',
'.svg': 'image/svg+xml',
'.webp': 'image/webp',
'.woff': 'font/woff',
'.woff2': 'font/woff2',
};
| src/server/supplements/recorder/recorderApp.ts | 1 | https://github.com/microsoft/playwright/commit/983e04374a881e4e0fbaf39ef6a57181fd951f1a | [
0.0007400812464766204,
0.00021353780175559223,
0.00016651696932967752,
0.0001735533296596259,
0.0001378422457491979
] |
{
"id": 3,
"code_window": [
" library: 'pwExport',\n",
" libraryExport: 'default',\n",
" filename: 'recorderSource.js',\n",
" path: path.resolve(__dirname, '../../../lib/server/injected/packed')\n",
" },\n",
" plugins: [\n",
" new InlineSource(path.join(__dirname, '..', '..', '..', 'generated', 'recorderSource.ts')),\n",
" ]\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" path: path.resolve(__dirname, '../../../../lib/server/injected/packed')\n"
],
"file_path": "src/server/supplements/injected/recorder.webpack.config.js",
"type": "replace",
"edit_start_line_idx": 44
} | /*
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.
*/
.action-list {
width: var(--sidebar-width);
display: flex;
flex-direction: column;
flex: none;
position: relative;
padding: 0 var(--layout-gap);
}
.action-entry {
position: relative;
display: flex;
flex-direction: column;
flex: none;
overflow: hidden;
border: 3px solid var(--background);
margin-top: var(--layout-gap);
user-select: none;
padding: 0 5px 5px 5px;
cursor: pointer;
outline: none;
}
.action-entry:hover {
border-color: var(--inactive-focus-ring);
}
.action-entry.selected {
border-color: var(--inactive-focus-ring);
}
.action-entry.selected:focus {
border-color: var(--orange);
}
.action-title {
display: inline;
white-space: nowrap;
font-weight: 600;
}
.action-header {
display: block;
align-items: center;
margin: 5px 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.action-header .action-error {
color: red;
top: 2px;
position: relative;
margin-right: 2px;
}
.action-selector {
display: inline;
padding-left: 5px;
}
.action-url {
display: inline;
padding-left: 5px;
}
.action-thumbnail {
flex: none;
display: flex;
align-items: center;
justify-content: center;
width: 200px;
height: 100px;
box-shadow: var(--box-shadow);
}
.action-thumbnail img {
max-width: 200px;
max-height: 100px;
}
| src/web/traceViewer/ui/actionList.css | 0 | https://github.com/microsoft/playwright/commit/983e04374a881e4e0fbaf39ef6a57181fd951f1a | [
0.0001764201879268512,
0.00017391768051311374,
0.00017157105321530253,
0.000173741762409918,
0.0000014646839190390892
] |
{
"id": 3,
"code_window": [
" library: 'pwExport',\n",
" libraryExport: 'default',\n",
" filename: 'recorderSource.js',\n",
" path: path.resolve(__dirname, '../../../lib/server/injected/packed')\n",
" },\n",
" plugins: [\n",
" new InlineSource(path.join(__dirname, '..', '..', '..', 'generated', 'recorderSource.ts')),\n",
" ]\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" path: path.resolve(__dirname, '../../../../lib/server/injected/packed')\n"
],
"file_path": "src/server/supplements/injected/recorder.webpack.config.js",
"type": "replace",
"edit_start_line_idx": 44
} | /**
* 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.
*/
type ServerResponse = import('http').ServerResponse;
type IncomingMessage = import('http').IncomingMessage;
export class TestServer {
static create(dirPath: string, port: number): Promise<TestServer>;
static createHTTPS(dirPath: string, port: number): Promise<TestServer>;
enableHTTPCache(pathPrefix: string);
setAuth(path: string, username: string, password: string);
enableGzip(path: string);
setCSP(path: string, csp: string);
stop(): Promise<void>;
setRoute(path: string, handler: (message: IncomingMessage & {postBody: Buffer}, response: ServerResponse) => void);
setRedirect(from: string, to: string);
waitForRequest(path: string): Promise<IncomingMessage & {postBody: Buffer}>;
reset();
serveFile(request: IncomingMessage, response: ServerResponse);
serveFile(request: IncomingMessage, response: ServerResponse, filePath: string);
PORT: number;
PREFIX: string;
CROSS_PROCESS_PREFIX: string;
EMPTY_PAGE: string;
}
| utils/testserver/index.d.ts | 0 | https://github.com/microsoft/playwright/commit/983e04374a881e4e0fbaf39ef6a57181fd951f1a | [
0.00017317385936621577,
0.00017132514039985836,
0.00016617435903754085,
0.0001729761715978384,
0.000002977587655550451
] |
{
"id": 3,
"code_window": [
" library: 'pwExport',\n",
" libraryExport: 'default',\n",
" filename: 'recorderSource.js',\n",
" path: path.resolve(__dirname, '../../../lib/server/injected/packed')\n",
" },\n",
" plugins: [\n",
" new InlineSource(path.join(__dirname, '..', '..', '..', 'generated', 'recorderSource.ts')),\n",
" ]\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" path: path.resolve(__dirname, '../../../../lib/server/injected/packed')\n"
],
"file_path": "src/server/supplements/injected/recorder.webpack.config.js",
"type": "replace",
"edit_start_line_idx": 44
} | /**
* Copyright 2017 Google Inc. All rights reserved.
* Modifications copyright (c) Microsoft Corporation.
*
* Licensed under the Apache License, Version 2.0 (the 'License');
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an 'AS IS' BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import * as input from '../input';
import * as types from '../types';
import { FFSession } from './ffConnection';
function toModifiersMask(modifiers: Set<types.KeyboardModifier>): number {
let mask = 0;
if (modifiers.has('Alt'))
mask |= 1;
if (modifiers.has('Control'))
mask |= 2;
if (modifiers.has('Shift'))
mask |= 4;
if (modifiers.has('Meta'))
mask |= 8;
return mask;
}
function toButtonNumber(button: types.MouseButton): number {
if (button === 'left')
return 0;
if (button === 'middle')
return 1;
if (button === 'right')
return 2;
return 0;
}
function toButtonsMask(buttons: Set<types.MouseButton>): number {
let mask = 0;
if (buttons.has('left'))
mask |= 1;
if (buttons.has('right'))
mask |= 2;
if (buttons.has('middle'))
mask |= 4;
return mask;
}
export class RawKeyboardImpl implements input.RawKeyboard {
private _client: FFSession;
constructor(client: FFSession) {
this._client = client;
}
async keydown(modifiers: Set<types.KeyboardModifier>, code: string, keyCode: number, keyCodeWithoutLocation: number, key: string, location: number, autoRepeat: boolean, text: string | undefined): Promise<void> {
if (code === 'MetaLeft')
code = 'OSLeft';
if (code === 'MetaRight')
code = 'OSRight';
// Firefox will figure out Enter by itself
if (text === '\r')
text = '';
await this._client.send('Page.dispatchKeyEvent', {
type: 'keydown',
keyCode: keyCodeWithoutLocation,
code,
key,
repeat: autoRepeat,
location,
text,
});
}
async keyup(modifiers: Set<types.KeyboardModifier>, code: string, keyCode: number, keyCodeWithoutLocation: number, key: string, location: number): Promise<void> {
if (code === 'MetaLeft')
code = 'OSLeft';
if (code === 'MetaRight')
code = 'OSRight';
await this._client.send('Page.dispatchKeyEvent', {
type: 'keyup',
key,
keyCode: keyCodeWithoutLocation,
code,
location,
repeat: false
});
}
async sendText(text: string): Promise<void> {
await this._client.send('Page.insertText', { text });
}
}
export class RawMouseImpl implements input.RawMouse {
private _client: FFSession;
constructor(client: FFSession) {
this._client = client;
}
async move(x: number, y: number, button: types.MouseButton | 'none', buttons: Set<types.MouseButton>, modifiers: Set<types.KeyboardModifier>): Promise<void> {
await this._client.send('Page.dispatchMouseEvent', {
type: 'mousemove',
button: 0,
buttons: toButtonsMask(buttons),
x,
y,
modifiers: toModifiersMask(modifiers)
});
}
async down(x: number, y: number, button: types.MouseButton, buttons: Set<types.MouseButton>, modifiers: Set<types.KeyboardModifier>, clickCount: number): Promise<void> {
await this._client.send('Page.dispatchMouseEvent', {
type: 'mousedown',
button: toButtonNumber(button),
buttons: toButtonsMask(buttons),
x,
y,
modifiers: toModifiersMask(modifiers),
clickCount
});
}
async up(x: number, y: number, button: types.MouseButton, buttons: Set<types.MouseButton>, modifiers: Set<types.KeyboardModifier>, clickCount: number): Promise<void> {
await this._client.send('Page.dispatchMouseEvent', {
type: 'mouseup',
button: toButtonNumber(button),
buttons: toButtonsMask(buttons),
x,
y,
modifiers: toModifiersMask(modifiers),
clickCount
});
}
}
export class RawTouchscreenImpl implements input.RawTouchscreen {
private _client: FFSession;
constructor(client: FFSession) {
this._client = client;
}
async tap(x: number, y: number, modifiers: Set<types.KeyboardModifier>) {
await this._client.send('Page.dispatchTapEvent', {
x,
y,
modifiers: toModifiersMask(modifiers),
});
}
}
| src/server/firefox/ffInput.ts | 0 | https://github.com/microsoft/playwright/commit/983e04374a881e4e0fbaf39ef6a57181fd951f1a | [
0.0001743322645779699,
0.00017056160140782595,
0.0001659616973483935,
0.0001711235527181998,
0.000002459140887367539
] |
{
"id": 4,
"code_window": [
" async close() {\n",
" await this._page.context().close();\n",
" }\n",
"\n",
" private async _init() {\n",
" const icon = await readFileAsync(require.resolve('../../../../lib/web/recorder/app_icon.png'));\n",
" const crPopup = this._page._delegate as CRPage;\n",
" await crPopup._mainFrameSession._client.send('Browser.setDockTile', {\n",
" image: icon.toString('base64')\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" const icon = await readFileAsync(require.resolve('../../../web/recorder/app_icon.png'));\n"
],
"file_path": "src/server/supplements/recorder/recorderApp.ts",
"type": "replace",
"edit_start_line_idx": 58
} | # NOTE: theoretically, we can remove this file, because we always create
# a directory for each package and only copy necessary files there.
# However, we keep it to double check the list of files.
#
# This ignores everything by default, except for package.json and LICENSE and README.md.
# See https://docs.npmjs.com/misc/developers
**/*
# Include sources from lib, but not map files.
!lib/**/*.js
# Exclude injected files. A preprocessed version of these is included via lib/generated.
# See src/server/injected/README.md.
lib/server/injected/
# Include all binaries that we ship with the package.
!bin/*
# Include FFMPEG
!third_party/ffmpeg/*
# Include generated types and entrypoint.
!types/*
!index.d.ts
# Include main entrypoint.
!index.js
# Include main entrypoint for ES Modules.
!index.mjs
# Include installer.
!install.js
# Include essentials.
!README.md
!LICENSE
!NOTICE
# Include protocol and api docs, so that dependent packages can consume them.
!api.json
!protocol.yml
# Include browser descriptors.
!browsers.json
# Include commit info
!commitinfo
| packages/common/.npmignore | 1 | https://github.com/microsoft/playwright/commit/983e04374a881e4e0fbaf39ef6a57181fd951f1a | [
0.0001733174140099436,
0.0001709676580503583,
0.00016702503489796072,
0.0001717640843708068,
0.0000024117496195685817
] |
{
"id": 4,
"code_window": [
" async close() {\n",
" await this._page.context().close();\n",
" }\n",
"\n",
" private async _init() {\n",
" const icon = await readFileAsync(require.resolve('../../../../lib/web/recorder/app_icon.png'));\n",
" const crPopup = this._page._delegate as CRPage;\n",
" await crPopup._mainFrameSession._client.send('Browser.setDockTile', {\n",
" image: icon.toString('base64')\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" const icon = await readFileAsync(require.resolve('../../../web/recorder/app_icon.png'));\n"
],
"file_path": "src/server/supplements/recorder/recorderApp.ts",
"type": "replace",
"edit_start_line_idx": 58
} | <!DOCTYPE html>
<html>
<head>
<title>Button test</title>
</head>
<body>
<script src="mouse-helper.js"></script>
<button>Click target</button>
<script>
window.result = 'Was not clicked';
window.offsetX = undefined;
window.offsetY = undefined;
window.pageX = undefined;
window.pageY = undefined;
window.shiftKey = undefined;
window.pageX = undefined;
window.pageY = undefined;
window.bubbles = undefined;
document.querySelector('button').addEventListener('click', e => {
result = 'Clicked';
offsetX = e.offsetX;
offsetY = e.offsetY;
pageX = e.pageX;
pageY = e.pageY;
shiftKey = e.shiftKey;
bubbles = e.bubbles;
cancelable = e.cancelable;
composed = e.composed;
}, false);
</script>
</body>
</html> | test/assets/input/button.html | 0 | https://github.com/microsoft/playwright/commit/983e04374a881e4e0fbaf39ef6a57181fd951f1a | [
0.0001725909678498283,
0.00017135405505541712,
0.00016880543262232095,
0.00017200992442667484,
0.0000015206693433356122
] |
{
"id": 4,
"code_window": [
" async close() {\n",
" await this._page.context().close();\n",
" }\n",
"\n",
" private async _init() {\n",
" const icon = await readFileAsync(require.resolve('../../../../lib/web/recorder/app_icon.png'));\n",
" const crPopup = this._page._delegate as CRPage;\n",
" await crPopup._mainFrameSession._client.send('Browser.setDockTile', {\n",
" image: icon.toString('base64')\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" const icon = await readFileAsync(require.resolve('../../../web/recorder/app_icon.png'));\n"
],
"file_path": "src/server/supplements/recorder/recorderApp.ts",
"type": "replace",
"edit_start_line_idx": 58
} | /**
* 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.
*/
import { expect, it } from './fixtures';
it('should work', async ({ page, server }) => {
const [request] = await Promise.all([
page.waitForEvent('requestfinished'),
page.goto(server.EMPTY_PAGE)
]);
const timing = request.timing();
verifyConnectionTimingConsistency(timing);
expect(timing.requestStart).toBeGreaterThanOrEqual(timing.connectEnd);
expect(timing.responseStart).toBeGreaterThanOrEqual(timing.requestStart);
expect(timing.responseEnd).toBeGreaterThanOrEqual(timing.responseStart);
expect(timing.responseEnd).toBeLessThan(10000);
});
it('should work for subresource', async ({ page, server }) => {
const requests = [];
page.on('requestfinished', request => requests.push(request));
await page.goto(server.PREFIX + '/one-style.html');
expect(requests.length).toBe(2);
const timing = requests[1].timing();
verifyConnectionTimingConsistency(timing);
expect(timing.requestStart).toBeGreaterThanOrEqual(0);
expect(timing.responseStart).toBeGreaterThan(timing.requestStart);
expect(timing.responseEnd).toBeGreaterThanOrEqual(timing.responseStart);
expect(timing.responseEnd).toBeLessThan(10000);
});
it('should work for SSL', async ({ browser, httpsServer }) => {
const page = await browser.newPage({ ignoreHTTPSErrors: true });
const [request] = await Promise.all([
page.waitForEvent('requestfinished'),
page.goto(httpsServer.EMPTY_PAGE)
]);
const timing = request.timing();
verifyConnectionTimingConsistency(timing);
expect(timing.requestStart).toBeGreaterThanOrEqual(timing.connectEnd);
expect(timing.responseStart).toBeGreaterThan(timing.requestStart);
expect(timing.responseEnd).toBeGreaterThanOrEqual(timing.responseStart);
expect(timing.responseEnd).toBeLessThan(10000);
await page.close();
});
it('should work for redirect', (test, { browserName }) => {
test.fixme(browserName === 'webkit', `In WebKit, redirects don't carry the timing info`);
}, async ({ page, server }) => {
server.setRedirect('/foo.html', '/empty.html');
const responses = [];
page.on('response', response => responses.push(response));
await page.goto(server.PREFIX + '/foo.html');
await Promise.all(responses.map(r => r.finished()));
expect(responses.length).toBe(2);
expect(responses[0].url()).toBe(server.PREFIX + '/foo.html');
expect(responses[1].url()).toBe(server.PREFIX + '/empty.html');
const timing1 = responses[0].request().timing();
verifyConnectionTimingConsistency(timing1);
expect(timing1.requestStart).toBeGreaterThanOrEqual(timing1.connectEnd);
expect(timing1.responseStart).toBeGreaterThan(timing1.requestStart);
expect(timing1.responseEnd).toBeGreaterThanOrEqual(timing1.responseStart);
expect(timing1.responseEnd).toBeLessThan(10000);
const timing2 = responses[1].request().timing();
verifyConnectionTimingConsistency(timing2);
expect(timing2.requestStart).toBeGreaterThanOrEqual(0);
expect(timing2.responseStart).toBeGreaterThan(timing2.requestStart);
expect(timing2.responseEnd).toBeGreaterThanOrEqual(timing2.responseStart);
expect(timing2.responseEnd).toBeLessThan(10000);
});
function verifyTimingValue(value: number, previous: number) {
expect(value === -1 || value > 0 && value >= previous);
}
function verifyConnectionTimingConsistency(timing) {
verifyTimingValue(timing.domainLookupStart, -1);
verifyTimingValue(timing.domainLookupEnd, timing.domainLookupStart);
verifyTimingValue(timing.connectStart, timing.domainLookupEnd);
verifyTimingValue(timing.secureConnectionStart, timing.connectStart);
verifyTimingValue(timing.connectEnd, timing.secureConnectionStart);
}
| test/resource-timing.spec.ts | 0 | https://github.com/microsoft/playwright/commit/983e04374a881e4e0fbaf39ef6a57181fd951f1a | [
0.0012168920366093516,
0.0002838703221641481,
0.00016622268594801426,
0.00017568556359037757,
0.00031125868554227054
] |
{
"id": 4,
"code_window": [
" async close() {\n",
" await this._page.context().close();\n",
" }\n",
"\n",
" private async _init() {\n",
" const icon = await readFileAsync(require.resolve('../../../../lib/web/recorder/app_icon.png'));\n",
" const crPopup = this._page._delegate as CRPage;\n",
" await crPopup._mainFrameSession._client.send('Browser.setDockTile', {\n",
" image: icon.toString('base64')\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" const icon = await readFileAsync(require.resolve('../../../web/recorder/app_icon.png'));\n"
],
"file_path": "src/server/supplements/recorder/recorderApp.ts",
"type": "replace",
"edit_start_line_idx": 58
} | /**
* Copyright 2020 Microsoft Corporation. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import type { Android, AndroidDevice } from '../../types/android';
import { folio as baseFolio } from '../fixtures';
const fixtures = baseFolio.extend<{
device: AndroidDevice
}, {
android: Android,
}>();
fixtures.device.init(async ({ playwright }, runTest) => {
const [device] = await playwright._android.devices();
await device.shell('am force-stop org.chromium.webview_shell');
await device.shell('am force-stop com.android.chrome');
device.setDefaultTimeout(120000);
await runTest(device);
await device.close();
});
export const folio = fixtures.build();
| test/android/android.fixtures.ts | 0 | https://github.com/microsoft/playwright/commit/983e04374a881e4e0fbaf39ef6a57181fd951f1a | [
0.00019615140627138317,
0.00018109909433405846,
0.00017491637845523655,
0.00017666432540863752,
0.000008736526069696993
] |
{
"id": 5,
"code_window": [
"\n",
" await this._page._setServerRequestInterceptor(async route => {\n",
" if (route.request().url().startsWith('https://playwright/')) {\n",
" const uri = route.request().url().substring('https://playwright/'.length);\n",
" const file = require.resolve('../../../../lib/web/recorder/' + uri);\n",
" const buffer = await readFileAsync(file);\n",
" await route.fulfill({\n",
" status: 200,\n",
" headers: [\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" const file = require.resolve('../../../web/recorder/' + uri);\n"
],
"file_path": "src/server/supplements/recorder/recorderApp.ts",
"type": "replace",
"edit_start_line_idx": 67
} | /**
* Copyright (c) Microsoft Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import * as os from 'os';
import * as fs from 'fs';
import * as path from 'path';
import * as util from 'util';
import { CRPage } from '../../chromium/crPage';
import { Page } from '../../page';
import { ProgressController } from '../../progress';
import { createPlaywright } from '../../playwright';
import { EventEmitter } from 'events';
import { DEFAULT_ARGS } from '../../chromium/chromium';
const readFileAsync = util.promisify(fs.readFile);
export type Mode = 'inspecting' | 'recording' | 'none';
export type EventData = {
event: 'clear' | 'resume' | 'setMode',
params: any
};
declare global {
interface Window {
playwrightSetMode: (mode: Mode) => void;
playwrightSetPaused: (paused: boolean) => void;
playwrightSetSource: (params: { text: string, language: string }) => void;
dispatch(data: EventData): Promise<void>;
}
}
export class RecorderApp extends EventEmitter {
private _page: Page;
constructor(page: Page) {
super();
this.setMaxListeners(0);
this._page = page;
}
async close() {
await this._page.context().close();
}
private async _init() {
const icon = await readFileAsync(require.resolve('../../../../lib/web/recorder/app_icon.png'));
const crPopup = this._page._delegate as CRPage;
await crPopup._mainFrameSession._client.send('Browser.setDockTile', {
image: icon.toString('base64')
});
await this._page._setServerRequestInterceptor(async route => {
if (route.request().url().startsWith('https://playwright/')) {
const uri = route.request().url().substring('https://playwright/'.length);
const file = require.resolve('../../../../lib/web/recorder/' + uri);
const buffer = await readFileAsync(file);
await route.fulfill({
status: 200,
headers: [
{ name: 'Content-Type', value: extensionToMime[path.extname(file)] }
],
body: buffer.toString('base64'),
isBase64: true
});
return;
}
await route.continue();
});
await this._page.exposeBinding('dispatch', false, (_, data: any) => this.emit('event', data));
this._page.once('close', () => {
this.emit('close');
this._page.context().close().catch(e => console.error(e));
});
await this._page.mainFrame().goto(new ProgressController(), 'https://playwright/index.html');
}
static async open(): Promise<RecorderApp> {
const recorderPlaywright = createPlaywright(true);
const context = await recorderPlaywright.chromium.launchPersistentContext('', {
ignoreAllDefaultArgs: true,
args: [
...DEFAULT_ARGS,
`--user-data-dir=${path.join(os.homedir(),'.playwright-app')}`,
'--remote-debugging-pipe',
'--app=data:text/html,',
`--window-size=300,800`,
],
noDefaultViewport: true
});
const controller = new ProgressController();
await controller.run(async progress => {
await context._browser._defaultContext!._loadDefaultContextAsIs(progress);
});
const [page] = context.pages();
const result = new RecorderApp(page);
await result._init();
return result;
}
async setMode(mode: 'none' | 'recording' | 'inspecting'): Promise<void> {
await this._page.mainFrame()._evaluateExpression(((mode: Mode) => {
window.playwrightSetMode(mode);
}).toString(), true, mode, 'main').catch(() => {});
}
async setPaused(paused: boolean): Promise<void> {
await this._page.mainFrame()._evaluateExpression(((paused: boolean) => {
window.playwrightSetPaused(paused);
}).toString(), true, paused, 'main').catch(() => {});
}
async setSource(text: string, language: string): Promise<void> {
await this._page.mainFrame()._evaluateExpression(((param: { text: string, language: string }) => {
window.playwrightSetSource(param);
}).toString(), true, { text, language }, 'main').catch(() => {});
}
async bringToFront() {
await this._page.bringToFront();
}
}
const extensionToMime: { [key: string]: string } = {
'.css': 'text/css',
'.html': 'text/html',
'.jpeg': 'image/jpeg',
'.js': 'application/javascript',
'.png': 'image/png',
'.ttf': 'font/ttf',
'.svg': 'image/svg+xml',
'.webp': 'image/webp',
'.woff': 'font/woff',
'.woff2': 'font/woff2',
};
| src/server/supplements/recorder/recorderApp.ts | 1 | https://github.com/microsoft/playwright/commit/983e04374a881e4e0fbaf39ef6a57181fd951f1a | [
0.9983508586883545,
0.12501616775989532,
0.0001670509809628129,
0.00018097046995535493,
0.32987844944000244
] |
{
"id": 5,
"code_window": [
"\n",
" await this._page._setServerRequestInterceptor(async route => {\n",
" if (route.request().url().startsWith('https://playwright/')) {\n",
" const uri = route.request().url().substring('https://playwright/'.length);\n",
" const file = require.resolve('../../../../lib/web/recorder/' + uri);\n",
" const buffer = await readFileAsync(file);\n",
" await route.fulfill({\n",
" status: 200,\n",
" headers: [\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" const file = require.resolve('../../../web/recorder/' + uri);\n"
],
"file_path": "src/server/supplements/recorder/recorderApp.ts",
"type": "replace",
"edit_start_line_idx": 67
} | <?xml version="1.0" encoding="utf-8"?>
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
<background android:drawable="@drawable/ic_launcher_background" />
<foreground android:drawable="@drawable/ic_launcher_foreground" />
</adaptive-icon>
| src/server/android/driver/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml | 0 | https://github.com/microsoft/playwright/commit/983e04374a881e4e0fbaf39ef6a57181fd951f1a | [
0.00017401522200088948,
0.00017401522200088948,
0.00017401522200088948,
0.00017401522200088948,
0
] |
{
"id": 5,
"code_window": [
"\n",
" await this._page._setServerRequestInterceptor(async route => {\n",
" if (route.request().url().startsWith('https://playwright/')) {\n",
" const uri = route.request().url().substring('https://playwright/'.length);\n",
" const file = require.resolve('../../../../lib/web/recorder/' + uri);\n",
" const buffer = await readFileAsync(file);\n",
" await route.fulfill({\n",
" status: 200,\n",
" headers: [\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" const file = require.resolve('../../../web/recorder/' + uri);\n"
],
"file_path": "src/server/supplements/recorder/recorderApp.ts",
"type": "replace",
"edit_start_line_idx": 67
} | /**
* 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.
*/
import { it, expect } from './fixtures';
it('should timeout waiting for display:none to be gone', async ({page, server}) => {
await page.goto(server.PREFIX + '/input/button.html');
await page.$eval('button', b => b.style.display = 'none');
const error = await page.click('button', { timeout: 5000 }).catch(e => e);
expect(error.message).toContain('page.click: Timeout 5000ms exceeded.');
expect(error.message).toContain('waiting for element to be visible, enabled and not moving');
expect(error.message).toContain('element is not visible - waiting');
});
it('should timeout waiting for visbility:hidden to be gone', async ({page, server}) => {
await page.goto(server.PREFIX + '/input/button.html');
await page.$eval('button', b => b.style.visibility = 'hidden');
const error = await page.click('button', { timeout: 5000 }).catch(e => e);
expect(error.message).toContain('page.click: Timeout 5000ms exceeded.');
expect(error.message).toContain('waiting for element to be visible, enabled and not moving');
expect(error.message).toContain('element is not visible - waiting');
});
| test/page-click-timeout-2.spec.ts | 0 | https://github.com/microsoft/playwright/commit/983e04374a881e4e0fbaf39ef6a57181fd951f1a | [
0.00017461641982663423,
0.00017197981651406735,
0.00016811746172606945,
0.00017259269952774048,
0.0000027176915864401963
] |
{
"id": 5,
"code_window": [
"\n",
" await this._page._setServerRequestInterceptor(async route => {\n",
" if (route.request().url().startsWith('https://playwright/')) {\n",
" const uri = route.request().url().substring('https://playwright/'.length);\n",
" const file = require.resolve('../../../../lib/web/recorder/' + uri);\n",
" const buffer = await readFileAsync(file);\n",
" await route.fulfill({\n",
" status: 200,\n",
" headers: [\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" const file = require.resolve('../../../web/recorder/' + uri);\n"
],
"file_path": "src/server/supplements/recorder/recorderApp.ts",
"type": "replace",
"edit_start_line_idx": 67
} | /**
* 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.
*/
import { it, expect } from './fixtures';
import { attachFrame } from './utils';
it('should work', async ({ page, server }) => {
await page.goto(server.EMPTY_PAGE);
await attachFrame(page, 'frame1', server.EMPTY_PAGE);
const elementHandle = await page.$('#frame1');
const frame = await elementHandle.contentFrame();
expect(frame).toBe(page.frames()[1]);
});
it('should work for cross-process iframes', async ({ page, server }) => {
await page.goto(server.EMPTY_PAGE);
await attachFrame(page, 'frame1', server.CROSS_PROCESS_PREFIX + '/empty.html');
const elementHandle = await page.$('#frame1');
const frame = await elementHandle.contentFrame();
expect(frame).toBe(page.frames()[1]);
});
it('should work for cross-frame evaluations', async ({ page, server }) => {
await page.goto(server.EMPTY_PAGE);
await attachFrame(page, 'frame1', server.EMPTY_PAGE);
const frame = page.frames()[1];
const elementHandle = await frame.evaluateHandle(() => window.top.document.querySelector('#frame1'));
expect(await elementHandle.contentFrame()).toBe(frame);
});
it('should return null for non-iframes', async ({ page, server }) => {
await page.goto(server.EMPTY_PAGE);
await attachFrame(page, 'frame1', server.EMPTY_PAGE);
const frame = page.frames()[1];
const elementHandle = await frame.evaluateHandle(() => document.body);
expect(await elementHandle.contentFrame()).toBe(null);
});
it('should return null for document.documentElement', async ({ page, server }) => {
await page.goto(server.EMPTY_PAGE);
await attachFrame(page, 'frame1', server.EMPTY_PAGE);
const frame = page.frames()[1];
const elementHandle = await frame.evaluateHandle(() => document.documentElement);
expect(await elementHandle.contentFrame()).toBe(null);
});
| test/elementhandle-content-frame.spec.ts | 0 | https://github.com/microsoft/playwright/commit/983e04374a881e4e0fbaf39ef6a57181fd951f1a | [
0.00017780785856302828,
0.0001708203344605863,
0.00016582566604483873,
0.0001695237442618236,
0.000004099182660866063
] |
{
"id": 6,
"code_window": [
" },\n",
" \"compileOnSave\": true,\n",
" \"include\": [\"src/**/*.ts\", \"src/**/*.js\"],\n",
" \"exclude\": [\"node_modules\", \"src/.eslintrc.js\", \"src/cli/traceViewer/web/**\"]\n",
"}"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
" \"exclude\": [\"node_modules\", \"src/.eslintrc.js\", \"src/web/**\", \"src/**/*webpack.config.js\"]\n"
],
"file_path": "tsconfig.json",
"type": "replace",
"edit_start_line_idx": 15
} | /**
* 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 child_process = require('child_process');
const path = require('path');
const chokidar = require('chokidar');
const steps = [];
const onChanges = [];
const watchMode = process.argv.slice(2).includes('--watch');
const ROOT = path.join(__dirname, '..', '..');
function filePath(relative) {
return path.join(ROOT, ...relative.split('/'));
}
function runWatch() {
function runOnChanges(paths, nodeFile) {
nodeFile = filePath(nodeFile);
function callback() {
child_process.spawnSync('node', [nodeFile], { stdio: 'inherit' });
}
chokidar.watch([...paths, nodeFile].map(filePath)).on('all', callback);
callback();
}
const spawns = [];
for (const step of steps)
spawns.push(child_process.spawn(step.command, step.args, { stdio: 'inherit', shell: step.shell, env: {
...process.env,
...step.env,
} }));
process.on('exit', () => spawns.forEach(s => s.kill()));
for (const onChange of onChanges)
runOnChanges(onChange.inputs, onChange.script);
}
function runBuild() {
function runStep(command, args, shell) {
const out = child_process.spawnSync(command, args, { stdio: 'inherit', shell });
if (out.status)
process.exit(out.status);
}
for (const step of steps)
runStep(step.command, step.args, step.shell);
for (const onChange of onChanges) {
if (!onChange.committed)
runStep('node', [filePath(onChange.script)], false);
}
}
// Build injected scripts.
const webPackFiles = [
'src/server/injected/injectedScript.webpack.config.js',
'src/server/injected/utilityScript.webpack.config.js',
'src/server/supplements/injected/consoleApi.webpack.config.js',
'src/server/supplements/injected/recorder.webpack.config.js',
'src/web/traceViewer/webpack.config.js',
'src/web/recorder/webpack.config.js',
];
for (const file of webPackFiles) {
steps.push({
command: 'npx',
args: ['webpack', '--config', filePath(file), ...(watchMode ? ['--watch', '--silent'] : [])],
shell: true,
env: {
NODE_ENV: watchMode ? 'development' : 'production'
}
});
}
// Run typescript.
steps.push({
command: 'npx',
args: ['tsc', ...(watchMode ? ['-w', '--preserveWatchOutput'] : []), '-p', filePath('.')],
shell: true,
});
// Generate api.json.
onChanges.push({
committed: false,
inputs: [
'docs/src/api/',
],
script: 'utils/doclint/generateApiJson.js',
});
// Generate channels.
onChanges.push({
committed: false,
inputs: [
'src/protocol/protocol.yml'
],
script: 'utils/generate_channels.js',
});
// Generate types.
onChanges.push({
committed: false,
inputs: [
'docs/src/api/',
'utils/generate_types/overrides.d.ts',
'utils/generate_types/exported.json',
'src/server/chromium/protocol.ts',
'src/trace/traceTypes.ts',
],
script: 'utils/generate_types/index.js',
});
// Copy images.
steps.push({
command: process.platform === 'win32' ? 'copy' : 'cp',
args: ['src/web/recorder/*.png'.replace(/\//g, path.sep), 'lib/web/recorder/'.replace(/\//g, path.sep)],
shell: true,
});
watchMode ? runWatch() : runBuild();
| utils/build/build.js | 1 | https://github.com/microsoft/playwright/commit/983e04374a881e4e0fbaf39ef6a57181fd951f1a | [
0.00019626572611741722,
0.00017259336891584098,
0.00016786003834567964,
0.00016983434034045786,
0.0000072587645263411105
] |
{
"id": 6,
"code_window": [
" },\n",
" \"compileOnSave\": true,\n",
" \"include\": [\"src/**/*.ts\", \"src/**/*.js\"],\n",
" \"exclude\": [\"node_modules\", \"src/.eslintrc.js\", \"src/cli/traceViewer/web/**\"]\n",
"}"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
" \"exclude\": [\"node_modules\", \"src/.eslintrc.js\", \"src/web/**\", \"src/**/*webpack.config.js\"]\n"
],
"file_path": "tsconfig.json",
"type": "replace",
"edit_start_line_idx": 15
} | /*
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.
*/
.logs-tab {
flex: auto;
position: relative;
overflow: auto;
background: #fdfcfc;
font-family: var(--monospace-font);
white-space: nowrap;
}
.log-line {
margin: 0 10px;
white-space: pre;
}
| src/web/traceViewer/ui/logsTab.css | 0 | https://github.com/microsoft/playwright/commit/983e04374a881e4e0fbaf39ef6a57181fd951f1a | [
0.0001743936154525727,
0.0001729840732878074,
0.00017215017578564584,
0.00017240841407328844,
0.0000010022604328696616
] |
{
"id": 6,
"code_window": [
" },\n",
" \"compileOnSave\": true,\n",
" \"include\": [\"src/**/*.ts\", \"src/**/*.js\"],\n",
" \"exclude\": [\"node_modules\", \"src/.eslintrc.js\", \"src/cli/traceViewer/web/**\"]\n",
"}"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
" \"exclude\": [\"node_modules\", \"src/.eslintrc.js\", \"src/web/**\", \"src/**/*webpack.config.js\"]\n"
],
"file_path": "tsconfig.json",
"type": "replace",
"edit_start_line_idx": 15
} | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include "nsScreencastService.h"
#include "ScreencastEncoder.h"
#include "HeadlessWidget.h"
#include "HeadlessWindowCapturer.h"
#include "mozilla/ClearOnShutdown.h"
#include "mozilla/PresShell.h"
#include "mozilla/StaticPtr.h"
#include "nsIDocShell.h"
#include "nsIObserverService.h"
#include "nsIRandomGenerator.h"
#include "nsISupportsPrimitives.h"
#include "nsThreadManager.h"
#include "nsView.h"
#include "nsViewManager.h"
#include "webrtc/modules/desktop_capture/desktop_capturer.h"
#include "webrtc/modules/desktop_capture/desktop_capture_options.h"
#include "webrtc/modules/desktop_capture/desktop_device_info.h"
#include "webrtc/modules/desktop_capture/desktop_frame.h"
#include "webrtc/modules/video_capture/video_capture.h"
#include "mozilla/widget/PlatformWidgetTypes.h"
#include "video_engine/desktop_capture_impl.h"
using namespace mozilla::widget;
namespace mozilla {
NS_IMPL_ISUPPORTS(nsScreencastService, nsIScreencastService)
namespace {
StaticRefPtr<nsScreencastService> gScreencastService;
rtc::scoped_refptr<webrtc::VideoCaptureModule> CreateWindowCapturer(nsIWidget* widget) {
if (gfxPlatform::IsHeadless()) {
HeadlessWidget* headlessWidget = static_cast<HeadlessWidget*>(widget);
return HeadlessWindowCapturer::Create(headlessWidget);
}
uintptr_t rawWindowId = reinterpret_cast<uintptr_t>(widget->GetNativeData(NS_NATIVE_WINDOW_WEBRTC_DEVICE_ID));
if (!rawWindowId) {
fprintf(stderr, "Failed to get native window id\n");
return nullptr;
}
nsCString windowId;
windowId.AppendPrintf("%" PRIuPTR, rawWindowId);
bool captureCursor = false;
static int moduleId = 0;
return webrtc::DesktopCaptureImpl::Create(++moduleId, windowId.get(), webrtc::CaptureDeviceType::Window, captureCursor);
}
void NotifyScreencastStopped(const nsString& sessionId) {
nsCOMPtr<nsIObserverService> observerService = mozilla::services::GetObserverService();
if (!observerService) {
fprintf(stderr, "NotifyScreencastStopped error: no observer service\n");
return;
}
observerService->NotifyObservers(nullptr, "juggler-screencast-stopped", sessionId.get());
}
nsresult generateUid(nsString& uid) {
nsresult rv = NS_OK;
nsCOMPtr<nsIRandomGenerator> rg = do_GetService("@mozilla.org/security/random-generator;1", &rv);
NS_ENSURE_SUCCESS(rv, rv);
uint8_t* buffer;
const int kLen = 16;
rv = rg->GenerateRandomBytes(kLen, &buffer);
NS_ENSURE_SUCCESS(rv, rv);
for (int i = 0; i < kLen; i++) {
uid.AppendPrintf("%02x", buffer[i]);
}
free(buffer);
return rv;
}
}
class nsScreencastService::Session : public rtc::VideoSinkInterface<webrtc::VideoFrame> {
public:
Session(rtc::scoped_refptr<webrtc::VideoCaptureModule>&& capturer, RefPtr<ScreencastEncoder>&& encoder)
: mCaptureModule(std::move(capturer))
, mEncoder(std::move(encoder)) {
}
bool Start() {
webrtc::VideoCaptureCapability capability;
// The size is ignored in fact.
capability.width = 1280;
capability.height = 960;
capability.maxFPS = ScreencastEncoder::fps;
capability.videoType = webrtc::VideoType::kI420;
int error = mCaptureModule->StartCapture(capability);
if (error) {
fprintf(stderr, "StartCapture error %d\n", error);
return false;
}
mCaptureModule->RegisterCaptureDataCallback(this);
return true;
}
void Stop(std::function<void()>&& callback) {
mCaptureModule->DeRegisterCaptureDataCallback(this);
int error = mCaptureModule->StopCapture();
if (error) {
fprintf(stderr, "StopCapture error %d\n", error);
}
mEncoder->finish(std::move(callback));
}
// These callbacks end up running on the VideoCapture thread.
void OnFrame(const webrtc::VideoFrame& videoFrame) override {
mEncoder->encodeFrame(videoFrame);
}
private:
rtc::scoped_refptr<webrtc::VideoCaptureModule> mCaptureModule;
RefPtr<ScreencastEncoder> mEncoder;
};
// static
already_AddRefed<nsIScreencastService> nsScreencastService::GetSingleton() {
if (gScreencastService) {
return do_AddRef(gScreencastService);
}
gScreencastService = new nsScreencastService();
// ClearOnShutdown(&gScreencastService);
return do_AddRef(gScreencastService);
}
nsScreencastService::nsScreencastService() = default;
nsScreencastService::~nsScreencastService() {
}
nsresult nsScreencastService::StartVideoRecording(nsIDocShell* aDocShell, const nsACString& aFileName, uint32_t width, uint32_t height, double scale, int32_t offsetTop, nsAString& sessionId) {
MOZ_RELEASE_ASSERT(NS_IsMainThread(), "Screencast service must be started on the Main thread.");
PresShell* presShell = aDocShell->GetPresShell();
if (!presShell)
return NS_ERROR_UNEXPECTED;
nsViewManager* viewManager = presShell->GetViewManager();
if (!viewManager)
return NS_ERROR_UNEXPECTED;
nsView* view = viewManager->GetRootView();
if (!view)
return NS_ERROR_UNEXPECTED;
nsIWidget* widget = view->GetWidget();
rtc::scoped_refptr<webrtc::VideoCaptureModule> capturer = CreateWindowCapturer(widget);
if (!capturer)
return NS_ERROR_FAILURE;
nsCString error;
Maybe<double> maybeScale;
if (scale)
maybeScale = Some(scale);
gfx::IntMargin margin;
// On GTK the bottom of the client rect is below the bounds and
// client size is actually equal to the size of the bounds so
// we don't need an adjustment.
#ifndef MOZ_WIDGET_GTK
auto bounds = widget->GetScreenBounds().ToUnknownRect();
auto clientBounds = widget->GetClientBounds().ToUnknownRect();
// Crop the image to exclude frame (if any).
margin = bounds - clientBounds;
#endif
// Crop the image to exclude controls.
margin.top += offsetTop;
RefPtr<ScreencastEncoder> encoder = ScreencastEncoder::create(error, PromiseFlatCString(aFileName), width, height, maybeScale, margin);
if (!encoder) {
fprintf(stderr, "Failed to create ScreencastEncoder: %s\n", error.get());
return NS_ERROR_FAILURE;
}
auto session = std::make_unique<Session>(std::move(capturer), std::move(encoder));
if (!session->Start())
return NS_ERROR_FAILURE;
nsString uid;
nsresult rv = generateUid(uid);
NS_ENSURE_SUCCESS(rv, rv);
sessionId = uid;
mIdToSession.emplace(uid, std::move(session));
return NS_OK;
}
nsresult nsScreencastService::StopVideoRecording(const nsAString& aSessionId) {
nsString sessionId(aSessionId);
auto it = mIdToSession.find(sessionId);
if (it == mIdToSession.end())
return NS_ERROR_INVALID_ARG;
it->second->Stop([sessionId] {
NS_DispatchToMainThread(NS_NewRunnableFunction(
"NotifyScreencastStopped", [sessionId]() -> void {
NotifyScreencastStopped(sessionId);
}));
});
mIdToSession.erase(it);
return NS_OK;
}
} // namespace mozilla
| browser_patches/firefox/juggler/screencast/nsScreencastService.cpp | 0 | https://github.com/microsoft/playwright/commit/983e04374a881e4e0fbaf39ef6a57181fd951f1a | [
0.00017496007785666734,
0.00016953535669017583,
0.00016453792341053486,
0.0001701725705061108,
0.000002475380597388721
] |
{
"id": 6,
"code_window": [
" },\n",
" \"compileOnSave\": true,\n",
" \"include\": [\"src/**/*.ts\", \"src/**/*.js\"],\n",
" \"exclude\": [\"node_modules\", \"src/.eslintrc.js\", \"src/cli/traceViewer/web/**\"]\n",
"}"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
" \"exclude\": [\"node_modules\", \"src/.eslintrc.js\", \"src/web/**\", \"src/**/*webpack.config.js\"]\n"
],
"file_path": "tsconfig.json",
"type": "replace",
"edit_start_line_idx": 15
} | /**
* 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 function applyTheme() {
if ((document as any).playwrightThemeInitialized)
return;
(document as any).playwrightThemeInitialized = true;
document!.defaultView!.addEventListener('focus', (event: any) => {
if (event.target.document.nodeType === Node.DOCUMENT_NODE)
document.body.classList.remove('inactive');
}, false);
document!.defaultView!.addEventListener('blur', event => {
document.body.classList.add('inactive');
}, false);
}
| src/web/theme.ts | 0 | https://github.com/microsoft/playwright/commit/983e04374a881e4e0fbaf39ef6a57181fd951f1a | [
0.00017125168233178556,
0.00017039687372744083,
0.0001693950907792896,
0.00017054380441550165,
7.650393172298209e-7
] |
{
"id": 7,
"code_window": [
"\n",
"// Copy images.\n",
"steps.push({\n",
" command: process.platform === 'win32' ? 'copy' : 'cp',\n",
" args: ['src/web/recorder/*.png'.replace(/\\//g, path.sep), 'lib/web/recorder/'.replace(/\\//g, path.sep)],\n",
" shell: true,\n",
"});\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" args: [filePath('src/web/recorder/*.png'), filePath('lib/web/recorder/')],\n"
],
"file_path": "utils/build/build.js",
"type": "replace",
"edit_start_line_idx": 127
} | /**
* 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 path = require('path');
const InlineSource = require('../../injected/webpack-inline-source-plugin');
/** @type {import('webpack').Configuration} */
module.exports = {
entry: path.join(__dirname, 'consoleApi.ts'),
mode: process.env.NODE_ENV === 'production' ? 'production' : 'development',
devtool: false,
module: {
rules: [
{
test: /\.(j|t)sx?$/,
loader: 'ts-loader',
options: {
transpileOnly: true
},
exclude: /node_modules/
}
]
},
resolve: {
extensions: [ '.tsx', '.ts', '.js' ]
},
output: {
libraryTarget: 'var',
library: 'pwExport',
libraryExport: 'default',
filename: 'consoleApiSource.js',
path: path.resolve(__dirname, '../../../lib/server/injected/packed')
},
plugins: [
new InlineSource(path.join(__dirname, '..', '..', '..', 'generated', 'consoleApiSource.ts')),
]
};
| src/server/supplements/injected/consoleApi.webpack.config.js | 1 | https://github.com/microsoft/playwright/commit/983e04374a881e4e0fbaf39ef6a57181fd951f1a | [
0.0003139356558676809,
0.00019598340441007167,
0.00016602041432633996,
0.00017376580217387527,
0.000052834693633485585
] |
{
"id": 7,
"code_window": [
"\n",
"// Copy images.\n",
"steps.push({\n",
" command: process.platform === 'win32' ? 'copy' : 'cp',\n",
" args: ['src/web/recorder/*.png'.replace(/\\//g, path.sep), 'lib/web/recorder/'.replace(/\\//g, path.sep)],\n",
" shell: true,\n",
"});\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" args: [filePath('src/web/recorder/*.png'), filePath('lib/web/recorder/')],\n"
],
"file_path": "utils/build/build.js",
"type": "replace",
"edit_start_line_idx": 127
} | /**
* Copyright 2019 Microsoft Corporation All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { helper, RegisteredListener } from '../helper';
import { Page, Worker } from '../page';
import { Protocol } from './protocol';
import { WKSession } from './wkConnection';
import { WKExecutionContext } from './wkExecutionContext';
import * as types from '../types';
export class WKWorkers {
private _sessionListeners: RegisteredListener[] = [];
private _page: Page;
private _workerSessions = new Map<string, WKSession>();
constructor(page: Page) {
this._page = page;
}
setSession(session: WKSession) {
helper.removeEventListeners(this._sessionListeners);
this.clear();
this._sessionListeners = [
helper.addEventListener(session, 'Worker.workerCreated', (event: Protocol.Worker.workerCreatedPayload) => {
const worker = new Worker(event.url);
const workerSession = new WKSession(session.connection, event.workerId, 'Most likely the worker has been closed.', (message: any) => {
session.send('Worker.sendMessageToWorker', {
workerId: event.workerId,
message: JSON.stringify(message)
}).catch(e => {
workerSession.dispatchMessage({ id: message.id, error: { message: e.message } });
});
});
this._workerSessions.set(event.workerId, workerSession);
worker._createExecutionContext(new WKExecutionContext(workerSession, undefined));
this._page._addWorker(event.workerId, worker);
workerSession.on('Console.messageAdded', event => this._onConsoleMessage(worker, event));
Promise.all([
workerSession.send('Runtime.enable'),
workerSession.send('Console.enable'),
session.send('Worker.initialized', { workerId: event.workerId })
]).catch(e => {
// Worker can go as we are initializing it.
this._page._removeWorker(event.workerId);
});
}),
helper.addEventListener(session, 'Worker.dispatchMessageFromWorker', (event: Protocol.Worker.dispatchMessageFromWorkerPayload) => {
const workerSession = this._workerSessions.get(event.workerId)!;
if (!workerSession)
return;
workerSession.dispatchMessage(JSON.parse(event.message));
}),
helper.addEventListener(session, 'Worker.workerTerminated', (event: Protocol.Worker.workerTerminatedPayload) => {
const workerSession = this._workerSessions.get(event.workerId)!;
if (!workerSession)
return;
workerSession.dispose(false);
this._workerSessions.delete(event.workerId);
this._page._removeWorker(event.workerId);
})
];
}
clear() {
this._page._clearWorkers();
this._workerSessions.clear();
}
async initializeSession(session: WKSession) {
await session.send('Worker.enable');
}
async _onConsoleMessage(worker: Worker, event: Protocol.Console.messageAddedPayload) {
const { type, level, text, parameters, url, line: lineNumber, column: columnNumber } = event.message;
let derivedType: string = type || '';
if (type === 'log')
derivedType = level;
else if (type === 'timing')
derivedType = 'timeEnd';
const handles = (parameters || []).map(p => {
return worker._existingExecutionContext!.createHandle(p);
});
const location: types.ConsoleMessageLocation = {
url: url || '',
lineNumber: (lineNumber || 1) - 1,
columnNumber: (columnNumber || 1) - 1
};
this._page._addConsoleMessage(derivedType, handles, location, handles.length ? undefined : text);
}
}
| src/server/webkit/wkWorkers.ts | 0 | https://github.com/microsoft/playwright/commit/983e04374a881e4e0fbaf39ef6a57181fd951f1a | [
0.00017999437113758177,
0.00017366257088724524,
0.0001704189635347575,
0.00017355075397063047,
0.000002407790589131764
] |
{
"id": 7,
"code_window": [
"\n",
"// Copy images.\n",
"steps.push({\n",
" command: process.platform === 'win32' ? 'copy' : 'cp',\n",
" args: ['src/web/recorder/*.png'.replace(/\\//g, path.sep), 'lib/web/recorder/'.replace(/\\//g, path.sep)],\n",
" shell: true,\n",
"});\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" args: [filePath('src/web/recorder/*.png'), filePath('lib/web/recorder/')],\n"
],
"file_path": "utils/build/build.js",
"type": "replace",
"edit_start_line_idx": 127
} | <?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "1140"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
buildImplicitDependencies = "YES">
<BuildActionEntries>
<BuildActionEntry
buildForTesting = "YES"
buildForRunning = "YES"
buildForProfiling = "YES"
buildForArchiving = "YES"
buildForAnalyzing = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "8D1107260486CEB800E47090"
BuildableName = "Playwright.app"
BlueprintName = "Playwright"
ReferencedContainer = "container:Playwright.xcodeproj">
</BuildableReference>
</BuildActionEntry>
</BuildActionEntries>
</BuildAction>
<TestAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
shouldUseLaunchSchemeArgsEnv = "YES">
<Testables>
</Testables>
</TestAction>
<LaunchAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
launchStyle = "0"
useCustomWorkingDirectory = "NO"
ignoresPersistentStateOnLaunch = "NO"
debugDocumentVersioning = "YES"
debugServiceExtension = "internal"
allowLocationSimulation = "YES">
<BuildableProductRunnable
runnableDebuggingMode = "0">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "8D1107260486CEB800E47090"
BuildableName = "Playwright.app"
BlueprintName = "Playwright"
ReferencedContainer = "container:Playwright.xcodeproj">
</BuildableReference>
</BuildableProductRunnable>
</LaunchAction>
<ProfileAction
buildConfiguration = "Release"
shouldUseLaunchSchemeArgsEnv = "YES"
savedToolIdentifier = ""
useCustomWorkingDirectory = "NO"
debugDocumentVersioning = "YES">
<BuildableProductRunnable
runnableDebuggingMode = "0">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "8D1107260486CEB800E47090"
BuildableName = "Playwright.app"
BlueprintName = "Playwright"
ReferencedContainer = "container:Playwright.xcodeproj">
</BuildableReference>
</BuildableProductRunnable>
</ProfileAction>
<AnalyzeAction
buildConfiguration = "Debug">
</AnalyzeAction>
<ArchiveAction
buildConfiguration = "Release"
revealArchiveInOrganizer = "YES">
</ArchiveAction>
</Scheme>
| browser_patches/webkit/embedder/Playwright/Playwright.xcodeproj/xcshareddata/xcschemes/Playwright.xcscheme | 0 | https://github.com/microsoft/playwright/commit/983e04374a881e4e0fbaf39ef6a57181fd951f1a | [
0.00017697903967928141,
0.0001757684221956879,
0.00017390426364727318,
0.0001758125436026603,
9.028952945300261e-7
] |
{
"id": 7,
"code_window": [
"\n",
"// Copy images.\n",
"steps.push({\n",
" command: process.platform === 'win32' ? 'copy' : 'cp',\n",
" args: ['src/web/recorder/*.png'.replace(/\\//g, path.sep), 'lib/web/recorder/'.replace(/\\//g, path.sep)],\n",
" shell: true,\n",
"});\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" args: [filePath('src/web/recorder/*.png'), filePath('lib/web/recorder/')],\n"
],
"file_path": "utils/build/build.js",
"type": "replace",
"edit_start_line_idx": 127
} | /**
* Copyright (c) Microsoft Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import * as path from 'path';
import * as fs from 'fs';
import { folio } from './cli.fixtures';
const { it, expect } = folio;
const emptyHTML = new URL('file://' + path.join(__dirname, '..', 'assets', 'empty.html')).toString();
it('should print the correct imports and context options', async ({ runCLI }) => {
const cli = runCLI(['codegen', '--target=csharp', emptyHTML]);
const expectedResult = `await Playwright.InstallAsync();
using var playwright = await Playwright.CreateAsync();
await using var browser = await playwright.Chromium.LaunchAsync(headless: false);
var context = await browser.NewContextAsync();`;
await cli.waitFor(expectedResult).catch(e => e);
expect(cli.text()).toContain(expectedResult);
});
it('should print the correct context options for custom settings', async ({ runCLI }) => {
const cli = runCLI([
'--color-scheme=dark',
'--geolocation=37.819722,-122.478611',
'--lang=es',
'--proxy-server=http://myproxy:3128',
'--timezone=Europe/Rome',
'--timeout=1000',
'--user-agent=hardkodemium',
'--viewport-size=1280,720',
'codegen',
'--target=csharp',
emptyHTML]);
const expectedResult = `await Playwright.InstallAsync();
using var playwright = await Playwright.CreateAsync();
await using var browser = await playwright.Chromium.LaunchAsync(
headless: false,
proxy: new ProxySettings
{
Server = "http://myproxy:3128",
});
var context = await browser.NewContextAsync(
viewport: new ViewportSize
{
Width = 1280,
Height = 720,
},
geolocation: new Geolocation
{
Latitude = 37.819722m,
Longitude = -122.478611m,
},
permissions: new[] { ContextPermission.Geolocation },
userAgent: "hardkodemium",
locale: "es",
colorScheme: ColorScheme.Dark,
timezoneId: "Europe/Rome");`;
await cli.waitFor(expectedResult);
expect(cli.text()).toContain(expectedResult);
});
it('should print the correct context options when using a device', async ({ runCLI }) => {
const cli = runCLI(['--device=Pixel 2', 'codegen', '--target=csharp', emptyHTML]);
const expectedResult = `await Playwright.InstallAsync();
using var playwright = await Playwright.CreateAsync();
await using var browser = await playwright.Chromium.LaunchAsync(headless: false);
var context = await browser.NewContextAsync(playwright.Devices["Pixel 2"]);`;
await cli.waitFor(expectedResult);
expect(cli.text()).toContain(expectedResult);
});
it('should print the correct context options when using a device and additional options', async ({ runCLI }) => {
const cli = runCLI([
'--device=Pixel 2',
'--color-scheme=dark',
'--geolocation=37.819722,-122.478611',
'--lang=es',
'--proxy-server=http://myproxy:3128',
'--timezone=Europe/Rome',
'--timeout=1000',
'--user-agent=hardkodemium',
'--viewport-size=1280,720',
'codegen',
'--target=csharp',
emptyHTML]);
const expectedResult = `await Playwright.InstallAsync();
using var playwright = await Playwright.CreateAsync();
await using var browser = await playwright.Chromium.LaunchAsync(
headless: false,
proxy: new ProxySettings
{
Server = "http://myproxy:3128",
});
var context = await browser.NewContextAsync(new BrowserContextOptions(playwright.Devices["Pixel 2"])
{
UserAgent = "hardkodemium",
Viewport = new ViewportSize
{
Width = 1280,
Height = 720,
},
Geolocation = new Geolocation
{
Latitude = 37.819722m,
Longitude = -122.478611m,
},
Permissions = new[] { ContextPermission.Geolocation },
Locale = "es",
ColorScheme = ColorScheme.Dark,
TimezoneId = "Europe/Rome",
});`;
await cli.waitFor(expectedResult);
expect(cli.text()).toContain(expectedResult);
});
it('should print load/save storageState', async ({ runCLI, testInfo }) => {
const loadFileName = testInfo.outputPath('load.json');
const saveFileName = testInfo.outputPath('save.json');
await fs.promises.writeFile(loadFileName, JSON.stringify({ cookies: [], origins: [] }), 'utf8');
const cli = runCLI([`--load-storage=${loadFileName}`, `--save-storage=${saveFileName}`, 'codegen', '--target=csharp', emptyHTML]);
const expectedResult = `await Playwright.InstallAsync();
using var playwright = await Playwright.CreateAsync();
await using var browser = await playwright.Chromium.LaunchAsync(headless: false);
var context = await browser.NewContextAsync(storageState: "${loadFileName}");
// Open new page
var page = await context.NewPageAsync();
// ---------------------
await context.StorageStateAsync(path: "${saveFileName}");
`;
await cli.waitFor(expectedResult);
});
| test/cli/cli-codegen-csharp.spec.ts | 0 | https://github.com/microsoft/playwright/commit/983e04374a881e4e0fbaf39ef6a57181fd951f1a | [
0.00017781532369554043,
0.0001746244524838403,
0.00016412987315561622,
0.00017596589168533683,
0.0000031824247344047762
] |
{
"id": 0,
"code_window": [
"import type { ActionOptions } from '../models';\n",
"\n",
"export const config: ActionOptions = {\n",
" depth: 6,\n",
" clearOnStoryChange: true,\n",
" limit: 50,\n",
"};\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" depth: 10,\n"
],
"file_path": "code/addons/actions/src/runtime/configureActions.ts",
"type": "replace",
"edit_start_line_idx": 3
} | import { dequal as deepEqual } from 'dequal';
import type { Renderer, Args, ArgTypes, InputType, SBType, StoryContext } from '@storybook/types';
import { once } from '@storybook/client-logger';
import isPlainObject from 'lodash/isPlainObject.js';
import { dedent } from 'ts-dedent';
const INCOMPATIBLE = Symbol('incompatible');
const map = (arg: unknown, argType: InputType): any => {
const type = argType.type as SBType;
if (arg === undefined || arg === null || !type) return arg;
if (argType.mapping) {
return arg;
}
switch (type.name) {
case 'string':
return String(arg);
case 'enum':
return arg;
case 'number':
return Number(arg);
case 'boolean':
return arg === 'true';
case 'array':
if (!type.value || !Array.isArray(arg)) return INCOMPATIBLE;
return arg.reduce((acc, item, index) => {
const mapped = map(item, { type: type.value });
if (mapped !== INCOMPATIBLE) acc[index] = mapped;
return acc;
}, new Array(arg.length));
case 'object':
if (typeof arg === 'string' || typeof arg === 'number') return arg;
if (!type.value || typeof arg !== 'object') return INCOMPATIBLE;
return Object.entries(arg).reduce((acc, [key, val]) => {
const mapped = map(val, { type: type.value[key] });
return mapped === INCOMPATIBLE ? acc : Object.assign(acc, { [key]: mapped });
}, {} as Args);
default:
return INCOMPATIBLE;
}
};
export const mapArgsToTypes = (args: Args, argTypes: ArgTypes): Args => {
return Object.entries(args).reduce((acc, [key, value]) => {
if (!argTypes[key]) return acc;
const mapped = map(value, argTypes[key]);
return mapped === INCOMPATIBLE ? acc : Object.assign(acc, { [key]: mapped });
}, {});
};
export const combineArgs = (value: any, update: any): Args => {
if (Array.isArray(value) && Array.isArray(update)) {
return update
.reduce(
(acc, upd, index) => {
acc[index] = combineArgs(value[index], update[index]);
return acc;
},
[...value]
)
.filter((v: any) => v !== undefined);
}
if (!isPlainObject(value) || !isPlainObject(update)) return update;
return Object.keys({ ...value, ...update }).reduce((acc, key) => {
if (key in update) {
const combined = combineArgs(value[key], update[key]);
if (combined !== undefined) acc[key] = combined;
} else {
acc[key] = value[key];
}
return acc;
}, {} as any);
};
export const validateOptions = (args: Args, argTypes: ArgTypes): Args => {
return Object.entries(argTypes).reduce((acc, [key, { options }]) => {
// Don't set args that are not defined in `args` (they can be undefined in there)
// see https://github.com/storybookjs/storybook/issues/15630 and
// https://github.com/storybookjs/storybook/issues/17063
function allowArg() {
if (key in args) {
acc[key] = args[key];
}
return acc;
}
if (!options) return allowArg();
if (!Array.isArray(options)) {
once.error(dedent`
Invalid argType: '${key}.options' should be an array.
More info: https://storybook.js.org/docs/react/api/argtypes
`);
return allowArg();
}
if (options.some((opt) => opt && ['object', 'function'].includes(typeof opt))) {
once.error(dedent`
Invalid argType: '${key}.options' should only contain primitives. Use a 'mapping' for complex values.
More info: https://storybook.js.org/docs/react/writing-stories/args#mapping-to-complex-arg-values
`);
return allowArg();
}
const isArray = Array.isArray(args[key]);
const invalidIndex = isArray && args[key].findIndex((val: any) => !options.includes(val));
const isValidArray = isArray && invalidIndex === -1;
if (args[key] === undefined || options.includes(args[key]) || isValidArray) {
return allowArg();
}
const field = isArray ? `${key}[${invalidIndex}]` : key;
const supportedOptions = options
.map((opt: any) => (typeof opt === 'string' ? `'${opt}'` : String(opt)))
.join(', ');
once.warn(`Received illegal value for '${field}'. Supported options: ${supportedOptions}`);
return acc;
}, {} as Args);
};
// TODO -- copied from router, needs to be in a shared location
export const DEEPLY_EQUAL = Symbol('Deeply equal');
export const deepDiff = (value: any, update: any): any => {
if (typeof value !== typeof update) return update;
if (deepEqual(value, update)) return DEEPLY_EQUAL;
if (Array.isArray(value) && Array.isArray(update)) {
const res = update.reduce((acc, upd, index) => {
const diff = deepDiff(value[index], upd);
if (diff !== DEEPLY_EQUAL) acc[index] = diff;
return acc;
}, new Array(update.length));
if (update.length >= value.length) return res;
return res.concat(new Array(value.length - update.length).fill(undefined));
}
if (isPlainObject(value) && isPlainObject(update)) {
return Object.keys({ ...value, ...update }).reduce((acc, key) => {
const diff = deepDiff(value?.[key], update?.[key]);
return diff === DEEPLY_EQUAL ? acc : Object.assign(acc, { [key]: diff });
}, {});
}
return update;
};
export const NO_TARGET_NAME = '';
export function groupArgsByTarget<TArgs extends Args = Args>({
args,
argTypes,
}: StoryContext<Renderer, TArgs>) {
const groupedArgs: Record<string, Partial<TArgs>> = {};
(Object.entries(args) as [keyof TArgs, any][]).forEach(([name, value]) => {
const { target = NO_TARGET_NAME } = (argTypes[name] || {}) as { target?: string };
groupedArgs[target] = groupedArgs[target] || {};
groupedArgs[target][name] = value;
});
return groupedArgs;
}
export function noTargetArgs<TArgs extends Args = Args>(context: StoryContext<Renderer, TArgs>) {
return groupArgsByTarget(context)[NO_TARGET_NAME];
}
| code/lib/preview-api/src/modules/store/args.ts | 1 | https://github.com/storybookjs/storybook/commit/5344bd17421860b917b0828a30c3851d7c0eeaff | [
0.00017655512783676386,
0.00017033895710483193,
0.00016265790327452123,
0.00016979353677015752,
0.0000038073012547101825
] |
{
"id": 0,
"code_window": [
"import type { ActionOptions } from '../models';\n",
"\n",
"export const config: ActionOptions = {\n",
" depth: 6,\n",
" clearOnStoryChange: true,\n",
" limit: 50,\n",
"};\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" depth: 10,\n"
],
"file_path": "code/addons/actions/src/runtime/configureActions.ts",
"type": "replace",
"edit_start_line_idx": 3
} | ```html
<!-- .storybook/manager-head.html -->
<meta name="description" content="Components for my awesome project" key="desc" />
```
| docs/snippets/common/seo-description.html.mdx | 0 | https://github.com/storybookjs/storybook/commit/5344bd17421860b917b0828a30c3851d7c0eeaff | [
0.00017434572509955615,
0.00017434572509955615,
0.00017434572509955615,
0.00017434572509955615,
0
] |
{
"id": 0,
"code_window": [
"import type { ActionOptions } from '../models';\n",
"\n",
"export const config: ActionOptions = {\n",
" depth: 6,\n",
" clearOnStoryChange: true,\n",
" limit: 50,\n",
"};\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" depth: 10,\n"
],
"file_path": "code/addons/actions/src/runtime/configureActions.ts",
"type": "replace",
"edit_start_line_idx": 3
} | import { global } from '@storybook/global';
import React from 'react';
import copy from 'copy-to-clipboard';
import { getStoryHref, IconButton, Icons } from '@storybook/components';
import { Consumer, type Combo } from '@storybook/manager-api';
import type { Addon } from '@storybook/manager-api';
const { PREVIEW_URL, document } = global;
const copyMapper = ({ state }: Combo) => {
const { storyId, refId, refs } = state;
const { location } = document;
const ref = refs[refId];
let baseUrl = `${location.origin}${location.pathname}`;
if (!baseUrl.endsWith('/')) baseUrl += '/';
return {
refId,
baseUrl: ref ? `${ref.url}/iframe.html` : (PREVIEW_URL as string) || `${baseUrl}iframe.html`,
storyId,
queryParams: state.customQueryParams,
};
};
export const copyTool: Addon = {
title: 'copy',
id: 'copy',
match: ({ viewMode }) => viewMode === 'story',
render: () => (
<Consumer filter={copyMapper}>
{({ baseUrl, storyId, queryParams }) =>
storyId ? (
<IconButton
key="copy"
onClick={() => copy(getStoryHref(baseUrl, storyId, queryParams))}
title="Copy canvas link"
>
<Icons icon="link" />
</IconButton>
) : null
}
</Consumer>
),
};
| code/ui/manager/src/components/preview/tools/copy.tsx | 0 | https://github.com/storybookjs/storybook/commit/5344bd17421860b917b0828a30c3851d7c0eeaff | [
0.0001761134626576677,
0.00017284729983657598,
0.00016928189143072814,
0.00017315108561888337,
0.000002951108172055683
] |
{
"id": 0,
"code_window": [
"import type { ActionOptions } from '../models';\n",
"\n",
"export const config: ActionOptions = {\n",
" depth: 6,\n",
" clearOnStoryChange: true,\n",
" limit: 50,\n",
"};\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" depth: 10,\n"
],
"file_path": "code/addons/actions/src/runtime/configureActions.ts",
"type": "replace",
"edit_start_line_idx": 3
} | import { within, userEvent } from '@storybook/testing-library';
import { createPage } from './Page';
export default {
title: 'Example/Page',
render: () => createPage(),
parameters: {
// More on how to position stories at: https://storybook.js.org/docs/7.0/html/configure/story-layout
layout: 'fullscreen',
},
};
export const LoggedOut = {};
// More on interaction testing: https://storybook.js.org/docs/7.0/html/writing-tests/interaction-testing
export const LoggedIn = {
play: async ({ canvasElement }) => {
const canvas = within(canvasElement);
const loginButton = await canvas.getByRole('button', {
name: /Log in/i,
});
await userEvent.click(loginButton);
},
};
| code/renderers/html/template/cli/js/Page.stories.js | 0 | https://github.com/storybookjs/storybook/commit/5344bd17421860b917b0828a30c3851d7c0eeaff | [
0.00029848841950297356,
0.00021259354252833873,
0.00016918200708460063,
0.00017011018644552678,
0.000060738035244867206
] |
{
"id": 1,
"code_window": [
"\n",
"import {\n",
" combineArgs,\n",
" groupArgsByTarget,\n",
" mapArgsToTypes,\n",
" NO_TARGET_NAME,\n",
" validateOptions,\n",
"} from './args';\n",
"\n",
"const stringType: SBType = { name: 'string' };\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" UNTARGETED,\n"
],
"file_path": "code/lib/preview-api/src/modules/store/args.test.ts",
"type": "replace",
"edit_start_line_idx": 8
} | import { global } from '@storybook/global';
import type {
Renderer,
Args,
ArgsStoryFn,
LegacyStoryFn,
Parameters,
PlayFunction,
PlayFunctionContext,
StepLabel,
NormalizedComponentAnnotations,
NormalizedProjectAnnotations,
NormalizedStoryAnnotations,
PreparedStory,
StoryContext,
StoryContextForEnhancers,
StoryContextForLoaders,
StrictArgTypes,
PreparedMeta,
ModuleExport,
} from '@storybook/types';
import { includeConditionalArg } from '@storybook/csf';
import { applyHooks } from '../../addons';
import { combineParameters } from '../parameters';
import { defaultDecorateStory } from '../decorators';
import { groupArgsByTarget, NO_TARGET_NAME } from '../args';
// Combine all the metadata about a story (both direct and inherited from the component/global scope)
// into a "renderable" story function, with all decorators applied, parameters passed as context etc
//
// Note that this story function is *stateless* in the sense that it does not track args or globals
// Instead, it is expected these are tracked separately (if necessary) and are passed into each invocation.
export function prepareStory<TRenderer extends Renderer>(
storyAnnotations: NormalizedStoryAnnotations<TRenderer>,
componentAnnotations: NormalizedComponentAnnotations<TRenderer>,
projectAnnotations: NormalizedProjectAnnotations<TRenderer>
): PreparedStory<TRenderer> {
// NOTE: in the current implementation we are doing everything once, up front, rather than doing
// anything at render time. The assumption is that as we don't load all the stories at once, this
// will have a limited cost. If this proves misguided, we can refactor it.
const { moduleExport, id, name } = storyAnnotations || {};
const partialAnnotations = preparePartialAnnotations(
storyAnnotations,
componentAnnotations,
projectAnnotations
);
const loaders = [
...(projectAnnotations.loaders || []),
...(componentAnnotations.loaders || []),
...(storyAnnotations?.loaders || []),
];
const applyLoaders = async (context: StoryContextForLoaders<TRenderer>) => {
const loadResults = await Promise.all(loaders.map((loader) => loader(context)));
const loaded = Object.assign({}, ...loadResults);
return { ...context, loaded };
};
const undecoratedStoryFn: LegacyStoryFn<TRenderer> = (context: StoryContext<TRenderer>) => {
const { passArgsFirst: renderTimePassArgsFirst = true } = context.parameters;
return renderTimePassArgsFirst
? (render as ArgsStoryFn<TRenderer>)(context.args, context)
: (render as LegacyStoryFn<TRenderer>)(context);
};
// Currently it is only possible to set these globally
const { applyDecorators = defaultDecorateStory, runStep } = projectAnnotations;
const decorators = [
...(storyAnnotations?.decorators || []),
...(componentAnnotations.decorators || []),
...(projectAnnotations.decorators || []),
];
// The render function on annotations *has* to be an `ArgsStoryFn`, so when we normalize
// CSFv1/2, we use a new field called `userStoryFn` so we know that it can be a LegacyStoryFn
const render =
storyAnnotations?.userStoryFn ||
storyAnnotations?.render ||
componentAnnotations.render ||
projectAnnotations.render;
if (!render) throw new Error(`No render function available for storyId '${id}'`);
const decoratedStoryFn = applyHooks<TRenderer>(applyDecorators)(undecoratedStoryFn, decorators);
const unboundStoryFn = (context: StoryContext<TRenderer>) => decoratedStoryFn(context);
// prepareContext is invoked at StoryRender.render()
// the context is prepared before invoking the render function, instead of here directly
// to ensure args don't loose there special properties set by the renderer
// eg. reactive proxies set by frameworks like SolidJS or Vue
const prepareContext = (context: StoryContext<TRenderer>) => {
let finalContext: StoryContext<TRenderer> = context;
if (global.FEATURES?.argTypeTargetsV7) {
const argsByTarget = groupArgsByTarget(context);
finalContext = {
...context,
allArgs: context.args,
argsByTarget,
args: argsByTarget[NO_TARGET_NAME] || {},
};
}
const mappedArgs = Object.entries(finalContext.args).reduce((acc, [key, val]) => {
const mapping = finalContext.argTypes[key]?.mapping;
acc[key] = mapping && val in mapping ? mapping[val] : val;
return acc;
}, {} as Args);
const includedArgs = Object.entries(mappedArgs).reduce((acc, [key, val]) => {
const argType = finalContext.argTypes[key] || {};
if (includeConditionalArg(argType, mappedArgs, finalContext.globals)) acc[key] = val;
return acc;
}, {} as Args);
return { ...finalContext, args: includedArgs };
};
const play = storyAnnotations?.play || componentAnnotations.play;
const playFunction =
play &&
(async (storyContext: StoryContext<TRenderer>) => {
const playFunctionContext: PlayFunctionContext<TRenderer> = {
...storyContext,
// eslint-disable-next-line @typescript-eslint/no-shadow
step: (label: StepLabel, play: PlayFunction<TRenderer>) =>
// TODO: We know runStep is defined, we need a proper normalized annotations type
runStep!(label, play, playFunctionContext),
};
return play(playFunctionContext);
});
return {
...partialAnnotations,
moduleExport,
id,
name,
story: name,
originalStoryFn: render,
undecoratedStoryFn,
unboundStoryFn,
applyLoaders,
playFunction,
prepareContext,
};
}
export function prepareMeta<TRenderer extends Renderer>(
componentAnnotations: NormalizedComponentAnnotations<TRenderer>,
projectAnnotations: NormalizedProjectAnnotations<TRenderer>,
moduleExport: ModuleExport
): PreparedMeta<TRenderer> {
return {
...preparePartialAnnotations(undefined, componentAnnotations, projectAnnotations),
moduleExport,
};
}
function preparePartialAnnotations<TRenderer extends Renderer>(
storyAnnotations: NormalizedStoryAnnotations<TRenderer> | undefined,
componentAnnotations: NormalizedComponentAnnotations<TRenderer>,
projectAnnotations: NormalizedProjectAnnotations<TRenderer>
): Omit<StoryContextForEnhancers<TRenderer>, 'name' | 'story'> {
// NOTE: in the current implementation we are doing everything once, up front, rather than doing
// anything at render time. The assumption is that as we don't load all the stories at once, this
// will have a limited cost. If this proves misguided, we can refactor it.
const id = storyAnnotations?.id || componentAnnotations.id;
const tags = [...(storyAnnotations?.tags || componentAnnotations.tags || []), 'story'];
const parameters: Parameters = combineParameters(
projectAnnotations.parameters,
componentAnnotations.parameters,
storyAnnotations?.parameters
);
// Currently it is only possible to set these globally
const { argTypesEnhancers = [], argsEnhancers = [] } = projectAnnotations;
// The render function on annotations *has* to be an `ArgsStoryFn`, so when we normalize
// CSFv1/2, we use a new field called `userStoryFn` so we know that it can be a LegacyStoryFn
const render =
storyAnnotations?.userStoryFn ||
storyAnnotations?.render ||
componentAnnotations.render ||
projectAnnotations.render;
if (!render) throw new Error(`No render function available for id '${id}'`);
const passedArgTypes: StrictArgTypes = combineParameters(
projectAnnotations.argTypes,
componentAnnotations.argTypes,
storyAnnotations?.argTypes
) as StrictArgTypes;
const { passArgsFirst = true } = parameters;
// eslint-disable-next-line no-underscore-dangle
parameters.__isArgsStory = passArgsFirst && render.length > 0;
// Pull out args[X] into initialArgs for argTypes enhancers
const passedArgs: Args = {
...projectAnnotations.args,
...componentAnnotations.args,
...storyAnnotations?.args,
} as Args;
const contextForEnhancers: StoryContextForEnhancers<TRenderer> = {
componentId: componentAnnotations.id,
title: componentAnnotations.title,
kind: componentAnnotations.title, // Back compat
id: storyAnnotations?.id || componentAnnotations.id,
// if there's no story name, we create a fake one since enhancers expect a name
name: storyAnnotations?.name || '__meta',
story: storyAnnotations?.name || '__meta', // Back compat
component: componentAnnotations.component,
subcomponents: componentAnnotations.subcomponents,
tags,
parameters,
initialArgs: passedArgs,
argTypes: passedArgTypes,
};
contextForEnhancers.argTypes = argTypesEnhancers.reduce(
(accumulatedArgTypes, enhancer) =>
enhancer({ ...contextForEnhancers, argTypes: accumulatedArgTypes }),
contextForEnhancers.argTypes
);
const initialArgsBeforeEnhancers = { ...passedArgs };
contextForEnhancers.initialArgs = argsEnhancers.reduce(
(accumulatedArgs: Args, enhancer) => ({
...accumulatedArgs,
...enhancer({
...contextForEnhancers,
initialArgs: accumulatedArgs,
}),
}),
initialArgsBeforeEnhancers
);
// Add some of our metadata into parameters as we used to do this in 6.x and users may be relying on it
if (!global.FEATURES?.breakingChangesV7) {
contextForEnhancers.parameters = {
...contextForEnhancers.parameters,
__id: id,
globals: projectAnnotations.globals,
globalTypes: projectAnnotations.globalTypes,
args: contextForEnhancers.initialArgs,
argTypes: contextForEnhancers.argTypes,
};
}
const { name, story, ...withoutStoryIdentifiers } = contextForEnhancers;
return withoutStoryIdentifiers;
}
| code/lib/preview-api/src/modules/store/csf/prepareStory.ts | 1 | https://github.com/storybookjs/storybook/commit/5344bd17421860b917b0828a30c3851d7c0eeaff | [
0.018220677971839905,
0.00166493677534163,
0.00016401302127633244,
0.00017466870485804975,
0.004498821217566729
] |
{
"id": 1,
"code_window": [
"\n",
"import {\n",
" combineArgs,\n",
" groupArgsByTarget,\n",
" mapArgsToTypes,\n",
" NO_TARGET_NAME,\n",
" validateOptions,\n",
"} from './args';\n",
"\n",
"const stringType: SBType = { name: 'string' };\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" UNTARGETED,\n"
],
"file_path": "code/lib/preview-api/src/modules/store/args.test.ts",
"type": "replace",
"edit_start_line_idx": 8
} | ```html
<!-- List.stories.svelte -->
<script>
import { Meta, Template, Story } from '@storybook/addon-svelte-csf';
import List from './List.svelte';
</script>
<meta title="List" component="{List}" />
<template let:args>
<List {...args} />
</template>
<Story name="Empty">
<List {...args} />
</Story>
```
| docs/snippets/svelte/list-story-starter.native-format.mdx | 0 | https://github.com/storybookjs/storybook/commit/5344bd17421860b917b0828a30c3851d7c0eeaff | [
0.00017424483667127788,
0.00017053427291102707,
0.00016682369459886104,
0.00017053427291102707,
0.000003710571036208421
] |
{
"id": 1,
"code_window": [
"\n",
"import {\n",
" combineArgs,\n",
" groupArgsByTarget,\n",
" mapArgsToTypes,\n",
" NO_TARGET_NAME,\n",
" validateOptions,\n",
"} from './args';\n",
"\n",
"const stringType: SBType = { name: 'string' };\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" UNTARGETED,\n"
],
"file_path": "code/lib/preview-api/src/modules/store/args.test.ts",
"type": "replace",
"edit_start_line_idx": 8
} | {
"version": 2,
"projects": {
"@storybook/addon-a11y": {
"implicitDependencies": [],
"root": "addons/a11y",
"type": "library"
},
"@storybook/addon-actions": {
"implicitDependencies": [],
"root": "addons/actions",
"type": "library"
},
"@storybook/addon-backgrounds": {
"implicitDependencies": [],
"root": "addons/backgrounds",
"type": "library"
},
"@storybook/addon-controls": {
"implicitDependencies": [],
"root": "addons/controls",
"type": "library"
},
"@storybook/addon-docs": {
"implicitDependencies": [],
"root": "addons/docs",
"type": "library"
},
"@storybook/addon-essentials": {
"implicitDependencies": [],
"root": "addons/essentials",
"type": "library"
},
"@storybook/addon-highlight": {
"implicitDependencies": [],
"root": "addons/highlight",
"type": "library"
},
"@storybook/addon-interactions": {
"implicitDependencies": [],
"root": "addons/interactions",
"type": "library"
},
"@storybook/addon-jest": {
"implicitDependencies": [],
"root": "addons/jest",
"type": "library"
},
"@storybook/addon-links": {
"implicitDependencies": [],
"root": "addons/links",
"type": "library"
},
"@storybook/addon-measure": {
"implicitDependencies": [],
"root": "addons/measure",
"type": "library"
},
"@storybook/addon-outline": {
"implicitDependencies": [],
"root": "addons/outline",
"type": "library"
},
"@storybook/addon-storyshots": {
"implicitDependencies": [],
"root": "addons/storyshots-core",
"type": "library"
},
"@storybook/addon-storyshots-puppeteer": {
"implicitDependencies": [],
"root": "addons/storyshots-puppeteer",
"type": "library"
},
"@storybook/addon-storysource": {
"implicitDependencies": [],
"root": "addons/storysource",
"type": "library"
},
"@storybook/addon-toolbars": {
"implicitDependencies": [],
"root": "addons/toolbars",
"type": "library"
},
"@storybook/addon-viewport": {
"implicitDependencies": [],
"root": "addons/viewport",
"type": "library"
},
"@storybook/addons": {
"implicitDependencies": [],
"root": "lib/addons",
"type": "library"
},
"@storybook/angular": {
"implicitDependencies": [],
"root": "frameworks/angular",
"type": "library"
},
"@storybook/api": {
"implicitDependencies": [],
"root": "lib/manager-api-shim",
"type": "library"
},
"@storybook/blocks": {
"implicitDependencies": [],
"root": "ui/blocks",
"type": "library"
},
"@storybook/builder-manager": {
"implicitDependencies": [],
"root": "lib/builder-manager",
"type": "library"
},
"@storybook/builder-vite": {
"implicitDependencies": [],
"root": "lib/builder-vite",
"type": "library"
},
"@storybook/builder-webpack5": {
"implicitDependencies": [],
"root": "lib/builder-webpack5",
"type": "library"
},
"@storybook/channel-postmessage": {
"implicitDependencies": [],
"root": "lib/channel-postmessage",
"type": "library"
},
"@storybook/channel-websocket": {
"implicitDependencies": [],
"root": "lib/channel-websocket",
"type": "library"
},
"@storybook/channels": {
"implicitDependencies": [],
"root": "lib/channels",
"type": "library"
},
"@storybook/cli": {
"implicitDependencies": [],
"root": "lib/cli",
"type": "library"
},
"@storybook/client-api": {
"implicitDependencies": [],
"root": "lib/client-api",
"type": "library"
},
"@storybook/client-logger": {
"implicitDependencies": [],
"root": "lib/client-logger",
"type": "library"
},
"@storybook/codemod": {
"implicitDependencies": [],
"root": "lib/codemod",
"type": "library"
},
"@storybook/components": {
"implicitDependencies": [],
"root": "ui/components",
"type": "library"
},
"@storybook/core-client": {
"implicitDependencies": [],
"root": "lib/core-client",
"type": "library"
},
"@storybook/core-common": {
"implicitDependencies": [],
"root": "lib/core-common",
"type": "library"
},
"@storybook/core-events": {
"implicitDependencies": [],
"root": "lib/core-events",
"type": "library"
},
"@storybook/core-server": {
"implicitDependencies": [],
"root": "lib/core-server",
"type": "library"
},
"@storybook/core-webpack": {
"implicitDependencies": [],
"root": "lib/core-webpack",
"type": "library"
},
"@storybook/csf-plugin": {
"implicitDependencies": [],
"root": "lib/csf-plugin",
"type": "library"
},
"@storybook/csf-tools": {
"implicitDependencies": [],
"root": "lib/csf-tools",
"type": "library"
},
"@storybook/docs-tools": {
"implicitDependencies": [],
"root": "lib/docs-tools",
"type": "library"
},
"@storybook/ember": {
"implicitDependencies": [],
"root": "frameworks/ember",
"type": "library"
},
"@storybook/html": {
"implicitDependencies": [],
"root": "renderers/html",
"type": "library"
},
"@storybook/html-vite": {
"implicitDependencies": [],
"root": "frameworks/html-vite",
"type": "library"
},
"@storybook/html-webpack5": {
"implicitDependencies": [],
"root": "frameworks/html-webpack5",
"type": "library"
},
"@storybook/instrumenter": {
"implicitDependencies": [],
"root": "lib/instrumenter",
"type": "library"
},
"@storybook/manager": {
"implicitDependencies": [],
"root": "ui/manager",
"type": "library"
},
"@storybook/manager-api": {
"implicitDependencies": [],
"root": "lib/manager-api",
"type": "library"
},
"@storybook/nextjs": {
"implicitDependencies": [],
"root": "frameworks/nextjs",
"type": "library"
},
"@storybook/node-logger": {
"implicitDependencies": [],
"root": "lib/node-logger",
"type": "library"
},
"@storybook/postinstall": {
"implicitDependencies": [],
"root": "lib/postinstall",
"type": "library"
},
"@storybook/preact": {
"implicitDependencies": [],
"root": "renderers/preact",
"type": "library"
},
"@storybook/preact-webpack5": {
"implicitDependencies": [],
"root": "frameworks/preact-webpack5",
"type": "library"
},
"@storybook/preact-vite": {
"implicitDependencies": [],
"root": "frameworks/preact-vite",
"type": "library"
},
"@storybook/preset-html-webpack": {
"implicitDependencies": [],
"root": "presets/html-webpack",
"type": "library"
},
"@storybook/preset-preact-webpack": {
"implicitDependencies": [],
"root": "presets/preact-webpack",
"type": "library"
},
"@storybook/preset-react-webpack": {
"implicitDependencies": [],
"root": "presets/react-webpack",
"type": "library"
},
"@storybook/preset-server-webpack": {
"implicitDependencies": [],
"root": "presets/server-webpack",
"type": "library"
},
"@storybook/preset-svelte-webpack": {
"implicitDependencies": [],
"root": "presets/svelte-webpack",
"type": "library"
},
"@storybook/preset-vue-webpack": {
"implicitDependencies": [],
"root": "presets/vue-webpack",
"type": "library"
},
"@storybook/preset-vue3-webpack": {
"implicitDependencies": [],
"root": "presets/vue3-webpack",
"type": "library"
},
"@storybook/preset-web-components-webpack": {
"implicitDependencies": [],
"root": "presets/web-components-webpack",
"type": "library"
},
"@storybook/preview": {
"implicitDependencies": [],
"root": "lib/preview",
"type": "library"
},
"@storybook/preview-api": {
"implicitDependencies": [],
"root": "lib/preview-api",
"type": "library"
},
"@storybook/preview-web": {
"implicitDependencies": [],
"root": "lib/preview-web",
"type": "library"
},
"@storybook/react": {
"implicitDependencies": [],
"root": "renderers/react",
"type": "library"
},
"@storybook/react-vite": {
"implicitDependencies": [],
"root": "frameworks/react-vite",
"type": "library"
},
"@storybook/react-webpack5": {
"implicitDependencies": [],
"root": "frameworks/react-webpack5",
"type": "library"
},
"@storybook/router": {
"implicitDependencies": [],
"root": "lib/router",
"type": "library"
},
"@storybook/server": {
"implicitDependencies": [],
"root": "renderers/server",
"type": "library"
},
"@storybook/server-webpack5": {
"implicitDependencies": [],
"root": "frameworks/server-webpack5",
"type": "library"
},
"@storybook/source-loader": {
"implicitDependencies": [],
"root": "lib/source-loader",
"type": "library"
},
"@storybook/store": {
"implicitDependencies": [],
"root": "lib/store",
"type": "library"
},
"@storybook/svelte": {
"implicitDependencies": [],
"root": "renderers/svelte",
"type": "library"
},
"@storybook/sveltekit": {
"implicitDependencies": [],
"root": "frameworks/sveltekit",
"type": "library"
},
"@storybook/svelte-vite": {
"implicitDependencies": [],
"root": "frameworks/svelte-vite",
"type": "library"
},
"@storybook/svelte-webpack5": {
"implicitDependencies": [],
"root": "frameworks/svelte-webpack5",
"type": "library"
},
"@storybook/telemetry": {
"implicitDependencies": [],
"root": "lib/telemetry",
"type": "library"
},
"@storybook/theming": {
"implicitDependencies": [],
"root": "lib/theming",
"type": "library"
},
"@storybook/types": {
"implicitDependencies": [],
"root": "lib/types",
"type": "library"
},
"@storybook/vue": {
"implicitDependencies": [],
"root": "renderers/vue",
"type": "library"
},
"@storybook/vue-vite": {
"implicitDependencies": [],
"root": "frameworks/vue-vite",
"type": "library"
},
"@storybook/vue-webpack5": {
"implicitDependencies": [],
"root": "frameworks/vue-webpack5",
"type": "library"
},
"@storybook/vue3": {
"implicitDependencies": [],
"root": "renderers/vue3",
"type": "library"
},
"@storybook/vue3-vite": {
"implicitDependencies": [],
"root": "frameworks/vue3-vite",
"type": "library"
},
"@storybook/vue3-webpack5": {
"implicitDependencies": [],
"root": "frameworks/vue3-webpack5",
"type": "library"
},
"@storybook/web-components": {
"implicitDependencies": [],
"root": "renderers/web-components",
"type": "library"
},
"@storybook/web-components-vite": {
"implicitDependencies": [],
"root": "frameworks/web-components-vite",
"type": "library"
},
"@storybook/web-components-webpack5": {
"implicitDependencies": [],
"root": "frameworks/web-components-webpack5",
"type": "library"
},
"sb": {
"implicitDependencies": [],
"root": "lib/cli-sb",
"type": "library"
},
"storybook": {
"implicitDependencies": [],
"root": "lib/cli-storybook",
"type": "library"
}
}
}
| code/workspace.json | 0 | https://github.com/storybookjs/storybook/commit/5344bd17421860b917b0828a30c3851d7c0eeaff | [
0.00017546677554491907,
0.0001740816660458222,
0.00017110609041992575,
0.00017414863395970315,
9.036785399985092e-7
] |
{
"id": 1,
"code_window": [
"\n",
"import {\n",
" combineArgs,\n",
" groupArgsByTarget,\n",
" mapArgsToTypes,\n",
" NO_TARGET_NAME,\n",
" validateOptions,\n",
"} from './args';\n",
"\n",
"const stringType: SBType = { name: 'string' };\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" UNTARGETED,\n"
],
"file_path": "code/lib/preview-api/src/modules/store/args.test.ts",
"type": "replace",
"edit_start_line_idx": 8
} | ```js
// Button.stories.js
export default {
title: 'Accessibility testing',
component: 'custom-button',
argTypes: {
backgroundColor: { control: 'color' },
},
};
// This is an accessible story
export const Accessible = {
args: {
primary: false,
label: 'Button',
},
};
// This is not
export const Inaccessible = {
args: {
...Accessible.args,
backgroundColor: 'red',
},
};
```
| docs/snippets/web-components/component-story-with-accessibility.js.mdx | 0 | https://github.com/storybookjs/storybook/commit/5344bd17421860b917b0828a30c3851d7c0eeaff | [
0.00019285389862488955,
0.00017798109911382198,
0.00016813204274512827,
0.00017295735597144812,
0.000010699564882088453
] |
{
"id": 2,
"code_window": [
" argTypes: { b: { name: 'b', target: 'group2' }, c: {} },\n",
" } as any);\n",
" expect(groups).toEqual({\n",
" [NO_TARGET_NAME]: {\n",
" a: 1,\n",
" c: 3,\n",
" },\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" [UNTARGETED]: {\n"
],
"file_path": "code/lib/preview-api/src/modules/store/args.test.ts",
"type": "replace",
"edit_start_line_idx": 297
} | import { global } from '@storybook/global';
import type {
Renderer,
Args,
ArgsStoryFn,
LegacyStoryFn,
Parameters,
PlayFunction,
PlayFunctionContext,
StepLabel,
NormalizedComponentAnnotations,
NormalizedProjectAnnotations,
NormalizedStoryAnnotations,
PreparedStory,
StoryContext,
StoryContextForEnhancers,
StoryContextForLoaders,
StrictArgTypes,
PreparedMeta,
ModuleExport,
} from '@storybook/types';
import { includeConditionalArg } from '@storybook/csf';
import { applyHooks } from '../../addons';
import { combineParameters } from '../parameters';
import { defaultDecorateStory } from '../decorators';
import { groupArgsByTarget, NO_TARGET_NAME } from '../args';
// Combine all the metadata about a story (both direct and inherited from the component/global scope)
// into a "renderable" story function, with all decorators applied, parameters passed as context etc
//
// Note that this story function is *stateless* in the sense that it does not track args or globals
// Instead, it is expected these are tracked separately (if necessary) and are passed into each invocation.
export function prepareStory<TRenderer extends Renderer>(
storyAnnotations: NormalizedStoryAnnotations<TRenderer>,
componentAnnotations: NormalizedComponentAnnotations<TRenderer>,
projectAnnotations: NormalizedProjectAnnotations<TRenderer>
): PreparedStory<TRenderer> {
// NOTE: in the current implementation we are doing everything once, up front, rather than doing
// anything at render time. The assumption is that as we don't load all the stories at once, this
// will have a limited cost. If this proves misguided, we can refactor it.
const { moduleExport, id, name } = storyAnnotations || {};
const partialAnnotations = preparePartialAnnotations(
storyAnnotations,
componentAnnotations,
projectAnnotations
);
const loaders = [
...(projectAnnotations.loaders || []),
...(componentAnnotations.loaders || []),
...(storyAnnotations?.loaders || []),
];
const applyLoaders = async (context: StoryContextForLoaders<TRenderer>) => {
const loadResults = await Promise.all(loaders.map((loader) => loader(context)));
const loaded = Object.assign({}, ...loadResults);
return { ...context, loaded };
};
const undecoratedStoryFn: LegacyStoryFn<TRenderer> = (context: StoryContext<TRenderer>) => {
const { passArgsFirst: renderTimePassArgsFirst = true } = context.parameters;
return renderTimePassArgsFirst
? (render as ArgsStoryFn<TRenderer>)(context.args, context)
: (render as LegacyStoryFn<TRenderer>)(context);
};
// Currently it is only possible to set these globally
const { applyDecorators = defaultDecorateStory, runStep } = projectAnnotations;
const decorators = [
...(storyAnnotations?.decorators || []),
...(componentAnnotations.decorators || []),
...(projectAnnotations.decorators || []),
];
// The render function on annotations *has* to be an `ArgsStoryFn`, so when we normalize
// CSFv1/2, we use a new field called `userStoryFn` so we know that it can be a LegacyStoryFn
const render =
storyAnnotations?.userStoryFn ||
storyAnnotations?.render ||
componentAnnotations.render ||
projectAnnotations.render;
if (!render) throw new Error(`No render function available for storyId '${id}'`);
const decoratedStoryFn = applyHooks<TRenderer>(applyDecorators)(undecoratedStoryFn, decorators);
const unboundStoryFn = (context: StoryContext<TRenderer>) => decoratedStoryFn(context);
// prepareContext is invoked at StoryRender.render()
// the context is prepared before invoking the render function, instead of here directly
// to ensure args don't loose there special properties set by the renderer
// eg. reactive proxies set by frameworks like SolidJS or Vue
const prepareContext = (context: StoryContext<TRenderer>) => {
let finalContext: StoryContext<TRenderer> = context;
if (global.FEATURES?.argTypeTargetsV7) {
const argsByTarget = groupArgsByTarget(context);
finalContext = {
...context,
allArgs: context.args,
argsByTarget,
args: argsByTarget[NO_TARGET_NAME] || {},
};
}
const mappedArgs = Object.entries(finalContext.args).reduce((acc, [key, val]) => {
const mapping = finalContext.argTypes[key]?.mapping;
acc[key] = mapping && val in mapping ? mapping[val] : val;
return acc;
}, {} as Args);
const includedArgs = Object.entries(mappedArgs).reduce((acc, [key, val]) => {
const argType = finalContext.argTypes[key] || {};
if (includeConditionalArg(argType, mappedArgs, finalContext.globals)) acc[key] = val;
return acc;
}, {} as Args);
return { ...finalContext, args: includedArgs };
};
const play = storyAnnotations?.play || componentAnnotations.play;
const playFunction =
play &&
(async (storyContext: StoryContext<TRenderer>) => {
const playFunctionContext: PlayFunctionContext<TRenderer> = {
...storyContext,
// eslint-disable-next-line @typescript-eslint/no-shadow
step: (label: StepLabel, play: PlayFunction<TRenderer>) =>
// TODO: We know runStep is defined, we need a proper normalized annotations type
runStep!(label, play, playFunctionContext),
};
return play(playFunctionContext);
});
return {
...partialAnnotations,
moduleExport,
id,
name,
story: name,
originalStoryFn: render,
undecoratedStoryFn,
unboundStoryFn,
applyLoaders,
playFunction,
prepareContext,
};
}
export function prepareMeta<TRenderer extends Renderer>(
componentAnnotations: NormalizedComponentAnnotations<TRenderer>,
projectAnnotations: NormalizedProjectAnnotations<TRenderer>,
moduleExport: ModuleExport
): PreparedMeta<TRenderer> {
return {
...preparePartialAnnotations(undefined, componentAnnotations, projectAnnotations),
moduleExport,
};
}
function preparePartialAnnotations<TRenderer extends Renderer>(
storyAnnotations: NormalizedStoryAnnotations<TRenderer> | undefined,
componentAnnotations: NormalizedComponentAnnotations<TRenderer>,
projectAnnotations: NormalizedProjectAnnotations<TRenderer>
): Omit<StoryContextForEnhancers<TRenderer>, 'name' | 'story'> {
// NOTE: in the current implementation we are doing everything once, up front, rather than doing
// anything at render time. The assumption is that as we don't load all the stories at once, this
// will have a limited cost. If this proves misguided, we can refactor it.
const id = storyAnnotations?.id || componentAnnotations.id;
const tags = [...(storyAnnotations?.tags || componentAnnotations.tags || []), 'story'];
const parameters: Parameters = combineParameters(
projectAnnotations.parameters,
componentAnnotations.parameters,
storyAnnotations?.parameters
);
// Currently it is only possible to set these globally
const { argTypesEnhancers = [], argsEnhancers = [] } = projectAnnotations;
// The render function on annotations *has* to be an `ArgsStoryFn`, so when we normalize
// CSFv1/2, we use a new field called `userStoryFn` so we know that it can be a LegacyStoryFn
const render =
storyAnnotations?.userStoryFn ||
storyAnnotations?.render ||
componentAnnotations.render ||
projectAnnotations.render;
if (!render) throw new Error(`No render function available for id '${id}'`);
const passedArgTypes: StrictArgTypes = combineParameters(
projectAnnotations.argTypes,
componentAnnotations.argTypes,
storyAnnotations?.argTypes
) as StrictArgTypes;
const { passArgsFirst = true } = parameters;
// eslint-disable-next-line no-underscore-dangle
parameters.__isArgsStory = passArgsFirst && render.length > 0;
// Pull out args[X] into initialArgs for argTypes enhancers
const passedArgs: Args = {
...projectAnnotations.args,
...componentAnnotations.args,
...storyAnnotations?.args,
} as Args;
const contextForEnhancers: StoryContextForEnhancers<TRenderer> = {
componentId: componentAnnotations.id,
title: componentAnnotations.title,
kind: componentAnnotations.title, // Back compat
id: storyAnnotations?.id || componentAnnotations.id,
// if there's no story name, we create a fake one since enhancers expect a name
name: storyAnnotations?.name || '__meta',
story: storyAnnotations?.name || '__meta', // Back compat
component: componentAnnotations.component,
subcomponents: componentAnnotations.subcomponents,
tags,
parameters,
initialArgs: passedArgs,
argTypes: passedArgTypes,
};
contextForEnhancers.argTypes = argTypesEnhancers.reduce(
(accumulatedArgTypes, enhancer) =>
enhancer({ ...contextForEnhancers, argTypes: accumulatedArgTypes }),
contextForEnhancers.argTypes
);
const initialArgsBeforeEnhancers = { ...passedArgs };
contextForEnhancers.initialArgs = argsEnhancers.reduce(
(accumulatedArgs: Args, enhancer) => ({
...accumulatedArgs,
...enhancer({
...contextForEnhancers,
initialArgs: accumulatedArgs,
}),
}),
initialArgsBeforeEnhancers
);
// Add some of our metadata into parameters as we used to do this in 6.x and users may be relying on it
if (!global.FEATURES?.breakingChangesV7) {
contextForEnhancers.parameters = {
...contextForEnhancers.parameters,
__id: id,
globals: projectAnnotations.globals,
globalTypes: projectAnnotations.globalTypes,
args: contextForEnhancers.initialArgs,
argTypes: contextForEnhancers.argTypes,
};
}
const { name, story, ...withoutStoryIdentifiers } = contextForEnhancers;
return withoutStoryIdentifiers;
}
| code/lib/preview-api/src/modules/store/csf/prepareStory.ts | 1 | https://github.com/storybookjs/storybook/commit/5344bd17421860b917b0828a30c3851d7c0eeaff | [
0.00046226856647990644,
0.00018806445586960763,
0.00016238422540482134,
0.000173039676155895,
0.00005701258487533778
] |
{
"id": 2,
"code_window": [
" argTypes: { b: { name: 'b', target: 'group2' }, c: {} },\n",
" } as any);\n",
" expect(groups).toEqual({\n",
" [NO_TARGET_NAME]: {\n",
" a: 1,\n",
" c: 3,\n",
" },\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" [UNTARGETED]: {\n"
],
"file_path": "code/lib/preview-api/src/modules/store/args.test.ts",
"type": "replace",
"edit_start_line_idx": 297
} | ```tsx
// Button.stories.ts|tsx
import type { Meta, StoryObj } from '@storybook/react';
import { Button } from './Button';
const meta = {
/* 👇 The title prop is optional.
* See https://storybook.js.org/docs/7.0/react/configure/overview#configure-story-loading
* to learn how to generate automatic titles
*/
title: 'Button',
component: Button,
decorators: [
(Story) => (
<div style={{ margin: '3em' }}>
<Story />
</div>
),
],
} satisfies Meta<typeof Button>;
export default meta;
```
| docs/snippets/react/button-story-component-decorator.ts-4-9.mdx | 0 | https://github.com/storybookjs/storybook/commit/5344bd17421860b917b0828a30c3851d7c0eeaff | [
0.00017717372975312173,
0.0001736436242936179,
0.00017045391723513603,
0.0001733031967887655,
0.000002753892204054864
] |
{
"id": 2,
"code_window": [
" argTypes: { b: { name: 'b', target: 'group2' }, c: {} },\n",
" } as any);\n",
" expect(groups).toEqual({\n",
" [NO_TARGET_NAME]: {\n",
" a: 1,\n",
" c: 3,\n",
" },\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" [UNTARGETED]: {\n"
],
"file_path": "code/lib/preview-api/src/modules/store/args.test.ts",
"type": "replace",
"edit_start_line_idx": 297
} | import { rgba, lighten, darken } from 'polished';
import { global } from '@storybook/global';
import { logger } from '@storybook/client-logger';
const { window: globalWindow } = global;
export const mkColor = (color: string) => ({ color });
// Check if it is a string. This is for the sake of warning users
// and the successive guarding logics that use String methods.
const isColorString = (color: string) => {
if (typeof color !== 'string') {
logger.warn(
`Color passed to theme object should be a string. Instead ${color}(${typeof color}) was passed.`
);
return false;
}
return true;
};
// Passing arguments that can't be converted to RGB such as linear-gradient
// to library polished's functions such as lighten or darken throws the error
// that crashes the entire storybook. It needs to be guarded when arguments
// of those functions are from user input.
const isValidColorForPolished = (color: string) => {
return !/(gradient|var|calc)/.test(color);
};
const applyPolished = (type: string, color: string) => {
if (type === 'darken') {
return rgba(`${darken(1, color)}`, 0.95);
}
if (type === 'lighten') {
return rgba(`${lighten(1, color)}`, 0.95);
}
return color;
};
const colorFactory = (type: string) => (color: string) => {
if (!isColorString(color)) {
return color;
}
if (!isValidColorForPolished(color)) {
return color;
}
// Guard anything that is not working with polished.
try {
return applyPolished(type, color);
} catch (error) {
return color;
}
};
export const lightenColor = colorFactory('lighten');
export const darkenColor = colorFactory('darken');
// The default color scheme is light so unless the preferred color
// scheme is set to dark we always want to use the light theme
export const getPreferredColorScheme = () => {
if (!globalWindow || !globalWindow.matchMedia) return 'light';
const isDarkThemePreferred = globalWindow.matchMedia('(prefers-color-scheme: dark)').matches;
if (isDarkThemePreferred) return 'dark';
return 'light';
};
| code/lib/theming/src/utils.ts | 0 | https://github.com/storybookjs/storybook/commit/5344bd17421860b917b0828a30c3851d7c0eeaff | [
0.00017704046331346035,
0.00017337646568194032,
0.00016848895756993443,
0.0001737266720738262,
0.0000025125921183644095
] |
{
"id": 2,
"code_window": [
" argTypes: { b: { name: 'b', target: 'group2' }, c: {} },\n",
" } as any);\n",
" expect(groups).toEqual({\n",
" [NO_TARGET_NAME]: {\n",
" a: 1,\n",
" c: 3,\n",
" },\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" [UNTARGETED]: {\n"
],
"file_path": "code/lib/preview-api/src/modules/store/args.test.ts",
"type": "replace",
"edit_start_line_idx": 297
} | ```md
<!-- Button.stories.mdx -->
import { Meta, Story } from '@storybook/addon-docs';
import Button from './Button.svelte';
<!-- 👇 Creates specific argTypes -->
<Meta
title="Button"
component={Button}
argTypes={{
backgroundColor: {
control: 'color',
},
}}
/>
<!-- 👇 Some function to demonstrate the behavior -->
export const someFunction = (someValue) => {
return `i am a ${someValue}`;
};
<!-- 👇 Destructure the label from the args object and assigns the function result to a variable and pass it as a prop into the component -->
<Story
name="ExampleStory"
args={{
primary: true,
size: 'small',
label: "button",
}}>
{(args) => {
const { label } = args;
const functionResult = someFunction(label);
return {
Component: Button,
props: {
...args,
label: functionResult,
},
};
}}
</Story>
``` | docs/snippets/svelte/button-story-default-docs-code.mdx.mdx | 0 | https://github.com/storybookjs/storybook/commit/5344bd17421860b917b0828a30c3851d7c0eeaff | [
0.0001748609938658774,
0.00017187285993713886,
0.00017007725546136498,
0.00017090339679270983,
0.0000017501914726381074
] |
{
"id": 3,
"code_window": [
" return update;\n",
"};\n",
"\n",
"export const NO_TARGET_NAME = '';\n",
"export function groupArgsByTarget<TArgs extends Args = Args>({\n",
" args,\n",
" argTypes,\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"export const UNTARGETED = 'UNTARGETED';\n"
],
"file_path": "code/lib/preview-api/src/modules/store/args.ts",
"type": "replace",
"edit_start_line_idx": 146
} | /// <reference types="@types/jest" />;
import { global } from '@storybook/global';
import { expect } from '@jest/globals';
import type { Renderer, ArgsEnhancer, PlayFunctionContext, SBScalarType } from '@storybook/types';
import { addons, HooksContext } from '../../addons';
import { NO_TARGET_NAME } from '../args';
import { prepareStory, prepareMeta } from './prepareStory';
jest.mock('@storybook/global', () => ({
global: {
...(jest.requireActual('@storybook/global') as any),
FEATURES: {
breakingChangesV7: true,
},
},
}));
const id = 'id';
const name = 'name';
const title = 'title';
const render = (args: any) => {};
const moduleExport = {};
const stringType: SBScalarType = { name: 'string' };
const numberType: SBScalarType = { name: 'number' };
const booleanType: SBScalarType = { name: 'boolean' };
beforeEach(() => {
global.FEATURES = { breakingChangesV7: true };
});
describe('prepareStory', () => {
describe('tags', () => {
it('story tags override component', () => {
const { tags } = prepareStory(
{ id, name, tags: ['story-1', 'story-2'], moduleExport },
{
id,
title,
tags: ['component-1', 'component-2'],
},
{ render }
);
expect(tags).toEqual(['story-1', 'story-2', 'story']);
});
it('component tags work if story are unset', () => {
const { tags } = prepareStory(
{ id, name, moduleExport },
{
id,
title,
tags: ['component-1', 'component-2'],
},
{ render }
);
expect(tags).toEqual(['component-1', 'component-2', 'story']);
});
it('sets a value even if annotations do not have tags', () => {
const { tags } = prepareStory({ id, name, moduleExport }, { id, title }, { render });
expect(tags).toEqual(['story']);
});
});
describe('parameters', () => {
it('are combined in the right order', () => {
const { parameters } = prepareStory(
{ id, name, parameters: { a: 'story', nested: { z: 'story' } }, moduleExport },
{
id,
title,
parameters: {
a: { name: 'component' },
b: { name: 'component' },
nested: { z: { name: 'component' }, y: { name: 'component' } },
},
},
{
render,
parameters: {
a: { name: 'global' },
b: { name: 'global' },
c: { name: 'global' },
nested: { z: { name: 'global' }, x: { name: 'global' } },
},
}
);
expect(parameters).toEqual({
__isArgsStory: true,
a: 'story',
b: { name: 'component' },
c: { name: 'global' },
nested: { z: 'story', y: { name: 'component' }, x: { name: 'global' } },
});
});
it('sets a value even if annotations do not have parameters', () => {
const { parameters } = prepareStory({ id, name, moduleExport }, { id, title }, { render });
expect(parameters).toEqual({ __isArgsStory: true });
});
it('does not set `__isArgsStory` if `passArgsFirst` is disabled', () => {
const { parameters } = prepareStory(
{ id, name, parameters: { passArgsFirst: false }, moduleExport },
{ id, title },
{ render }
);
expect(parameters).toEqual({ passArgsFirst: false, __isArgsStory: false });
});
it('does not set `__isArgsStory` if `render` does not take args', () => {
const { parameters } = prepareStory(
{ id, name, moduleExport },
{ id, title },
{ render: () => {} }
);
expect(parameters).toEqual({ __isArgsStory: false });
});
});
describe('args/initialArgs', () => {
it('are combined in the right order', () => {
const { initialArgs } = prepareStory(
{ id, name, args: { a: 'story', nested: { z: 'story' } }, moduleExport },
{
id,
title,
args: {
a: 'component',
b: 'component',
nested: { z: 'component', y: 'component' },
},
},
{
render,
args: {
a: 'global',
b: 'global',
c: 'global',
nested: { z: 'global', x: 'global' },
},
}
);
expect(initialArgs).toEqual({
a: 'story',
b: 'component',
c: 'global',
nested: { z: 'story' },
});
});
it('can be overriden by `undefined`', () => {
const { initialArgs } = prepareStory(
{ id, name, args: { a: undefined }, moduleExport },
{ id, title, args: { a: 'component' } },
{ render }
);
expect(initialArgs).toEqual({ a: undefined });
});
it('sets a value even if annotations do not have args', () => {
const { initialArgs } = prepareStory({ id, name, moduleExport }, { id, title }, { render });
expect(initialArgs).toEqual({});
});
describe('argsEnhancers', () => {
it('are applied in the right order', () => {
const run: number[] = [];
const enhancerOne: ArgsEnhancer<Renderer> = () => {
run.push(1);
return {};
};
const enhancerTwo: ArgsEnhancer<Renderer> = () => {
run.push(2);
return {};
};
prepareStory(
{ id, name, moduleExport },
{ id, title },
{ render, argsEnhancers: [enhancerOne, enhancerTwo] }
);
expect(run).toEqual([1, 2]);
});
it('allow you to add args', () => {
const enhancer = jest.fn(() => ({ c: 'd' }));
const { initialArgs } = prepareStory(
{ id, name, args: { a: 'b' }, moduleExport },
{ id, title },
{ render, argsEnhancers: [enhancer] }
);
expect(enhancer).toHaveBeenCalledWith(expect.objectContaining({ initialArgs: { a: 'b' } }));
expect(initialArgs).toEqual({ a: 'b', c: 'd' });
});
it('passes result of earlier enhancers into subsequent ones, and composes their output', () => {
const enhancerOne = jest.fn(() => ({ b: 'B' }));
const enhancerTwo = jest.fn(({ initialArgs }) =>
Object.entries(initialArgs).reduce(
(acc, [key, val]) => ({ ...acc, [key]: `enhanced ${val}` }),
{}
)
);
const enhancerThree = jest.fn(() => ({ c: 'C' }));
const { initialArgs } = prepareStory(
{ id, name, args: { a: 'A' }, moduleExport },
{ id, title },
{ render, argsEnhancers: [enhancerOne, enhancerTwo, enhancerThree] }
);
expect(enhancerOne).toHaveBeenCalledWith(
expect.objectContaining({ initialArgs: { a: 'A' } })
);
expect(enhancerTwo).toHaveBeenCalledWith(
expect.objectContaining({ initialArgs: { a: 'A', b: 'B' } })
);
expect(enhancerThree).toHaveBeenCalledWith(
expect.objectContaining({ initialArgs: { a: 'enhanced A', b: 'enhanced B' } })
);
expect(initialArgs).toEqual({
a: 'enhanced A',
b: 'enhanced B',
c: 'C',
});
});
});
});
describe('argTypes', () => {
it('are combined in the right order', () => {
const { argTypes } = prepareStory(
{
id,
name,
argTypes: {
a: { name: 'a-story', type: booleanType },
nested: { name: 'nested', type: booleanType, a: 'story' },
},
moduleExport,
},
{
id,
title,
argTypes: {
a: { name: 'a-component', type: stringType },
b: { name: 'b-component', type: stringType },
nested: { name: 'nested', type: booleanType, a: 'component', b: 'component' },
},
},
{
render,
argTypes: {
a: { name: 'a-global', type: numberType },
b: { name: 'b-global', type: numberType },
c: { name: 'c-global', type: numberType },
nested: { name: 'nested', type: booleanType, a: 'global', b: 'global', c: 'global' },
},
}
);
expect(argTypes).toEqual({
a: { name: 'a-story', type: booleanType },
b: { name: 'b-component', type: stringType },
c: { name: 'c-global', type: numberType },
nested: { name: 'nested', type: booleanType, a: 'story', b: 'component', c: 'global' },
});
});
describe('argTypesEnhancers', () => {
it('allows you to alter argTypes when stories are added', () => {
const enhancer = jest.fn((context) => ({ ...context.argTypes, c: { name: 'd' } }));
const { argTypes } = prepareStory(
{ id, name, argTypes: { a: { name: 'b' } }, moduleExport },
{ id, title },
{ render, argTypesEnhancers: [enhancer] }
);
expect(enhancer).toHaveBeenCalledWith(
expect.objectContaining({ argTypes: { a: { name: 'b' } } })
);
expect(argTypes).toEqual({ a: { name: 'b' }, c: { name: 'd' } });
});
it('does not merge argType enhancer results', () => {
const enhancer = jest.fn(() => ({ c: { name: 'd' } }));
const { argTypes } = prepareStory(
{ id, name, argTypes: { a: { name: 'b' } }, moduleExport },
{ id, title },
{ render, argTypesEnhancers: [enhancer] }
);
expect(enhancer).toHaveBeenCalledWith(
expect.objectContaining({ argTypes: { a: { name: 'b' } } })
);
expect(argTypes).toEqual({ c: { name: 'd' } });
});
it('recursively passes argTypes to successive enhancers', () => {
const firstEnhancer = jest.fn((context) => ({ ...context.argTypes, c: { name: 'd' } }));
const secondEnhancer = jest.fn((context) => ({ ...context.argTypes, e: { name: 'f' } }));
const { argTypes } = prepareStory(
{ id, name, argTypes: { a: { name: 'b' } }, moduleExport },
{ id, title },
{ render, argTypesEnhancers: [firstEnhancer, secondEnhancer] }
);
expect(firstEnhancer).toHaveBeenCalledWith(
expect.objectContaining({ argTypes: { a: { name: 'b' } } })
);
expect(secondEnhancer).toHaveBeenCalledWith(
expect.objectContaining({ argTypes: { a: { name: 'b' }, c: { name: 'd' } } })
);
expect(argTypes).toEqual({ a: { name: 'b' }, c: { name: 'd' }, e: { name: 'f' } });
});
});
});
describe('applyLoaders', () => {
it('awaits the result of a loader', async () => {
const loader = jest.fn(async () => new Promise((r) => setTimeout(() => r({ foo: 7 }), 100)));
const { applyLoaders } = prepareStory(
{ id, name, loaders: [loader as any], moduleExport },
{ id, title },
{ render }
);
const storyContext = { context: 'value' } as any;
const loadedContext = await applyLoaders(storyContext);
expect(loader).toHaveBeenCalledWith(storyContext);
expect(loadedContext).toEqual({
context: 'value',
loaded: { foo: 7 },
});
});
it('loaders are composed in the right order', async () => {
const globalLoader = async () => ({ foo: 1, bar: 1, baz: 1 });
const componentLoader = async () => ({ foo: 3, bar: 3 });
const storyLoader = async () => ({ foo: 5 });
const { applyLoaders } = prepareStory(
{ id, name, loaders: [storyLoader], moduleExport },
{ id, title, loaders: [componentLoader] },
{ render, loaders: [globalLoader] }
);
const storyContext = { context: 'value' } as any;
const loadedContext = await applyLoaders(storyContext);
expect(loadedContext).toEqual({
context: 'value',
loaded: { foo: 5, bar: 3, baz: 1 },
});
});
it('later loaders override earlier loaders', async () => {
const loaders: any[] = [
async () => new Promise((r) => setTimeout(() => r({ foo: 7 }), 100)),
async () => new Promise((r) => setTimeout(() => r({ foo: 3 }), 50)),
];
const { applyLoaders } = prepareStory(
{ id, name, loaders, moduleExport },
{ id, title },
{ render }
);
const storyContext = { context: 'value' } as any;
const loadedContext = await applyLoaders(storyContext);
expect(loadedContext).toEqual({
context: 'value',
loaded: { foo: 3 },
});
});
});
describe('undecoratedStoryFn', () => {
it('args are mapped by argTypes[x].mapping', () => {
const renderMock = jest.fn();
const story = prepareStory(
{
id,
name,
argTypes: {
one: { name: 'one', type: { name: 'string' }, mapping: { 1: 'mapped' } },
two: { name: 'two', type: { name: 'string' }, mapping: { 1: 'no match' } },
},
args: { one: 1, two: 2, three: 3 },
moduleExport,
},
{ id, title },
{ render: renderMock }
);
const context = story.prepareContext({ args: story.initialArgs, ...story } as any);
story.undecoratedStoryFn(context);
expect(renderMock).toHaveBeenCalledWith(
{ one: 'mapped', two: 2, three: 3 },
expect.objectContaining({ args: { one: 'mapped', two: 2, three: 3 } })
);
});
it('passes args as the first argument to the story if `parameters.passArgsFirst` is true', () => {
const renderMock = jest.fn();
const firstStory = prepareStory(
{ id, name, args: { a: 1 }, parameters: { passArgsFirst: true }, moduleExport },
{ id, title },
{ render: renderMock }
);
firstStory.undecoratedStoryFn({ args: firstStory.initialArgs, ...firstStory } as any);
expect(renderMock).toHaveBeenCalledWith(
{ a: 1 },
expect.objectContaining({ args: { a: 1 } })
);
const secondStory = prepareStory(
{ id, name, args: { a: 1 }, parameters: { passArgsFirst: false }, moduleExport },
{ id, title },
{ render: renderMock }
);
secondStory.undecoratedStoryFn({ args: secondStory.initialArgs, ...secondStory } as any);
expect(renderMock).toHaveBeenCalledWith(expect.objectContaining({ args: { a: 1 } }));
});
});
describe('storyFn', () => {
it('produces a story with inherited decorators applied', () => {
const renderMock = jest.fn();
const globalDecorator = jest.fn((s) => s());
const componentDecorator = jest.fn((s) => s());
const storyDecorator = jest.fn((s) => s());
const story = prepareStory(
{
id,
name,
decorators: [storyDecorator],
moduleExport,
},
{ id, title, decorators: [componentDecorator] },
{ render: renderMock, decorators: [globalDecorator] }
);
addons.setChannel({ on: jest.fn(), removeListener: jest.fn() } as any);
const hooks = new HooksContext();
story.unboundStoryFn({ args: story.initialArgs, hooks, ...story } as any);
expect(globalDecorator).toHaveBeenCalled();
expect(componentDecorator).toHaveBeenCalled();
expect(storyDecorator).toHaveBeenCalled();
expect(renderMock).toHaveBeenCalled();
hooks.clean();
});
it('prepared context is applied to decorators', () => {
const renderMock = jest.fn();
let ctx1;
let ctx2;
let ctx3;
const globalDecorator = jest.fn((fn, ctx) => {
ctx1 = ctx;
return fn();
});
const componentDecorator = jest.fn((fn, ctx) => {
ctx2 = ctx;
return fn();
});
const storyDecorator = jest.fn((fn, ctx) => {
ctx3 = ctx;
return fn();
});
const story = prepareStory(
{
id,
name,
argTypes: {
one: { name: 'one', type: { name: 'string' }, mapping: { 1: 'mapped-1' } },
},
args: { one: 1 },
decorators: [storyDecorator],
moduleExport,
},
{ id, title, decorators: [componentDecorator] },
{ render: renderMock, decorators: [globalDecorator] }
);
const hooks = new HooksContext();
const context = story.prepareContext({ args: story.initialArgs, hooks, ...story } as any);
story.unboundStoryFn(context);
expect(ctx1).toMatchObject({ args: { one: 'mapped-1' } });
expect(ctx2).toMatchObject({ args: { one: 'mapped-1' } });
expect(ctx3).toMatchObject({ args: { one: 'mapped-1' } });
hooks.clean();
});
});
describe('with `FEATURES.argTypeTargetsV7`', () => {
beforeEach(() => {
global.FEATURES = { breakingChangesV7: true, argTypeTargetsV7: true };
});
it('filters out targeted args', () => {
const renderMock = jest.fn();
const firstStory = prepareStory(
{
id,
name,
args: { a: 1, b: 2 },
argTypes: { b: { name: 'b', target: 'foo' } },
moduleExport,
},
{ id, title },
{ render: renderMock }
);
const context = firstStory.prepareContext({
args: firstStory.initialArgs,
hooks: new HooksContext(),
...firstStory,
} as any);
firstStory.unboundStoryFn(context);
expect(renderMock).toHaveBeenCalledWith(
{ a: 1 },
expect.objectContaining({ args: { a: 1 }, allArgs: { a: 1, b: 2 } })
);
});
it('filters out conditional args', () => {
const renderMock = jest.fn();
const firstStory = prepareStory(
{
id,
name,
args: { a: 1, b: 2 },
argTypes: { b: { name: 'b', if: { arg: 'a', truthy: false } } },
moduleExport,
},
{ id, title },
{ render: renderMock }
);
const context = firstStory.prepareContext({
args: firstStory.initialArgs,
hooks: new HooksContext(),
...firstStory,
} as any);
firstStory.unboundStoryFn(context);
expect(renderMock).toHaveBeenCalledWith(
{ a: 1 },
expect.objectContaining({ args: { a: 1 }, allArgs: { a: 1, b: 2 } })
);
});
it('adds argsByTarget to context', () => {
const renderMock = jest.fn();
const firstStory = prepareStory(
{
id,
name,
args: { a: 1, b: 2 },
argTypes: { b: { name: 'b', target: 'foo' } },
moduleExport,
},
{ id, title },
{ render: renderMock }
);
const context = firstStory.prepareContext({
args: firstStory.initialArgs,
hooks: new HooksContext(),
...firstStory,
} as any);
firstStory.unboundStoryFn(context);
expect(renderMock).toHaveBeenCalledWith(
{ a: 1 },
expect.objectContaining({ argsByTarget: { [NO_TARGET_NAME]: { a: 1 }, foo: { b: 2 } } })
);
});
it('always sets args, even when all are targetted', () => {
const renderMock = jest.fn();
const firstStory = prepareStory(
{
id,
name,
args: { b: 2 },
argTypes: { b: { name: 'b', target: 'foo' } },
moduleExport,
},
{ id, title },
{ render: renderMock }
);
const context = firstStory.prepareContext({
args: firstStory.initialArgs,
hooks: new HooksContext(),
...firstStory,
} as any);
firstStory.unboundStoryFn(context);
expect(renderMock).toHaveBeenCalledWith(
{},
expect.objectContaining({ argsByTarget: { foo: { b: 2 } } })
);
});
it('always sets args, even when none are set for the story', () => {
const renderMock = jest.fn();
const firstStory = prepareStory(
{
id,
name,
moduleExport,
},
{ id, title },
{ render: renderMock }
);
const context = firstStory.prepareContext({
args: firstStory.initialArgs,
hooks: new HooksContext(),
...firstStory,
} as any);
firstStory.unboundStoryFn(context);
expect(renderMock).toHaveBeenCalledWith({}, expect.objectContaining({ argsByTarget: {} }));
});
});
});
describe('playFunction', () => {
it('awaits play if defined', async () => {
const inner = jest.fn();
const play = jest.fn(async () => {
await new Promise((r) => setTimeout(r, 0)); // Ensure this puts an async boundary in
inner();
});
const { playFunction } = prepareStory(
{ id, name, play, moduleExport },
{ id, title },
{ render }
);
await playFunction!({} as PlayFunctionContext);
expect(play).toHaveBeenCalled();
expect(inner).toHaveBeenCalled();
});
it('provides step via runStep', async () => {
const stepPlay = jest.fn((context) => {
expect(context).not.toBeUndefined();
expect(context.step).toEqual(expect.any(Function));
});
const play = jest.fn(async ({ step }) => {
await step('label', stepPlay);
});
const runStep = jest.fn((label, p, c) => p(c));
const { playFunction } = prepareStory(
{ id, name, play, moduleExport },
{ id, title },
{ render, runStep }
);
await playFunction!({} as PlayFunctionContext);
expect(play).toHaveBeenCalled();
expect(stepPlay).toHaveBeenCalled();
expect(runStep).toBeCalledWith('label', stepPlay, expect.any(Object));
});
});
describe('moduleExport', () => {
it('are carried through from the story annotations', () => {
const storyObj = {};
const story = prepareStory({ id, name, moduleExport: storyObj }, { id, title }, { render });
expect(story.moduleExport).toBe(storyObj);
});
});
describe('prepareMeta', () => {
it('returns the same as prepareStory', () => {
const meta = {
id,
title,
moduleExport,
tags: ['some-tag'],
parameters: {
a: { name: 'component' },
b: { name: 'component' },
nested: { z: { name: 'component' }, y: { name: 'component' } },
},
args: {
a: 'component',
b: 'component',
nested: { z: 'component', y: 'component' },
},
argTypes: {
a: { name: 'a-story', type: booleanType },
nested: { name: 'nested', type: booleanType, a: 'story' },
},
};
const preparedStory = prepareStory({ id, name, moduleExport }, meta, { render });
const preparedMeta = prepareMeta(meta, { render }, {});
// omitting the properties from preparedStory that are not in preparedMeta
const {
name: storyName,
story,
applyLoaders,
originalStoryFn,
unboundStoryFn,
undecoratedStoryFn,
playFunction,
prepareContext,
...expectedPreparedMeta
} = preparedStory;
expect(preparedMeta).toMatchObject(expectedPreparedMeta);
expect(Object.keys(preparedMeta)).toHaveLength(Object.keys(expectedPreparedMeta).length);
});
});
| code/lib/preview-api/src/modules/store/csf/prepareStory.test.ts | 1 | https://github.com/storybookjs/storybook/commit/5344bd17421860b917b0828a30c3851d7c0eeaff | [
0.998976469039917,
0.0271301232278347,
0.00016509093984495848,
0.000174850327312015,
0.16084329783916473
] |
{
"id": 3,
"code_window": [
" return update;\n",
"};\n",
"\n",
"export const NO_TARGET_NAME = '';\n",
"export function groupArgsByTarget<TArgs extends Args = Args>({\n",
" args,\n",
" argTypes,\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"export const UNTARGETED = 'UNTARGETED';\n"
],
"file_path": "code/lib/preview-api/src/modules/store/args.ts",
"type": "replace",
"edit_start_line_idx": 146
} | // @ts-expect-error The generated definition file is empty. https://github.com/egoist/tsup/issues/762
export * from '@storybook/addon-outline/manager';
| code/addons/essentials/src/outline/manager.ts | 0 | https://github.com/storybookjs/storybook/commit/5344bd17421860b917b0828a30c3851d7c0eeaff | [
0.00016649567987769842,
0.00016649567987769842,
0.00016649567987769842,
0.00016649567987769842,
0
] |
{
"id": 3,
"code_window": [
" return update;\n",
"};\n",
"\n",
"export const NO_TARGET_NAME = '';\n",
"export function groupArgsByTarget<TArgs extends Args = Args>({\n",
" args,\n",
" argTypes,\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"export const UNTARGETED = 'UNTARGETED';\n"
],
"file_path": "code/lib/preview-api/src/modules/store/args.ts",
"type": "replace",
"edit_start_line_idx": 146
} | ```ts
// .storybook/main.ts
// Replace your-framework with the framework you are using (e.g., react-webpack5, vue3-webpack5)
import type { StorybookConfig } from '@storybook/your-framework';
const config: StorybookConfig = {
// Your Storybook configuration
refs: {
'package-name': { disable: true },
},
};
export default config;
```
| docs/snippets/common/storybook-main-register-essentials-addon.ts.mdx | 0 | https://github.com/storybookjs/storybook/commit/5344bd17421860b917b0828a30c3851d7c0eeaff | [
0.0001721541048027575,
0.0001700753637123853,
0.0001679966226220131,
0.0001700753637123853,
0.0000020787410903722048
] |
{
"id": 3,
"code_window": [
" return update;\n",
"};\n",
"\n",
"export const NO_TARGET_NAME = '';\n",
"export function groupArgsByTarget<TArgs extends Args = Args>({\n",
" args,\n",
" argTypes,\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"export const UNTARGETED = 'UNTARGETED';\n"
],
"file_path": "code/lib/preview-api/src/modules/store/args.ts",
"type": "replace",
"edit_start_line_idx": 146
} | const path = require('path');
const baseConfig = require('../../jest.config.browser');
module.exports = {
...baseConfig,
displayName: __dirname.split(path.sep).slice(-2).join(path.posix.sep),
};
| code/addons/measure/jest.config.js | 0 | https://github.com/storybookjs/storybook/commit/5344bd17421860b917b0828a30c3851d7c0eeaff | [
0.00017225822375621647,
0.00017225822375621647,
0.00017225822375621647,
0.00017225822375621647,
0
] |
{
"id": 4,
"code_window": [
" args,\n",
" argTypes,\n",
"}: StoryContext<Renderer, TArgs>) {\n",
" const groupedArgs: Record<string, Partial<TArgs>> = {};\n",
" (Object.entries(args) as [keyof TArgs, any][]).forEach(([name, value]) => {\n",
" const { target = NO_TARGET_NAME } = (argTypes[name] || {}) as { target?: string };\n",
"\n",
" groupedArgs[target] = groupedArgs[target] || {};\n",
" groupedArgs[target][name] = value;\n",
" });\n",
" return groupedArgs;\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" const { target = UNTARGETED } = (argTypes[name] || {}) as { target?: string };\n"
],
"file_path": "code/lib/preview-api/src/modules/store/args.ts",
"type": "replace",
"edit_start_line_idx": 153
} | import { dequal as deepEqual } from 'dequal';
import type { Renderer, Args, ArgTypes, InputType, SBType, StoryContext } from '@storybook/types';
import { once } from '@storybook/client-logger';
import isPlainObject from 'lodash/isPlainObject.js';
import { dedent } from 'ts-dedent';
const INCOMPATIBLE = Symbol('incompatible');
const map = (arg: unknown, argType: InputType): any => {
const type = argType.type as SBType;
if (arg === undefined || arg === null || !type) return arg;
if (argType.mapping) {
return arg;
}
switch (type.name) {
case 'string':
return String(arg);
case 'enum':
return arg;
case 'number':
return Number(arg);
case 'boolean':
return arg === 'true';
case 'array':
if (!type.value || !Array.isArray(arg)) return INCOMPATIBLE;
return arg.reduce((acc, item, index) => {
const mapped = map(item, { type: type.value });
if (mapped !== INCOMPATIBLE) acc[index] = mapped;
return acc;
}, new Array(arg.length));
case 'object':
if (typeof arg === 'string' || typeof arg === 'number') return arg;
if (!type.value || typeof arg !== 'object') return INCOMPATIBLE;
return Object.entries(arg).reduce((acc, [key, val]) => {
const mapped = map(val, { type: type.value[key] });
return mapped === INCOMPATIBLE ? acc : Object.assign(acc, { [key]: mapped });
}, {} as Args);
default:
return INCOMPATIBLE;
}
};
export const mapArgsToTypes = (args: Args, argTypes: ArgTypes): Args => {
return Object.entries(args).reduce((acc, [key, value]) => {
if (!argTypes[key]) return acc;
const mapped = map(value, argTypes[key]);
return mapped === INCOMPATIBLE ? acc : Object.assign(acc, { [key]: mapped });
}, {});
};
export const combineArgs = (value: any, update: any): Args => {
if (Array.isArray(value) && Array.isArray(update)) {
return update
.reduce(
(acc, upd, index) => {
acc[index] = combineArgs(value[index], update[index]);
return acc;
},
[...value]
)
.filter((v: any) => v !== undefined);
}
if (!isPlainObject(value) || !isPlainObject(update)) return update;
return Object.keys({ ...value, ...update }).reduce((acc, key) => {
if (key in update) {
const combined = combineArgs(value[key], update[key]);
if (combined !== undefined) acc[key] = combined;
} else {
acc[key] = value[key];
}
return acc;
}, {} as any);
};
export const validateOptions = (args: Args, argTypes: ArgTypes): Args => {
return Object.entries(argTypes).reduce((acc, [key, { options }]) => {
// Don't set args that are not defined in `args` (they can be undefined in there)
// see https://github.com/storybookjs/storybook/issues/15630 and
// https://github.com/storybookjs/storybook/issues/17063
function allowArg() {
if (key in args) {
acc[key] = args[key];
}
return acc;
}
if (!options) return allowArg();
if (!Array.isArray(options)) {
once.error(dedent`
Invalid argType: '${key}.options' should be an array.
More info: https://storybook.js.org/docs/react/api/argtypes
`);
return allowArg();
}
if (options.some((opt) => opt && ['object', 'function'].includes(typeof opt))) {
once.error(dedent`
Invalid argType: '${key}.options' should only contain primitives. Use a 'mapping' for complex values.
More info: https://storybook.js.org/docs/react/writing-stories/args#mapping-to-complex-arg-values
`);
return allowArg();
}
const isArray = Array.isArray(args[key]);
const invalidIndex = isArray && args[key].findIndex((val: any) => !options.includes(val));
const isValidArray = isArray && invalidIndex === -1;
if (args[key] === undefined || options.includes(args[key]) || isValidArray) {
return allowArg();
}
const field = isArray ? `${key}[${invalidIndex}]` : key;
const supportedOptions = options
.map((opt: any) => (typeof opt === 'string' ? `'${opt}'` : String(opt)))
.join(', ');
once.warn(`Received illegal value for '${field}'. Supported options: ${supportedOptions}`);
return acc;
}, {} as Args);
};
// TODO -- copied from router, needs to be in a shared location
export const DEEPLY_EQUAL = Symbol('Deeply equal');
export const deepDiff = (value: any, update: any): any => {
if (typeof value !== typeof update) return update;
if (deepEqual(value, update)) return DEEPLY_EQUAL;
if (Array.isArray(value) && Array.isArray(update)) {
const res = update.reduce((acc, upd, index) => {
const diff = deepDiff(value[index], upd);
if (diff !== DEEPLY_EQUAL) acc[index] = diff;
return acc;
}, new Array(update.length));
if (update.length >= value.length) return res;
return res.concat(new Array(value.length - update.length).fill(undefined));
}
if (isPlainObject(value) && isPlainObject(update)) {
return Object.keys({ ...value, ...update }).reduce((acc, key) => {
const diff = deepDiff(value?.[key], update?.[key]);
return diff === DEEPLY_EQUAL ? acc : Object.assign(acc, { [key]: diff });
}, {});
}
return update;
};
export const NO_TARGET_NAME = '';
export function groupArgsByTarget<TArgs extends Args = Args>({
args,
argTypes,
}: StoryContext<Renderer, TArgs>) {
const groupedArgs: Record<string, Partial<TArgs>> = {};
(Object.entries(args) as [keyof TArgs, any][]).forEach(([name, value]) => {
const { target = NO_TARGET_NAME } = (argTypes[name] || {}) as { target?: string };
groupedArgs[target] = groupedArgs[target] || {};
groupedArgs[target][name] = value;
});
return groupedArgs;
}
export function noTargetArgs<TArgs extends Args = Args>(context: StoryContext<Renderer, TArgs>) {
return groupArgsByTarget(context)[NO_TARGET_NAME];
}
| code/lib/preview-api/src/modules/store/args.ts | 1 | https://github.com/storybookjs/storybook/commit/5344bd17421860b917b0828a30c3851d7c0eeaff | [
0.9984750151634216,
0.06989521533250809,
0.00016595804481767118,
0.00018747878493741155,
0.23357705771923065
] |
{
"id": 4,
"code_window": [
" args,\n",
" argTypes,\n",
"}: StoryContext<Renderer, TArgs>) {\n",
" const groupedArgs: Record<string, Partial<TArgs>> = {};\n",
" (Object.entries(args) as [keyof TArgs, any][]).forEach(([name, value]) => {\n",
" const { target = NO_TARGET_NAME } = (argTypes[name] || {}) as { target?: string };\n",
"\n",
" groupedArgs[target] = groupedArgs[target] || {};\n",
" groupedArgs[target][name] = value;\n",
" });\n",
" return groupedArgs;\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" const { target = UNTARGETED } = (argTypes[name] || {}) as { target?: string };\n"
],
"file_path": "code/lib/preview-api/src/modules/store/args.ts",
"type": "replace",
"edit_start_line_idx": 153
} | import type { ToolbarItem, ToolbarItemType } from '../types';
const disallowedCycleableItemTypes: Array<ToolbarItemType> = ['reset'];
export const createCycleValueArray = (items: ToolbarItem[]) => {
// Do not allow items in the cycle arrays that are conditional in placement
const valueArray = items
.filter((item) => !disallowedCycleableItemTypes.includes(item.type as ToolbarItemType))
.map((item) => item.value);
return valueArray;
};
| code/addons/toolbars/src/utils/create-cycle-value-array.ts | 0 | https://github.com/storybookjs/storybook/commit/5344bd17421860b917b0828a30c3851d7c0eeaff | [
0.00017436701455153525,
0.000171998719451949,
0.00016963040980044752,
0.000171998719451949,
0.0000023683023755438626
] |
{
"id": 4,
"code_window": [
" args,\n",
" argTypes,\n",
"}: StoryContext<Renderer, TArgs>) {\n",
" const groupedArgs: Record<string, Partial<TArgs>> = {};\n",
" (Object.entries(args) as [keyof TArgs, any][]).forEach(([name, value]) => {\n",
" const { target = NO_TARGET_NAME } = (argTypes[name] || {}) as { target?: string };\n",
"\n",
" groupedArgs[target] = groupedArgs[target] || {};\n",
" groupedArgs[target][name] = value;\n",
" });\n",
" return groupedArgs;\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" const { target = UNTARGETED } = (argTypes[name] || {}) as { target?: string };\n"
],
"file_path": "code/lib/preview-api/src/modules/store/args.ts",
"type": "replace",
"edit_start_line_idx": 153
} | ```ts
// MyComponent.stories.ts
import { userEvent, within } from '@storybook/testing-library';
import type { Meta, StoryObj } from '@storybook/web-components';
const meta: Meta = {
title: 'WithDelay',
component: 'demo-my-component',
};
export default meta;
type Story = StoryObj;
/* See https://storybook.js.org/docs/7.0/web-components/writing-stories/play-function#working-with-the-canvas
* to learn more about using the canvasElement to query the DOM
*/
export const DelayedStory: Story = {
play: async ({ canvasElement }) => {
const canvas = within(canvasElement);
const exampleElement = canvas.getByLabelText('example-element');
// The delay option set the ammount of milliseconds between characters being typed
await userEvent.type(exampleElement, 'random string', {
delay: 100,
});
const AnotherExampleElement = canvas.getByLabelText('another-example-element');
await userEvent.type(AnotherExampleElement, 'another random string', {
delay: 100,
});
},
};
```
| docs/snippets/web-components/my-component-play-function-with-delay.ts.mdx | 0 | https://github.com/storybookjs/storybook/commit/5344bd17421860b917b0828a30c3851d7c0eeaff | [
0.00027490590582601726,
0.00019796281412709504,
0.00017092362395487726,
0.00017301086336374283,
0.00004444456862984225
] |
{
"id": 4,
"code_window": [
" args,\n",
" argTypes,\n",
"}: StoryContext<Renderer, TArgs>) {\n",
" const groupedArgs: Record<string, Partial<TArgs>> = {};\n",
" (Object.entries(args) as [keyof TArgs, any][]).forEach(([name, value]) => {\n",
" const { target = NO_TARGET_NAME } = (argTypes[name] || {}) as { target?: string };\n",
"\n",
" groupedArgs[target] = groupedArgs[target] || {};\n",
" groupedArgs[target][name] = value;\n",
" });\n",
" return groupedArgs;\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" const { target = UNTARGETED } = (argTypes[name] || {}) as { target?: string };\n"
],
"file_path": "code/lib/preview-api/src/modules/store/args.ts",
"type": "replace",
"edit_start_line_idx": 153
} | import { global as globalThis } from '@storybook/global';
import type { PartialStoryFn, StoryContext } from '@storybook/types';
const greetingForLocale = (locale: string) => {
switch (locale) {
case 'es':
return 'Hola!';
case 'fr':
return 'Bonjour !';
case 'zh':
return '你好!';
case 'kr':
return '안녕하세요!';
case 'en':
default:
return 'Hello';
}
};
export default {
component: globalThis.Components.Pre,
decorators: [
(storyFn: PartialStoryFn, { globals }: StoryContext) => {
const object = {
...globals,
caption: `Locale is '${globals.locale}', so I say: ${greetingForLocale(globals.locale)}`,
};
return storyFn({ args: { object } });
},
],
};
export const Basic = {};
| code/addons/toolbars/template/stories/globals.stories.ts | 0 | https://github.com/storybookjs/storybook/commit/5344bd17421860b917b0828a30c3851d7c0eeaff | [
0.0002420878445263952,
0.00018968193035107106,
0.00017067899170797318,
0.0001729804353090003,
0.000030310911824926734
] |
{
"id": 5,
"code_window": [
"}\n",
"\n",
"export function noTargetArgs<TArgs extends Args = Args>(context: StoryContext<Renderer, TArgs>) {\n",
" return groupArgsByTarget(context)[NO_TARGET_NAME];\n",
"}"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
" return groupArgsByTarget(context)[UNTARGETED];\n"
],
"file_path": "code/lib/preview-api/src/modules/store/args.ts",
"type": "replace",
"edit_start_line_idx": 162
} | import { global } from '@storybook/global';
import type {
Renderer,
Args,
ArgsStoryFn,
LegacyStoryFn,
Parameters,
PlayFunction,
PlayFunctionContext,
StepLabel,
NormalizedComponentAnnotations,
NormalizedProjectAnnotations,
NormalizedStoryAnnotations,
PreparedStory,
StoryContext,
StoryContextForEnhancers,
StoryContextForLoaders,
StrictArgTypes,
PreparedMeta,
ModuleExport,
} from '@storybook/types';
import { includeConditionalArg } from '@storybook/csf';
import { applyHooks } from '../../addons';
import { combineParameters } from '../parameters';
import { defaultDecorateStory } from '../decorators';
import { groupArgsByTarget, NO_TARGET_NAME } from '../args';
// Combine all the metadata about a story (both direct and inherited from the component/global scope)
// into a "renderable" story function, with all decorators applied, parameters passed as context etc
//
// Note that this story function is *stateless* in the sense that it does not track args or globals
// Instead, it is expected these are tracked separately (if necessary) and are passed into each invocation.
export function prepareStory<TRenderer extends Renderer>(
storyAnnotations: NormalizedStoryAnnotations<TRenderer>,
componentAnnotations: NormalizedComponentAnnotations<TRenderer>,
projectAnnotations: NormalizedProjectAnnotations<TRenderer>
): PreparedStory<TRenderer> {
// NOTE: in the current implementation we are doing everything once, up front, rather than doing
// anything at render time. The assumption is that as we don't load all the stories at once, this
// will have a limited cost. If this proves misguided, we can refactor it.
const { moduleExport, id, name } = storyAnnotations || {};
const partialAnnotations = preparePartialAnnotations(
storyAnnotations,
componentAnnotations,
projectAnnotations
);
const loaders = [
...(projectAnnotations.loaders || []),
...(componentAnnotations.loaders || []),
...(storyAnnotations?.loaders || []),
];
const applyLoaders = async (context: StoryContextForLoaders<TRenderer>) => {
const loadResults = await Promise.all(loaders.map((loader) => loader(context)));
const loaded = Object.assign({}, ...loadResults);
return { ...context, loaded };
};
const undecoratedStoryFn: LegacyStoryFn<TRenderer> = (context: StoryContext<TRenderer>) => {
const { passArgsFirst: renderTimePassArgsFirst = true } = context.parameters;
return renderTimePassArgsFirst
? (render as ArgsStoryFn<TRenderer>)(context.args, context)
: (render as LegacyStoryFn<TRenderer>)(context);
};
// Currently it is only possible to set these globally
const { applyDecorators = defaultDecorateStory, runStep } = projectAnnotations;
const decorators = [
...(storyAnnotations?.decorators || []),
...(componentAnnotations.decorators || []),
...(projectAnnotations.decorators || []),
];
// The render function on annotations *has* to be an `ArgsStoryFn`, so when we normalize
// CSFv1/2, we use a new field called `userStoryFn` so we know that it can be a LegacyStoryFn
const render =
storyAnnotations?.userStoryFn ||
storyAnnotations?.render ||
componentAnnotations.render ||
projectAnnotations.render;
if (!render) throw new Error(`No render function available for storyId '${id}'`);
const decoratedStoryFn = applyHooks<TRenderer>(applyDecorators)(undecoratedStoryFn, decorators);
const unboundStoryFn = (context: StoryContext<TRenderer>) => decoratedStoryFn(context);
// prepareContext is invoked at StoryRender.render()
// the context is prepared before invoking the render function, instead of here directly
// to ensure args don't loose there special properties set by the renderer
// eg. reactive proxies set by frameworks like SolidJS or Vue
const prepareContext = (context: StoryContext<TRenderer>) => {
let finalContext: StoryContext<TRenderer> = context;
if (global.FEATURES?.argTypeTargetsV7) {
const argsByTarget = groupArgsByTarget(context);
finalContext = {
...context,
allArgs: context.args,
argsByTarget,
args: argsByTarget[NO_TARGET_NAME] || {},
};
}
const mappedArgs = Object.entries(finalContext.args).reduce((acc, [key, val]) => {
const mapping = finalContext.argTypes[key]?.mapping;
acc[key] = mapping && val in mapping ? mapping[val] : val;
return acc;
}, {} as Args);
const includedArgs = Object.entries(mappedArgs).reduce((acc, [key, val]) => {
const argType = finalContext.argTypes[key] || {};
if (includeConditionalArg(argType, mappedArgs, finalContext.globals)) acc[key] = val;
return acc;
}, {} as Args);
return { ...finalContext, args: includedArgs };
};
const play = storyAnnotations?.play || componentAnnotations.play;
const playFunction =
play &&
(async (storyContext: StoryContext<TRenderer>) => {
const playFunctionContext: PlayFunctionContext<TRenderer> = {
...storyContext,
// eslint-disable-next-line @typescript-eslint/no-shadow
step: (label: StepLabel, play: PlayFunction<TRenderer>) =>
// TODO: We know runStep is defined, we need a proper normalized annotations type
runStep!(label, play, playFunctionContext),
};
return play(playFunctionContext);
});
return {
...partialAnnotations,
moduleExport,
id,
name,
story: name,
originalStoryFn: render,
undecoratedStoryFn,
unboundStoryFn,
applyLoaders,
playFunction,
prepareContext,
};
}
export function prepareMeta<TRenderer extends Renderer>(
componentAnnotations: NormalizedComponentAnnotations<TRenderer>,
projectAnnotations: NormalizedProjectAnnotations<TRenderer>,
moduleExport: ModuleExport
): PreparedMeta<TRenderer> {
return {
...preparePartialAnnotations(undefined, componentAnnotations, projectAnnotations),
moduleExport,
};
}
function preparePartialAnnotations<TRenderer extends Renderer>(
storyAnnotations: NormalizedStoryAnnotations<TRenderer> | undefined,
componentAnnotations: NormalizedComponentAnnotations<TRenderer>,
projectAnnotations: NormalizedProjectAnnotations<TRenderer>
): Omit<StoryContextForEnhancers<TRenderer>, 'name' | 'story'> {
// NOTE: in the current implementation we are doing everything once, up front, rather than doing
// anything at render time. The assumption is that as we don't load all the stories at once, this
// will have a limited cost. If this proves misguided, we can refactor it.
const id = storyAnnotations?.id || componentAnnotations.id;
const tags = [...(storyAnnotations?.tags || componentAnnotations.tags || []), 'story'];
const parameters: Parameters = combineParameters(
projectAnnotations.parameters,
componentAnnotations.parameters,
storyAnnotations?.parameters
);
// Currently it is only possible to set these globally
const { argTypesEnhancers = [], argsEnhancers = [] } = projectAnnotations;
// The render function on annotations *has* to be an `ArgsStoryFn`, so when we normalize
// CSFv1/2, we use a new field called `userStoryFn` so we know that it can be a LegacyStoryFn
const render =
storyAnnotations?.userStoryFn ||
storyAnnotations?.render ||
componentAnnotations.render ||
projectAnnotations.render;
if (!render) throw new Error(`No render function available for id '${id}'`);
const passedArgTypes: StrictArgTypes = combineParameters(
projectAnnotations.argTypes,
componentAnnotations.argTypes,
storyAnnotations?.argTypes
) as StrictArgTypes;
const { passArgsFirst = true } = parameters;
// eslint-disable-next-line no-underscore-dangle
parameters.__isArgsStory = passArgsFirst && render.length > 0;
// Pull out args[X] into initialArgs for argTypes enhancers
const passedArgs: Args = {
...projectAnnotations.args,
...componentAnnotations.args,
...storyAnnotations?.args,
} as Args;
const contextForEnhancers: StoryContextForEnhancers<TRenderer> = {
componentId: componentAnnotations.id,
title: componentAnnotations.title,
kind: componentAnnotations.title, // Back compat
id: storyAnnotations?.id || componentAnnotations.id,
// if there's no story name, we create a fake one since enhancers expect a name
name: storyAnnotations?.name || '__meta',
story: storyAnnotations?.name || '__meta', // Back compat
component: componentAnnotations.component,
subcomponents: componentAnnotations.subcomponents,
tags,
parameters,
initialArgs: passedArgs,
argTypes: passedArgTypes,
};
contextForEnhancers.argTypes = argTypesEnhancers.reduce(
(accumulatedArgTypes, enhancer) =>
enhancer({ ...contextForEnhancers, argTypes: accumulatedArgTypes }),
contextForEnhancers.argTypes
);
const initialArgsBeforeEnhancers = { ...passedArgs };
contextForEnhancers.initialArgs = argsEnhancers.reduce(
(accumulatedArgs: Args, enhancer) => ({
...accumulatedArgs,
...enhancer({
...contextForEnhancers,
initialArgs: accumulatedArgs,
}),
}),
initialArgsBeforeEnhancers
);
// Add some of our metadata into parameters as we used to do this in 6.x and users may be relying on it
if (!global.FEATURES?.breakingChangesV7) {
contextForEnhancers.parameters = {
...contextForEnhancers.parameters,
__id: id,
globals: projectAnnotations.globals,
globalTypes: projectAnnotations.globalTypes,
args: contextForEnhancers.initialArgs,
argTypes: contextForEnhancers.argTypes,
};
}
const { name, story, ...withoutStoryIdentifiers } = contextForEnhancers;
return withoutStoryIdentifiers;
}
| code/lib/preview-api/src/modules/store/csf/prepareStory.ts | 1 | https://github.com/storybookjs/storybook/commit/5344bd17421860b917b0828a30c3851d7c0eeaff | [
0.9244817495346069,
0.048638876527547836,
0.00016500864876434207,
0.00025867982185445726,
0.1798071414232254
] |
{
"id": 5,
"code_window": [
"}\n",
"\n",
"export function noTargetArgs<TArgs extends Args = Args>(context: StoryContext<Renderer, TArgs>) {\n",
" return groupArgsByTarget(context)[NO_TARGET_NAME];\n",
"}"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
" return groupArgsByTarget(context)[UNTARGETED];\n"
],
"file_path": "code/lib/preview-api/src/modules/store/args.ts",
"type": "replace",
"edit_start_line_idx": 162
} | ```ts
// MyComponent.stories.ts
// For Vue 3 use import type { Meta, StoryObj } from '@storybook/vue3';
import type { Meta, StoryObj } from '@storybook/vue';
import MyComponent from './MyComponent.vue';
const meta: Meta<typeof MyComponent> = {
/* 👇 The title prop is optional.
* See https://storybook.js.org/docs/7.0/vue/configure/overview#configure-story-loading
* to learn how to generate automatic titles
*/
title: 'Path/To/MyComponent',
component: MyComponent,
};
export default meta;
type Story = StoryObj<typeof MyComponent>;
/*
*👇 Render functions are a framework specific feature to allow you control on how the component renders.
* See https://storybook.js.org/docs/7.0/vue/api/csf
* to learn how to use render functions.
*/
export const Basic: Story = {
render: () => ({
components: { MyComponent },
template: '<MyComponent />',
}),
};
export const WithProp: Story = {
render: () => ({
components: { MyComponent },
template: '<MyComponent prop="value"/>',
}),
};
```
| docs/snippets/vue/my-component-story-basic-and-props.ts.mdx | 0 | https://github.com/storybookjs/storybook/commit/5344bd17421860b917b0828a30c3851d7c0eeaff | [
0.0013323418097570539,
0.0004957151832059026,
0.00016661161498632282,
0.0002419536904199049,
0.00048662949120625854
] |
{
"id": 5,
"code_window": [
"}\n",
"\n",
"export function noTargetArgs<TArgs extends Args = Args>(context: StoryContext<Renderer, TArgs>) {\n",
" return groupArgsByTarget(context)[NO_TARGET_NAME];\n",
"}"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
" return groupArgsByTarget(context)[UNTARGETED];\n"
],
"file_path": "code/lib/preview-api/src/modules/store/args.ts",
"type": "replace",
"edit_start_line_idx": 162
} | import { global as globalThis } from '@storybook/global';
import { Meta, Story, Canvas } from '@storybook/addon-docs';
<Meta title="stories/renderers/vue3/vue3-mdx" />
# Vue3-specific MDX Stories
export const Button = globalThis.Components.Button;
export const Template = (args, { argTypes }) => ({
components: { MyButton: Button },
template: '<my-button v-bind="args" />',
setup() {
return { args };
},
});
## Primary
<Canvas>
<Story name="Primary">
{{
components: { MyButton: Button },
template: '<my-button :primary="true" label="Primary button" />',
}}
</Story>
</Canvas>
## Secondary
<Canvas>
<Story name="Secondary">
{{
components: { MyButton: Button },
template: '<my-button :primary="false" label="Secondary button" />',
}}
</Story>
</Canvas>
## From template
<Canvas>
<Story name="From Template" args={{ label: 'From template' }}>
{Template.bind({})}
</Story>
</Canvas>
| code/renderers/vue3/template/stories/vue3-mdx.stories.mdx | 0 | https://github.com/storybookjs/storybook/commit/5344bd17421860b917b0828a30c3851d7c0eeaff | [
0.00017644171020947397,
0.00017306565132457763,
0.00016753033560235053,
0.000174366170540452,
0.000003046895699299057
] |
{
"id": 5,
"code_window": [
"}\n",
"\n",
"export function noTargetArgs<TArgs extends Args = Args>(context: StoryContext<Renderer, TArgs>) {\n",
" return groupArgsByTarget(context)[NO_TARGET_NAME];\n",
"}"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
" return groupArgsByTarget(context)[UNTARGETED];\n"
],
"file_path": "code/lib/preview-api/src/modules/store/args.ts",
"type": "replace",
"edit_start_line_idx": 162
} | // Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`react component properties ts-html 1`] = `Object {}`;
| code/renderers/react/template/stories/docgen-components/ts-html/argTypes.snapshot | 0 | https://github.com/storybookjs/storybook/commit/5344bd17421860b917b0828a30c3851d7c0eeaff | [
0.00017487283912487328,
0.00017487283912487328,
0.00017487283912487328,
0.00017487283912487328,
0
] |
{
"id": 6,
"code_window": [
"import { global } from '@storybook/global';\n",
"import { expect } from '@jest/globals';\n",
"import type { Renderer, ArgsEnhancer, PlayFunctionContext, SBScalarType } from '@storybook/types';\n",
"import { addons, HooksContext } from '../../addons';\n",
"\n",
"import { NO_TARGET_NAME } from '../args';\n",
"import { prepareStory, prepareMeta } from './prepareStory';\n",
"\n",
"jest.mock('@storybook/global', () => ({\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { UNTARGETED } from '../args';\n"
],
"file_path": "code/lib/preview-api/src/modules/store/csf/prepareStory.test.ts",
"type": "replace",
"edit_start_line_idx": 7
} | /// <reference types="@types/jest" />;
import { global } from '@storybook/global';
import { expect } from '@jest/globals';
import type { Renderer, ArgsEnhancer, PlayFunctionContext, SBScalarType } from '@storybook/types';
import { addons, HooksContext } from '../../addons';
import { NO_TARGET_NAME } from '../args';
import { prepareStory, prepareMeta } from './prepareStory';
jest.mock('@storybook/global', () => ({
global: {
...(jest.requireActual('@storybook/global') as any),
FEATURES: {
breakingChangesV7: true,
},
},
}));
const id = 'id';
const name = 'name';
const title = 'title';
const render = (args: any) => {};
const moduleExport = {};
const stringType: SBScalarType = { name: 'string' };
const numberType: SBScalarType = { name: 'number' };
const booleanType: SBScalarType = { name: 'boolean' };
beforeEach(() => {
global.FEATURES = { breakingChangesV7: true };
});
describe('prepareStory', () => {
describe('tags', () => {
it('story tags override component', () => {
const { tags } = prepareStory(
{ id, name, tags: ['story-1', 'story-2'], moduleExport },
{
id,
title,
tags: ['component-1', 'component-2'],
},
{ render }
);
expect(tags).toEqual(['story-1', 'story-2', 'story']);
});
it('component tags work if story are unset', () => {
const { tags } = prepareStory(
{ id, name, moduleExport },
{
id,
title,
tags: ['component-1', 'component-2'],
},
{ render }
);
expect(tags).toEqual(['component-1', 'component-2', 'story']);
});
it('sets a value even if annotations do not have tags', () => {
const { tags } = prepareStory({ id, name, moduleExport }, { id, title }, { render });
expect(tags).toEqual(['story']);
});
});
describe('parameters', () => {
it('are combined in the right order', () => {
const { parameters } = prepareStory(
{ id, name, parameters: { a: 'story', nested: { z: 'story' } }, moduleExport },
{
id,
title,
parameters: {
a: { name: 'component' },
b: { name: 'component' },
nested: { z: { name: 'component' }, y: { name: 'component' } },
},
},
{
render,
parameters: {
a: { name: 'global' },
b: { name: 'global' },
c: { name: 'global' },
nested: { z: { name: 'global' }, x: { name: 'global' } },
},
}
);
expect(parameters).toEqual({
__isArgsStory: true,
a: 'story',
b: { name: 'component' },
c: { name: 'global' },
nested: { z: 'story', y: { name: 'component' }, x: { name: 'global' } },
});
});
it('sets a value even if annotations do not have parameters', () => {
const { parameters } = prepareStory({ id, name, moduleExport }, { id, title }, { render });
expect(parameters).toEqual({ __isArgsStory: true });
});
it('does not set `__isArgsStory` if `passArgsFirst` is disabled', () => {
const { parameters } = prepareStory(
{ id, name, parameters: { passArgsFirst: false }, moduleExport },
{ id, title },
{ render }
);
expect(parameters).toEqual({ passArgsFirst: false, __isArgsStory: false });
});
it('does not set `__isArgsStory` if `render` does not take args', () => {
const { parameters } = prepareStory(
{ id, name, moduleExport },
{ id, title },
{ render: () => {} }
);
expect(parameters).toEqual({ __isArgsStory: false });
});
});
describe('args/initialArgs', () => {
it('are combined in the right order', () => {
const { initialArgs } = prepareStory(
{ id, name, args: { a: 'story', nested: { z: 'story' } }, moduleExport },
{
id,
title,
args: {
a: 'component',
b: 'component',
nested: { z: 'component', y: 'component' },
},
},
{
render,
args: {
a: 'global',
b: 'global',
c: 'global',
nested: { z: 'global', x: 'global' },
},
}
);
expect(initialArgs).toEqual({
a: 'story',
b: 'component',
c: 'global',
nested: { z: 'story' },
});
});
it('can be overriden by `undefined`', () => {
const { initialArgs } = prepareStory(
{ id, name, args: { a: undefined }, moduleExport },
{ id, title, args: { a: 'component' } },
{ render }
);
expect(initialArgs).toEqual({ a: undefined });
});
it('sets a value even if annotations do not have args', () => {
const { initialArgs } = prepareStory({ id, name, moduleExport }, { id, title }, { render });
expect(initialArgs).toEqual({});
});
describe('argsEnhancers', () => {
it('are applied in the right order', () => {
const run: number[] = [];
const enhancerOne: ArgsEnhancer<Renderer> = () => {
run.push(1);
return {};
};
const enhancerTwo: ArgsEnhancer<Renderer> = () => {
run.push(2);
return {};
};
prepareStory(
{ id, name, moduleExport },
{ id, title },
{ render, argsEnhancers: [enhancerOne, enhancerTwo] }
);
expect(run).toEqual([1, 2]);
});
it('allow you to add args', () => {
const enhancer = jest.fn(() => ({ c: 'd' }));
const { initialArgs } = prepareStory(
{ id, name, args: { a: 'b' }, moduleExport },
{ id, title },
{ render, argsEnhancers: [enhancer] }
);
expect(enhancer).toHaveBeenCalledWith(expect.objectContaining({ initialArgs: { a: 'b' } }));
expect(initialArgs).toEqual({ a: 'b', c: 'd' });
});
it('passes result of earlier enhancers into subsequent ones, and composes their output', () => {
const enhancerOne = jest.fn(() => ({ b: 'B' }));
const enhancerTwo = jest.fn(({ initialArgs }) =>
Object.entries(initialArgs).reduce(
(acc, [key, val]) => ({ ...acc, [key]: `enhanced ${val}` }),
{}
)
);
const enhancerThree = jest.fn(() => ({ c: 'C' }));
const { initialArgs } = prepareStory(
{ id, name, args: { a: 'A' }, moduleExport },
{ id, title },
{ render, argsEnhancers: [enhancerOne, enhancerTwo, enhancerThree] }
);
expect(enhancerOne).toHaveBeenCalledWith(
expect.objectContaining({ initialArgs: { a: 'A' } })
);
expect(enhancerTwo).toHaveBeenCalledWith(
expect.objectContaining({ initialArgs: { a: 'A', b: 'B' } })
);
expect(enhancerThree).toHaveBeenCalledWith(
expect.objectContaining({ initialArgs: { a: 'enhanced A', b: 'enhanced B' } })
);
expect(initialArgs).toEqual({
a: 'enhanced A',
b: 'enhanced B',
c: 'C',
});
});
});
});
describe('argTypes', () => {
it('are combined in the right order', () => {
const { argTypes } = prepareStory(
{
id,
name,
argTypes: {
a: { name: 'a-story', type: booleanType },
nested: { name: 'nested', type: booleanType, a: 'story' },
},
moduleExport,
},
{
id,
title,
argTypes: {
a: { name: 'a-component', type: stringType },
b: { name: 'b-component', type: stringType },
nested: { name: 'nested', type: booleanType, a: 'component', b: 'component' },
},
},
{
render,
argTypes: {
a: { name: 'a-global', type: numberType },
b: { name: 'b-global', type: numberType },
c: { name: 'c-global', type: numberType },
nested: { name: 'nested', type: booleanType, a: 'global', b: 'global', c: 'global' },
},
}
);
expect(argTypes).toEqual({
a: { name: 'a-story', type: booleanType },
b: { name: 'b-component', type: stringType },
c: { name: 'c-global', type: numberType },
nested: { name: 'nested', type: booleanType, a: 'story', b: 'component', c: 'global' },
});
});
describe('argTypesEnhancers', () => {
it('allows you to alter argTypes when stories are added', () => {
const enhancer = jest.fn((context) => ({ ...context.argTypes, c: { name: 'd' } }));
const { argTypes } = prepareStory(
{ id, name, argTypes: { a: { name: 'b' } }, moduleExport },
{ id, title },
{ render, argTypesEnhancers: [enhancer] }
);
expect(enhancer).toHaveBeenCalledWith(
expect.objectContaining({ argTypes: { a: { name: 'b' } } })
);
expect(argTypes).toEqual({ a: { name: 'b' }, c: { name: 'd' } });
});
it('does not merge argType enhancer results', () => {
const enhancer = jest.fn(() => ({ c: { name: 'd' } }));
const { argTypes } = prepareStory(
{ id, name, argTypes: { a: { name: 'b' } }, moduleExport },
{ id, title },
{ render, argTypesEnhancers: [enhancer] }
);
expect(enhancer).toHaveBeenCalledWith(
expect.objectContaining({ argTypes: { a: { name: 'b' } } })
);
expect(argTypes).toEqual({ c: { name: 'd' } });
});
it('recursively passes argTypes to successive enhancers', () => {
const firstEnhancer = jest.fn((context) => ({ ...context.argTypes, c: { name: 'd' } }));
const secondEnhancer = jest.fn((context) => ({ ...context.argTypes, e: { name: 'f' } }));
const { argTypes } = prepareStory(
{ id, name, argTypes: { a: { name: 'b' } }, moduleExport },
{ id, title },
{ render, argTypesEnhancers: [firstEnhancer, secondEnhancer] }
);
expect(firstEnhancer).toHaveBeenCalledWith(
expect.objectContaining({ argTypes: { a: { name: 'b' } } })
);
expect(secondEnhancer).toHaveBeenCalledWith(
expect.objectContaining({ argTypes: { a: { name: 'b' }, c: { name: 'd' } } })
);
expect(argTypes).toEqual({ a: { name: 'b' }, c: { name: 'd' }, e: { name: 'f' } });
});
});
});
describe('applyLoaders', () => {
it('awaits the result of a loader', async () => {
const loader = jest.fn(async () => new Promise((r) => setTimeout(() => r({ foo: 7 }), 100)));
const { applyLoaders } = prepareStory(
{ id, name, loaders: [loader as any], moduleExport },
{ id, title },
{ render }
);
const storyContext = { context: 'value' } as any;
const loadedContext = await applyLoaders(storyContext);
expect(loader).toHaveBeenCalledWith(storyContext);
expect(loadedContext).toEqual({
context: 'value',
loaded: { foo: 7 },
});
});
it('loaders are composed in the right order', async () => {
const globalLoader = async () => ({ foo: 1, bar: 1, baz: 1 });
const componentLoader = async () => ({ foo: 3, bar: 3 });
const storyLoader = async () => ({ foo: 5 });
const { applyLoaders } = prepareStory(
{ id, name, loaders: [storyLoader], moduleExport },
{ id, title, loaders: [componentLoader] },
{ render, loaders: [globalLoader] }
);
const storyContext = { context: 'value' } as any;
const loadedContext = await applyLoaders(storyContext);
expect(loadedContext).toEqual({
context: 'value',
loaded: { foo: 5, bar: 3, baz: 1 },
});
});
it('later loaders override earlier loaders', async () => {
const loaders: any[] = [
async () => new Promise((r) => setTimeout(() => r({ foo: 7 }), 100)),
async () => new Promise((r) => setTimeout(() => r({ foo: 3 }), 50)),
];
const { applyLoaders } = prepareStory(
{ id, name, loaders, moduleExport },
{ id, title },
{ render }
);
const storyContext = { context: 'value' } as any;
const loadedContext = await applyLoaders(storyContext);
expect(loadedContext).toEqual({
context: 'value',
loaded: { foo: 3 },
});
});
});
describe('undecoratedStoryFn', () => {
it('args are mapped by argTypes[x].mapping', () => {
const renderMock = jest.fn();
const story = prepareStory(
{
id,
name,
argTypes: {
one: { name: 'one', type: { name: 'string' }, mapping: { 1: 'mapped' } },
two: { name: 'two', type: { name: 'string' }, mapping: { 1: 'no match' } },
},
args: { one: 1, two: 2, three: 3 },
moduleExport,
},
{ id, title },
{ render: renderMock }
);
const context = story.prepareContext({ args: story.initialArgs, ...story } as any);
story.undecoratedStoryFn(context);
expect(renderMock).toHaveBeenCalledWith(
{ one: 'mapped', two: 2, three: 3 },
expect.objectContaining({ args: { one: 'mapped', two: 2, three: 3 } })
);
});
it('passes args as the first argument to the story if `parameters.passArgsFirst` is true', () => {
const renderMock = jest.fn();
const firstStory = prepareStory(
{ id, name, args: { a: 1 }, parameters: { passArgsFirst: true }, moduleExport },
{ id, title },
{ render: renderMock }
);
firstStory.undecoratedStoryFn({ args: firstStory.initialArgs, ...firstStory } as any);
expect(renderMock).toHaveBeenCalledWith(
{ a: 1 },
expect.objectContaining({ args: { a: 1 } })
);
const secondStory = prepareStory(
{ id, name, args: { a: 1 }, parameters: { passArgsFirst: false }, moduleExport },
{ id, title },
{ render: renderMock }
);
secondStory.undecoratedStoryFn({ args: secondStory.initialArgs, ...secondStory } as any);
expect(renderMock).toHaveBeenCalledWith(expect.objectContaining({ args: { a: 1 } }));
});
});
describe('storyFn', () => {
it('produces a story with inherited decorators applied', () => {
const renderMock = jest.fn();
const globalDecorator = jest.fn((s) => s());
const componentDecorator = jest.fn((s) => s());
const storyDecorator = jest.fn((s) => s());
const story = prepareStory(
{
id,
name,
decorators: [storyDecorator],
moduleExport,
},
{ id, title, decorators: [componentDecorator] },
{ render: renderMock, decorators: [globalDecorator] }
);
addons.setChannel({ on: jest.fn(), removeListener: jest.fn() } as any);
const hooks = new HooksContext();
story.unboundStoryFn({ args: story.initialArgs, hooks, ...story } as any);
expect(globalDecorator).toHaveBeenCalled();
expect(componentDecorator).toHaveBeenCalled();
expect(storyDecorator).toHaveBeenCalled();
expect(renderMock).toHaveBeenCalled();
hooks.clean();
});
it('prepared context is applied to decorators', () => {
const renderMock = jest.fn();
let ctx1;
let ctx2;
let ctx3;
const globalDecorator = jest.fn((fn, ctx) => {
ctx1 = ctx;
return fn();
});
const componentDecorator = jest.fn((fn, ctx) => {
ctx2 = ctx;
return fn();
});
const storyDecorator = jest.fn((fn, ctx) => {
ctx3 = ctx;
return fn();
});
const story = prepareStory(
{
id,
name,
argTypes: {
one: { name: 'one', type: { name: 'string' }, mapping: { 1: 'mapped-1' } },
},
args: { one: 1 },
decorators: [storyDecorator],
moduleExport,
},
{ id, title, decorators: [componentDecorator] },
{ render: renderMock, decorators: [globalDecorator] }
);
const hooks = new HooksContext();
const context = story.prepareContext({ args: story.initialArgs, hooks, ...story } as any);
story.unboundStoryFn(context);
expect(ctx1).toMatchObject({ args: { one: 'mapped-1' } });
expect(ctx2).toMatchObject({ args: { one: 'mapped-1' } });
expect(ctx3).toMatchObject({ args: { one: 'mapped-1' } });
hooks.clean();
});
});
describe('with `FEATURES.argTypeTargetsV7`', () => {
beforeEach(() => {
global.FEATURES = { breakingChangesV7: true, argTypeTargetsV7: true };
});
it('filters out targeted args', () => {
const renderMock = jest.fn();
const firstStory = prepareStory(
{
id,
name,
args: { a: 1, b: 2 },
argTypes: { b: { name: 'b', target: 'foo' } },
moduleExport,
},
{ id, title },
{ render: renderMock }
);
const context = firstStory.prepareContext({
args: firstStory.initialArgs,
hooks: new HooksContext(),
...firstStory,
} as any);
firstStory.unboundStoryFn(context);
expect(renderMock).toHaveBeenCalledWith(
{ a: 1 },
expect.objectContaining({ args: { a: 1 }, allArgs: { a: 1, b: 2 } })
);
});
it('filters out conditional args', () => {
const renderMock = jest.fn();
const firstStory = prepareStory(
{
id,
name,
args: { a: 1, b: 2 },
argTypes: { b: { name: 'b', if: { arg: 'a', truthy: false } } },
moduleExport,
},
{ id, title },
{ render: renderMock }
);
const context = firstStory.prepareContext({
args: firstStory.initialArgs,
hooks: new HooksContext(),
...firstStory,
} as any);
firstStory.unboundStoryFn(context);
expect(renderMock).toHaveBeenCalledWith(
{ a: 1 },
expect.objectContaining({ args: { a: 1 }, allArgs: { a: 1, b: 2 } })
);
});
it('adds argsByTarget to context', () => {
const renderMock = jest.fn();
const firstStory = prepareStory(
{
id,
name,
args: { a: 1, b: 2 },
argTypes: { b: { name: 'b', target: 'foo' } },
moduleExport,
},
{ id, title },
{ render: renderMock }
);
const context = firstStory.prepareContext({
args: firstStory.initialArgs,
hooks: new HooksContext(),
...firstStory,
} as any);
firstStory.unboundStoryFn(context);
expect(renderMock).toHaveBeenCalledWith(
{ a: 1 },
expect.objectContaining({ argsByTarget: { [NO_TARGET_NAME]: { a: 1 }, foo: { b: 2 } } })
);
});
it('always sets args, even when all are targetted', () => {
const renderMock = jest.fn();
const firstStory = prepareStory(
{
id,
name,
args: { b: 2 },
argTypes: { b: { name: 'b', target: 'foo' } },
moduleExport,
},
{ id, title },
{ render: renderMock }
);
const context = firstStory.prepareContext({
args: firstStory.initialArgs,
hooks: new HooksContext(),
...firstStory,
} as any);
firstStory.unboundStoryFn(context);
expect(renderMock).toHaveBeenCalledWith(
{},
expect.objectContaining({ argsByTarget: { foo: { b: 2 } } })
);
});
it('always sets args, even when none are set for the story', () => {
const renderMock = jest.fn();
const firstStory = prepareStory(
{
id,
name,
moduleExport,
},
{ id, title },
{ render: renderMock }
);
const context = firstStory.prepareContext({
args: firstStory.initialArgs,
hooks: new HooksContext(),
...firstStory,
} as any);
firstStory.unboundStoryFn(context);
expect(renderMock).toHaveBeenCalledWith({}, expect.objectContaining({ argsByTarget: {} }));
});
});
});
describe('playFunction', () => {
it('awaits play if defined', async () => {
const inner = jest.fn();
const play = jest.fn(async () => {
await new Promise((r) => setTimeout(r, 0)); // Ensure this puts an async boundary in
inner();
});
const { playFunction } = prepareStory(
{ id, name, play, moduleExport },
{ id, title },
{ render }
);
await playFunction!({} as PlayFunctionContext);
expect(play).toHaveBeenCalled();
expect(inner).toHaveBeenCalled();
});
it('provides step via runStep', async () => {
const stepPlay = jest.fn((context) => {
expect(context).not.toBeUndefined();
expect(context.step).toEqual(expect.any(Function));
});
const play = jest.fn(async ({ step }) => {
await step('label', stepPlay);
});
const runStep = jest.fn((label, p, c) => p(c));
const { playFunction } = prepareStory(
{ id, name, play, moduleExport },
{ id, title },
{ render, runStep }
);
await playFunction!({} as PlayFunctionContext);
expect(play).toHaveBeenCalled();
expect(stepPlay).toHaveBeenCalled();
expect(runStep).toBeCalledWith('label', stepPlay, expect.any(Object));
});
});
describe('moduleExport', () => {
it('are carried through from the story annotations', () => {
const storyObj = {};
const story = prepareStory({ id, name, moduleExport: storyObj }, { id, title }, { render });
expect(story.moduleExport).toBe(storyObj);
});
});
describe('prepareMeta', () => {
it('returns the same as prepareStory', () => {
const meta = {
id,
title,
moduleExport,
tags: ['some-tag'],
parameters: {
a: { name: 'component' },
b: { name: 'component' },
nested: { z: { name: 'component' }, y: { name: 'component' } },
},
args: {
a: 'component',
b: 'component',
nested: { z: 'component', y: 'component' },
},
argTypes: {
a: { name: 'a-story', type: booleanType },
nested: { name: 'nested', type: booleanType, a: 'story' },
},
};
const preparedStory = prepareStory({ id, name, moduleExport }, meta, { render });
const preparedMeta = prepareMeta(meta, { render }, {});
// omitting the properties from preparedStory that are not in preparedMeta
const {
name: storyName,
story,
applyLoaders,
originalStoryFn,
unboundStoryFn,
undecoratedStoryFn,
playFunction,
prepareContext,
...expectedPreparedMeta
} = preparedStory;
expect(preparedMeta).toMatchObject(expectedPreparedMeta);
expect(Object.keys(preparedMeta)).toHaveLength(Object.keys(expectedPreparedMeta).length);
});
});
| code/lib/preview-api/src/modules/store/csf/prepareStory.test.ts | 1 | https://github.com/storybookjs/storybook/commit/5344bd17421860b917b0828a30c3851d7c0eeaff | [
0.9930160045623779,
0.014417789876461029,
0.0001640117698116228,
0.0005015032947994769,
0.1137697845697403
] |
{
"id": 6,
"code_window": [
"import { global } from '@storybook/global';\n",
"import { expect } from '@jest/globals';\n",
"import type { Renderer, ArgsEnhancer, PlayFunctionContext, SBScalarType } from '@storybook/types';\n",
"import { addons, HooksContext } from '../../addons';\n",
"\n",
"import { NO_TARGET_NAME } from '../args';\n",
"import { prepareStory, prepareMeta } from './prepareStory';\n",
"\n",
"jest.mock('@storybook/global', () => ({\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { UNTARGETED } from '../args';\n"
],
"file_path": "code/lib/preview-api/src/modules/store/csf/prepareStory.test.ts",
"type": "replace",
"edit_start_line_idx": 7
} | ```ts
// YourComponent.stories.ts|tsx
import { YourComponent } from './YourComponent';
// Replace your-framework with the name of your framework
import type { Meta } from '@storybook/your-framework';
const meta: Meta<typeof YourComponent> = {
/* 👇 The title prop is optional.
* See https://storybook.js.org/docs/7.0/react/configure/overview#configure-story-loading
* to learn how to generate automatic titles
*/
title: 'YourComponent',
component: YourComponent,
argTypes: {
// foo is the property we want to remove from the UI
foo: {
control: false,
},
},
};
export default meta;
```
| docs/snippets/common/component-story-disable-controls-alt.ts.mdx | 0 | https://github.com/storybookjs/storybook/commit/5344bd17421860b917b0828a30c3851d7c0eeaff | [
0.00017471268074586987,
0.00016788516950327903,
0.0001622987911105156,
0.00016664403665345162,
0.0000051433758017083164
] |
{
"id": 6,
"code_window": [
"import { global } from '@storybook/global';\n",
"import { expect } from '@jest/globals';\n",
"import type { Renderer, ArgsEnhancer, PlayFunctionContext, SBScalarType } from '@storybook/types';\n",
"import { addons, HooksContext } from '../../addons';\n",
"\n",
"import { NO_TARGET_NAME } from '../args';\n",
"import { prepareStory, prepareMeta } from './prepareStory';\n",
"\n",
"jest.mock('@storybook/global', () => ({\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { UNTARGETED } from '../args';\n"
],
"file_path": "code/lib/preview-api/src/modules/store/csf/prepareStory.test.ts",
"type": "replace",
"edit_start_line_idx": 7
} | ---
title: 'Code snippets contributions'
---
Add or update the code snippets in the documentation. This page outlines how the code snippets are structured.
## Documented frameworks
Storybook maintains code snippets for a [variety of frameworks](./../api/frameworks-feature-support.md). We try to keep them up to date as framework APIs evolve. But it's tricky to keep track of every API change in every framework.
We welcome community contributions to the code snippets. Here's a matrix of the frameworks we have snippets for. Help us add snippets for your favorite framework.
| React | Vue | Angular | Web Components | Svelte | Ember | HTML | Preact |
| ---------------------------------------------------------------------------- | -------------------------------------------------------------------------- | ------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------- | ----- | ---- | ------ |
| [✅](https://github.com/storybookjs/storybook/tree/next/docs/snippets/react) | [✅](https://github.com/storybookjs/storybook/tree/next/docs/snippets/vue) | [✅](https://github.com/storybookjs/storybook/tree/next/docs/snippets/angular) | [✅](https://github.com/storybookjs/storybook/tree/next/docs/snippets/web-components) | [✅](https://github.com/storybookjs/storybook/tree/next/docs/snippets/svelte) | ❌ | ❌ | ❌ |
## Setup
Assuming you've already followed the [local environment guide](./code.md#initial-setup), the first thing you need to do is create a branch on your local Storybook monorepo by running the following command:
```shell
git checkout -b code-snippets-for-framework
```
Before adding your snippets, open the `docs` folder with your editor of choice. Get familiarized with the documentation, including how the snippets are organized and their contents.
### Add your first snippet
Now that you're familiar with how the documentation is structured, it's time to add the code snippets. First, go to the `docs/snippets/` folder and create a new directory for your framework of choice (e.g., `ember`).
Browse the documentation and look for the code snippets you're willing to contribute. For example, on the [setup page](https://github.com/storybookjs/storybook/blob/next/docs/get-started/setup.md), you should see something similar to:
```jsx
// /docs/get-started/setup.md
<!-- prettier-ignore-start -->
<CodeSnippets
paths={[
'react/your-component.js.mdx',
'react/your-component.ts.mdx',
'angular/your-component.ts.mdx',
'vue/your-component.2.js.mdx',
'vue/your-component.3.js.mdx',
'svelte/your-component.js.mdx',
'web-components/your-component.js.mdx',
]}
/>
<!-- prettier-ignore-end -->
```
Create the file `ember/your-component.js.mdx`, similar to the other frameworks, and reference it.
```jsx
// /docs/get-started/setup.md
<!-- prettier-ignore-start -->
<CodeSnippets
paths={[
'react/your-component.js.mdx',
'react/your-component.ts.mdx',
'angular/your-component.ts.mdx',
'vue/your-component.2.js.mdx',
'vue/your-component.3.js.mdx',
'svelte/your-component.js.mdx',
'web-components/your-component.js.mdx',
'ember/your-component.js.mdx', //👈🏼 The code snippet you created.
]}
/>
<!-- prettier-ignore-end -->
```
<div class="aside">
💡 Code snippets are divided into various file extensions, if you're contributing a TypeScript file use <code>.ts.mdx</code>, or if you're adding JavaScript files use <code>.js.mdx</code> .
</div>
Go through the rest of the documentation and repeat the process.
### Preview your work
Before submitting your contribution, we advise you to check your work against the Storybook website. Doing this prevents last-minute issues with the documentation and is also an excellent way for the maintainers to merge faster once you submit the pull request. However, failing to do so will lead one of the maintainers to notify you that your contribution has an issue.
Start by forking [frontpage repo](https://github.com/storybookjs/frontpage) and cloning it locally.
```shell
git clone https://github.com/your-username/frontpage.git
```
Navigate to the `frontpage` directory and install the required dependencies with the following command:
```shell
yarn
```
Next, you'll need a way to get the documentation linked to the website. Execute the following:
```shell
yarn link-monorepo-docs ./path-to-your-local-storybook
```
And run the Storybook website with the following command:
```shell
yarn start:docs-only
```
<div class="aside">
💡 During the start process if there's an issue with the documentation, the process will stop and you'll get a notification.
</div>
Open a browser window to `http://localhost:8000`, click the Docs link, and select your framework from the dropdown.

Go through the documentation and check your work.
## Submit your contribution
Finally, commit, push and open a pull request in the Storybook monorepo. Add a clear description of the work you've done, and one of the maintainers will guide you through the merge process.
| docs/contribute/new-snippets.md | 0 | https://github.com/storybookjs/storybook/commit/5344bd17421860b917b0828a30c3851d7c0eeaff | [
0.00017535740335006267,
0.0001689895725576207,
0.00016183857223950326,
0.0001705680479062721,
0.000004438072210177779
] |
{
"id": 6,
"code_window": [
"import { global } from '@storybook/global';\n",
"import { expect } from '@jest/globals';\n",
"import type { Renderer, ArgsEnhancer, PlayFunctionContext, SBScalarType } from '@storybook/types';\n",
"import { addons, HooksContext } from '../../addons';\n",
"\n",
"import { NO_TARGET_NAME } from '../args';\n",
"import { prepareStory, prepareMeta } from './prepareStory';\n",
"\n",
"jest.mock('@storybook/global', () => ({\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { UNTARGETED } from '../args';\n"
],
"file_path": "code/lib/preview-api/src/modules/store/csf/prepareStory.test.ts",
"type": "replace",
"edit_start_line_idx": 7
} | ---
title: 'Conclusion'
---
Congratulations! You learned the basics. Storybook is the most popular tool for UI component development and documentation. You’ll be able to transfer these skills to thousands of companies that use Storybook to build UIs including GitHub, Airbnb, and Stripe.
If you’d like to learn workflows for building app UIs with Storybook, check out our in-depth guides over at the [tutorials](https://storybook.js.org/tutorials/) page. Continue reading for detailed information on how to use Storybook APIs.
- [How to write stories](../writing-stories/introduction.md)
- [How to document components and design systems](../writing-docs/introduction.md)
- [View example Storybooks from leading companies](https://storybook.js.org/showcase)
| docs/get-started/conclusion.md | 0 | https://github.com/storybookjs/storybook/commit/5344bd17421860b917b0828a30c3851d7c0eeaff | [
0.00020829001732636243,
0.00018708195420913398,
0.00016587389109190553,
0.00018708195420913398,
0.00002120806311722845
] |
{
"id": 7,
"code_window": [
" } as any);\n",
" firstStory.unboundStoryFn(context);\n",
" expect(renderMock).toHaveBeenCalledWith(\n",
" { a: 1 },\n",
" expect.objectContaining({ argsByTarget: { [NO_TARGET_NAME]: { a: 1 }, foo: { b: 2 } } })\n",
" );\n",
" });\n",
"\n",
" it('always sets args, even when all are targetted', () => {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" expect.objectContaining({ argsByTarget: { [UNTARGETED]: { a: 1 }, foo: { b: 2 } } })\n"
],
"file_path": "code/lib/preview-api/src/modules/store/csf/prepareStory.test.ts",
"type": "replace",
"edit_start_line_idx": 597
} | import { dequal as deepEqual } from 'dequal';
import type { Renderer, Args, ArgTypes, InputType, SBType, StoryContext } from '@storybook/types';
import { once } from '@storybook/client-logger';
import isPlainObject from 'lodash/isPlainObject.js';
import { dedent } from 'ts-dedent';
const INCOMPATIBLE = Symbol('incompatible');
const map = (arg: unknown, argType: InputType): any => {
const type = argType.type as SBType;
if (arg === undefined || arg === null || !type) return arg;
if (argType.mapping) {
return arg;
}
switch (type.name) {
case 'string':
return String(arg);
case 'enum':
return arg;
case 'number':
return Number(arg);
case 'boolean':
return arg === 'true';
case 'array':
if (!type.value || !Array.isArray(arg)) return INCOMPATIBLE;
return arg.reduce((acc, item, index) => {
const mapped = map(item, { type: type.value });
if (mapped !== INCOMPATIBLE) acc[index] = mapped;
return acc;
}, new Array(arg.length));
case 'object':
if (typeof arg === 'string' || typeof arg === 'number') return arg;
if (!type.value || typeof arg !== 'object') return INCOMPATIBLE;
return Object.entries(arg).reduce((acc, [key, val]) => {
const mapped = map(val, { type: type.value[key] });
return mapped === INCOMPATIBLE ? acc : Object.assign(acc, { [key]: mapped });
}, {} as Args);
default:
return INCOMPATIBLE;
}
};
export const mapArgsToTypes = (args: Args, argTypes: ArgTypes): Args => {
return Object.entries(args).reduce((acc, [key, value]) => {
if (!argTypes[key]) return acc;
const mapped = map(value, argTypes[key]);
return mapped === INCOMPATIBLE ? acc : Object.assign(acc, { [key]: mapped });
}, {});
};
export const combineArgs = (value: any, update: any): Args => {
if (Array.isArray(value) && Array.isArray(update)) {
return update
.reduce(
(acc, upd, index) => {
acc[index] = combineArgs(value[index], update[index]);
return acc;
},
[...value]
)
.filter((v: any) => v !== undefined);
}
if (!isPlainObject(value) || !isPlainObject(update)) return update;
return Object.keys({ ...value, ...update }).reduce((acc, key) => {
if (key in update) {
const combined = combineArgs(value[key], update[key]);
if (combined !== undefined) acc[key] = combined;
} else {
acc[key] = value[key];
}
return acc;
}, {} as any);
};
export const validateOptions = (args: Args, argTypes: ArgTypes): Args => {
return Object.entries(argTypes).reduce((acc, [key, { options }]) => {
// Don't set args that are not defined in `args` (they can be undefined in there)
// see https://github.com/storybookjs/storybook/issues/15630 and
// https://github.com/storybookjs/storybook/issues/17063
function allowArg() {
if (key in args) {
acc[key] = args[key];
}
return acc;
}
if (!options) return allowArg();
if (!Array.isArray(options)) {
once.error(dedent`
Invalid argType: '${key}.options' should be an array.
More info: https://storybook.js.org/docs/react/api/argtypes
`);
return allowArg();
}
if (options.some((opt) => opt && ['object', 'function'].includes(typeof opt))) {
once.error(dedent`
Invalid argType: '${key}.options' should only contain primitives. Use a 'mapping' for complex values.
More info: https://storybook.js.org/docs/react/writing-stories/args#mapping-to-complex-arg-values
`);
return allowArg();
}
const isArray = Array.isArray(args[key]);
const invalidIndex = isArray && args[key].findIndex((val: any) => !options.includes(val));
const isValidArray = isArray && invalidIndex === -1;
if (args[key] === undefined || options.includes(args[key]) || isValidArray) {
return allowArg();
}
const field = isArray ? `${key}[${invalidIndex}]` : key;
const supportedOptions = options
.map((opt: any) => (typeof opt === 'string' ? `'${opt}'` : String(opt)))
.join(', ');
once.warn(`Received illegal value for '${field}'. Supported options: ${supportedOptions}`);
return acc;
}, {} as Args);
};
// TODO -- copied from router, needs to be in a shared location
export const DEEPLY_EQUAL = Symbol('Deeply equal');
export const deepDiff = (value: any, update: any): any => {
if (typeof value !== typeof update) return update;
if (deepEqual(value, update)) return DEEPLY_EQUAL;
if (Array.isArray(value) && Array.isArray(update)) {
const res = update.reduce((acc, upd, index) => {
const diff = deepDiff(value[index], upd);
if (diff !== DEEPLY_EQUAL) acc[index] = diff;
return acc;
}, new Array(update.length));
if (update.length >= value.length) return res;
return res.concat(new Array(value.length - update.length).fill(undefined));
}
if (isPlainObject(value) && isPlainObject(update)) {
return Object.keys({ ...value, ...update }).reduce((acc, key) => {
const diff = deepDiff(value?.[key], update?.[key]);
return diff === DEEPLY_EQUAL ? acc : Object.assign(acc, { [key]: diff });
}, {});
}
return update;
};
export const NO_TARGET_NAME = '';
export function groupArgsByTarget<TArgs extends Args = Args>({
args,
argTypes,
}: StoryContext<Renderer, TArgs>) {
const groupedArgs: Record<string, Partial<TArgs>> = {};
(Object.entries(args) as [keyof TArgs, any][]).forEach(([name, value]) => {
const { target = NO_TARGET_NAME } = (argTypes[name] || {}) as { target?: string };
groupedArgs[target] = groupedArgs[target] || {};
groupedArgs[target][name] = value;
});
return groupedArgs;
}
export function noTargetArgs<TArgs extends Args = Args>(context: StoryContext<Renderer, TArgs>) {
return groupArgsByTarget(context)[NO_TARGET_NAME];
}
| code/lib/preview-api/src/modules/store/args.ts | 1 | https://github.com/storybookjs/storybook/commit/5344bd17421860b917b0828a30c3851d7c0eeaff | [
0.00543855270370841,
0.0013118170900270343,
0.00016426593356300145,
0.0001775813288986683,
0.001893297303467989
] |
{
"id": 7,
"code_window": [
" } as any);\n",
" firstStory.unboundStoryFn(context);\n",
" expect(renderMock).toHaveBeenCalledWith(\n",
" { a: 1 },\n",
" expect.objectContaining({ argsByTarget: { [NO_TARGET_NAME]: { a: 1 }, foo: { b: 2 } } })\n",
" );\n",
" });\n",
"\n",
" it('always sets args, even when all are targetted', () => {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" expect.objectContaining({ argsByTarget: { [UNTARGETED]: { a: 1 }, foo: { b: 2 } } })\n"
],
"file_path": "code/lib/preview-api/src/modules/store/csf/prepareStory.test.ts",
"type": "replace",
"edit_start_line_idx": 597
} | ```shell
yarn add --dev @storybook/addons @storybook/theming
```
| docs/snippets/common/storybook-theming-packages-install.yarn.js.mdx | 0 | https://github.com/storybookjs/storybook/commit/5344bd17421860b917b0828a30c3851d7c0eeaff | [
0.00017331395065411925,
0.00017331395065411925,
0.00017331395065411925,
0.00017331395065411925,
0
] |
{
"id": 7,
"code_window": [
" } as any);\n",
" firstStory.unboundStoryFn(context);\n",
" expect(renderMock).toHaveBeenCalledWith(\n",
" { a: 1 },\n",
" expect.objectContaining({ argsByTarget: { [NO_TARGET_NAME]: { a: 1 }, foo: { b: 2 } } })\n",
" );\n",
" });\n",
"\n",
" it('always sets args, even when all are targetted', () => {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" expect.objectContaining({ argsByTarget: { [UNTARGETED]: { a: 1 }, foo: { b: 2 } } })\n"
],
"file_path": "code/lib/preview-api/src/modules/store/csf/prepareStory.test.ts",
"type": "replace",
"edit_start_line_idx": 597
} | import type { Renderer } from '@storybook/types';
import type { StoryStore } from '@storybook/preview-api';
declare global {
interface Window {
__STORYBOOK_STORY_STORE__: StoryStore<Renderer>;
}
}
| code/lib/cli/src/window.d.ts | 0 | https://github.com/storybookjs/storybook/commit/5344bd17421860b917b0828a30c3851d7c0eeaff | [
0.0001775313721736893,
0.0001775313721736893,
0.0001775313721736893,
0.0001775313721736893,
0
] |
{
"id": 7,
"code_window": [
" } as any);\n",
" firstStory.unboundStoryFn(context);\n",
" expect(renderMock).toHaveBeenCalledWith(\n",
" { a: 1 },\n",
" expect.objectContaining({ argsByTarget: { [NO_TARGET_NAME]: { a: 1 }, foo: { b: 2 } } })\n",
" );\n",
" });\n",
"\n",
" it('always sets args, even when all are targetted', () => {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" expect.objectContaining({ argsByTarget: { [UNTARGETED]: { a: 1 }, foo: { b: 2 } } })\n"
],
"file_path": "code/lib/preview-api/src/modules/store/csf/prepareStory.test.ts",
"type": "replace",
"edit_start_line_idx": 597
} | /// <reference types="node" />
/* eslint-disable no-console */
import npmLog from 'npmlog';
import prettyTime from 'pretty-hrtime';
import chalk from 'chalk';
// The default is stderr, which can cause some tools (like rush.js) to think
// there are issues with the build: https://github.com/storybookjs/storybook/issues/14621
npmLog.stream = process.stdout;
export const colors = {
pink: chalk.hex('F1618C'),
purple: chalk.hex('B57EE5'),
orange: chalk.hex('F3AD38'),
green: chalk.hex('A2E05E'),
blue: chalk.hex('6DABF5'),
red: chalk.hex('F16161'),
gray: chalk.gray,
};
export const logger = {
verbose: (message: string): void => npmLog.verbose('', message),
info: (message: string): void => npmLog.info('', message),
plain: (message: string): void => console.log(message),
line: (count = 1): void => console.log(`${Array(count - 1).fill('\n')}`),
warn: (message: string): void => npmLog.warn('', message),
error: (message: string): void => npmLog.error('', message),
trace: ({ message, time }: { message: string; time: [number, number] }): void =>
npmLog.info('', `${message} (${colors.purple(prettyTime(time))})`),
setLevel: (level = 'info'): void => {
npmLog.level = level;
},
};
export { npmLog as instance };
const logged = new Set();
export const once = (type: 'verbose' | 'info' | 'warn' | 'error') => (message: string) => {
if (logged.has(message)) return undefined;
logged.add(message);
return logger[type](message);
};
once.clear = () => logged.clear();
once.verbose = once('verbose');
once.info = once('info');
once.warn = once('warn');
once.error = once('error');
export const deprecate = once('warn');
| code/lib/node-logger/src/index.ts | 0 | https://github.com/storybookjs/storybook/commit/5344bd17421860b917b0828a30c3851d7c0eeaff | [
0.00017592060612514615,
0.0001725260663079098,
0.0001654982042964548,
0.00017346368986181915,
0.0000034676634186325828
] |
{
"id": 8,
"code_window": [
"import { includeConditionalArg } from '@storybook/csf';\n",
"\n",
"import { applyHooks } from '../../addons';\n",
"import { combineParameters } from '../parameters';\n",
"import { defaultDecorateStory } from '../decorators';\n",
"import { groupArgsByTarget, NO_TARGET_NAME } from '../args';\n",
"\n",
"// Combine all the metadata about a story (both direct and inherited from the component/global scope)\n",
"// into a \"renderable\" story function, with all decorators applied, parameters passed as context etc\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { groupArgsByTarget, UNTARGETED } from '../args';\n"
],
"file_path": "code/lib/preview-api/src/modules/store/csf/prepareStory.ts",
"type": "replace",
"edit_start_line_idx": 27
} | import { dequal as deepEqual } from 'dequal';
import type { Renderer, Args, ArgTypes, InputType, SBType, StoryContext } from '@storybook/types';
import { once } from '@storybook/client-logger';
import isPlainObject from 'lodash/isPlainObject.js';
import { dedent } from 'ts-dedent';
const INCOMPATIBLE = Symbol('incompatible');
const map = (arg: unknown, argType: InputType): any => {
const type = argType.type as SBType;
if (arg === undefined || arg === null || !type) return arg;
if (argType.mapping) {
return arg;
}
switch (type.name) {
case 'string':
return String(arg);
case 'enum':
return arg;
case 'number':
return Number(arg);
case 'boolean':
return arg === 'true';
case 'array':
if (!type.value || !Array.isArray(arg)) return INCOMPATIBLE;
return arg.reduce((acc, item, index) => {
const mapped = map(item, { type: type.value });
if (mapped !== INCOMPATIBLE) acc[index] = mapped;
return acc;
}, new Array(arg.length));
case 'object':
if (typeof arg === 'string' || typeof arg === 'number') return arg;
if (!type.value || typeof arg !== 'object') return INCOMPATIBLE;
return Object.entries(arg).reduce((acc, [key, val]) => {
const mapped = map(val, { type: type.value[key] });
return mapped === INCOMPATIBLE ? acc : Object.assign(acc, { [key]: mapped });
}, {} as Args);
default:
return INCOMPATIBLE;
}
};
export const mapArgsToTypes = (args: Args, argTypes: ArgTypes): Args => {
return Object.entries(args).reduce((acc, [key, value]) => {
if (!argTypes[key]) return acc;
const mapped = map(value, argTypes[key]);
return mapped === INCOMPATIBLE ? acc : Object.assign(acc, { [key]: mapped });
}, {});
};
export const combineArgs = (value: any, update: any): Args => {
if (Array.isArray(value) && Array.isArray(update)) {
return update
.reduce(
(acc, upd, index) => {
acc[index] = combineArgs(value[index], update[index]);
return acc;
},
[...value]
)
.filter((v: any) => v !== undefined);
}
if (!isPlainObject(value) || !isPlainObject(update)) return update;
return Object.keys({ ...value, ...update }).reduce((acc, key) => {
if (key in update) {
const combined = combineArgs(value[key], update[key]);
if (combined !== undefined) acc[key] = combined;
} else {
acc[key] = value[key];
}
return acc;
}, {} as any);
};
export const validateOptions = (args: Args, argTypes: ArgTypes): Args => {
return Object.entries(argTypes).reduce((acc, [key, { options }]) => {
// Don't set args that are not defined in `args` (they can be undefined in there)
// see https://github.com/storybookjs/storybook/issues/15630 and
// https://github.com/storybookjs/storybook/issues/17063
function allowArg() {
if (key in args) {
acc[key] = args[key];
}
return acc;
}
if (!options) return allowArg();
if (!Array.isArray(options)) {
once.error(dedent`
Invalid argType: '${key}.options' should be an array.
More info: https://storybook.js.org/docs/react/api/argtypes
`);
return allowArg();
}
if (options.some((opt) => opt && ['object', 'function'].includes(typeof opt))) {
once.error(dedent`
Invalid argType: '${key}.options' should only contain primitives. Use a 'mapping' for complex values.
More info: https://storybook.js.org/docs/react/writing-stories/args#mapping-to-complex-arg-values
`);
return allowArg();
}
const isArray = Array.isArray(args[key]);
const invalidIndex = isArray && args[key].findIndex((val: any) => !options.includes(val));
const isValidArray = isArray && invalidIndex === -1;
if (args[key] === undefined || options.includes(args[key]) || isValidArray) {
return allowArg();
}
const field = isArray ? `${key}[${invalidIndex}]` : key;
const supportedOptions = options
.map((opt: any) => (typeof opt === 'string' ? `'${opt}'` : String(opt)))
.join(', ');
once.warn(`Received illegal value for '${field}'. Supported options: ${supportedOptions}`);
return acc;
}, {} as Args);
};
// TODO -- copied from router, needs to be in a shared location
export const DEEPLY_EQUAL = Symbol('Deeply equal');
export const deepDiff = (value: any, update: any): any => {
if (typeof value !== typeof update) return update;
if (deepEqual(value, update)) return DEEPLY_EQUAL;
if (Array.isArray(value) && Array.isArray(update)) {
const res = update.reduce((acc, upd, index) => {
const diff = deepDiff(value[index], upd);
if (diff !== DEEPLY_EQUAL) acc[index] = diff;
return acc;
}, new Array(update.length));
if (update.length >= value.length) return res;
return res.concat(new Array(value.length - update.length).fill(undefined));
}
if (isPlainObject(value) && isPlainObject(update)) {
return Object.keys({ ...value, ...update }).reduce((acc, key) => {
const diff = deepDiff(value?.[key], update?.[key]);
return diff === DEEPLY_EQUAL ? acc : Object.assign(acc, { [key]: diff });
}, {});
}
return update;
};
export const NO_TARGET_NAME = '';
export function groupArgsByTarget<TArgs extends Args = Args>({
args,
argTypes,
}: StoryContext<Renderer, TArgs>) {
const groupedArgs: Record<string, Partial<TArgs>> = {};
(Object.entries(args) as [keyof TArgs, any][]).forEach(([name, value]) => {
const { target = NO_TARGET_NAME } = (argTypes[name] || {}) as { target?: string };
groupedArgs[target] = groupedArgs[target] || {};
groupedArgs[target][name] = value;
});
return groupedArgs;
}
export function noTargetArgs<TArgs extends Args = Args>(context: StoryContext<Renderer, TArgs>) {
return groupArgsByTarget(context)[NO_TARGET_NAME];
}
| code/lib/preview-api/src/modules/store/args.ts | 1 | https://github.com/storybookjs/storybook/commit/5344bd17421860b917b0828a30c3851d7c0eeaff | [
0.013097908347845078,
0.0013189896708354354,
0.0001669668999966234,
0.0001853225548984483,
0.0031123943626880646
] |
{
"id": 8,
"code_window": [
"import { includeConditionalArg } from '@storybook/csf';\n",
"\n",
"import { applyHooks } from '../../addons';\n",
"import { combineParameters } from '../parameters';\n",
"import { defaultDecorateStory } from '../decorators';\n",
"import { groupArgsByTarget, NO_TARGET_NAME } from '../args';\n",
"\n",
"// Combine all the metadata about a story (both direct and inherited from the component/global scope)\n",
"// into a \"renderable\" story function, with all decorators applied, parameters passed as context etc\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { groupArgsByTarget, UNTARGETED } from '../args';\n"
],
"file_path": "code/lib/preview-api/src/modules/store/csf/prepareStory.ts",
"type": "replace",
"edit_start_line_idx": 27
} | ```ts
// Button.stories.ts
import { html } from 'lit-html';
import type { Meta, StoryObj } from '@storybook/web-components';
import { action } from '@storybook/addon-actions';
const meta: Meta = {
title: 'Button',
component: 'custom-button',
};
export default meta;
type Story = StoryObj;
export const Text: Story = {
render: () => html`<custom-button label="Hello" @click=${action('clicked')}></custom-button>`,
};
```
| docs/snippets/web-components/button-story-click-handler.ts.mdx | 0 | https://github.com/storybookjs/storybook/commit/5344bd17421860b917b0828a30c3851d7c0eeaff | [
0.0002375920012127608,
0.0001929226127685979,
0.00016903108917176723,
0.0001721447624731809,
0.00003161159111186862
] |
{
"id": 8,
"code_window": [
"import { includeConditionalArg } from '@storybook/csf';\n",
"\n",
"import { applyHooks } from '../../addons';\n",
"import { combineParameters } from '../parameters';\n",
"import { defaultDecorateStory } from '../decorators';\n",
"import { groupArgsByTarget, NO_TARGET_NAME } from '../args';\n",
"\n",
"// Combine all the metadata about a story (both direct and inherited from the component/global scope)\n",
"// into a \"renderable\" story function, with all decorators applied, parameters passed as context etc\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { groupArgsByTarget, UNTARGETED } from '../args';\n"
],
"file_path": "code/lib/preview-api/src/modules/store/csf/prepareStory.ts",
"type": "replace",
"edit_start_line_idx": 27
} | import { transparentize } from 'polished';
import type { CSSObject, Theme } from '@storybook/theming';
export const headerCommon = ({ theme }: { theme: Theme }): CSSObject => ({
margin: '20px 0 8px',
padding: 0,
cursor: 'text',
position: 'relative',
color: theme.color.defaultText,
'&:first-of-type': {
marginTop: 0,
paddingTop: 0,
},
'&:hover a.anchor': {
textDecoration: 'none',
},
'& tt, & code': {
fontSize: 'inherit',
},
});
export const codeCommon = ({ theme }: { theme: Theme }): CSSObject => ({
lineHeight: 1,
margin: '0 2px',
padding: '3px 5px',
whiteSpace: 'nowrap',
borderRadius: 3,
fontSize: theme.typography.size.s2 - 1,
border:
theme.base === 'light'
? `1px solid ${theme.color.mediumlight}`
: `1px solid ${theme.color.darker}`,
color:
theme.base === 'light'
? transparentize(0.1, theme.color.defaultText)
: transparentize(0.3, theme.color.defaultText),
backgroundColor: theme.base === 'light' ? theme.color.lighter : theme.color.border,
});
export const withReset = ({ theme }: { theme: Theme }): CSSObject => ({
fontFamily: theme.typography.fonts.base,
fontSize: theme.typography.size.s3,
margin: 0,
WebkitFontSmoothing: 'antialiased',
MozOsxFontSmoothing: 'grayscale',
WebkitTapHighlightColor: 'rgba(0, 0, 0, 0)',
WebkitOverflowScrolling: 'touch',
});
export const withMargin: CSSObject = {
margin: '16px 0',
};
| code/ui/components/src/typography/lib/common.tsx | 0 | https://github.com/storybookjs/storybook/commit/5344bd17421860b917b0828a30c3851d7c0eeaff | [
0.0001763719046721235,
0.00017083193233702332,
0.00016731195501051843,
0.000170752260601148,
0.000003057177082155249
] |
{
"id": 8,
"code_window": [
"import { includeConditionalArg } from '@storybook/csf';\n",
"\n",
"import { applyHooks } from '../../addons';\n",
"import { combineParameters } from '../parameters';\n",
"import { defaultDecorateStory } from '../decorators';\n",
"import { groupArgsByTarget, NO_TARGET_NAME } from '../args';\n",
"\n",
"// Combine all the metadata about a story (both direct and inherited from the component/global scope)\n",
"// into a \"renderable\" story function, with all decorators applied, parameters passed as context etc\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { groupArgsByTarget, UNTARGETED } from '../args';\n"
],
"file_path": "code/lib/preview-api/src/modules/store/csf/prepareStory.ts",
"type": "replace",
"edit_start_line_idx": 27
} | import { global } from '@storybook/global';
/**
* This file includes polyfills needed by Angular and is loaded before the app.
* You can add your own extra polyfills to this file.
*
* This file is divided into 2 sections:
* 1. Browser polyfills. These are applied before loading ZoneJS and are sorted by browsers.
* 2. Application imports. Files imported after ZoneJS that should be loaded before your main
* file.
*
* The current setup is for so-called "evergreen" browsers; the last versions of browsers that
* automatically update themselves. This includes Safari >= 10, Chrome >= 55 (including Opera),
* Edge >= 13 on the desktop, and iOS 10 and Chrome on mobile.
*
* Learn more in https://angular.io/docs/ts/latest/guide/browser-support.html
*/
/** *************************************************************************************************
* BROWSER POLYFILLS
*/
/** IE9, IE10 and IE11 requires all of the following polyfills. * */
// import 'core-js/es6/symbol';
// import 'core-js/es6/object';
// import 'core-js/es6/function';
// import 'core-js/es6/parse-int';
// import 'core-js/es6/parse-float';
// import 'core-js/es6/number';
// import 'core-js/es6/math';
// import 'core-js/es6/string';
// import 'core-js/es6/date';
// import 'core-js/es6/array';
// import 'core-js/es6/regexp';
// import 'core-js/es6/map';
// import 'core-js/es6/weak-map';
// import 'core-js/es6/set';
/** IE10 and IE11 requires the following for NgClass support on SVG elements */
// import 'classlist.js'; // Run `npm install --save classlist.js`.
/** Evergreen browsers require these. * */
import 'core-js/es/reflect';
import 'core-js/proposals/reflect-metadata';
/**
* Required to support Web Animations `@angular/animation`.
* Needed for: All but Chrome, Firefox and Opera. http://caniuse.com/#feat=web-animation
* */
// import 'web-animations-js'; // Run `npm install --save web-animations-js`.
/** *************************************************************************************************
* Zone JS is required by Angular itself.
*/
import 'zone.js/dist/zone'; // Included with Angular CLI.
/** *************************************************************************************************
* APPLICATION IMPORTS
*/
/**
* Date, currency, decimal and percent pipes.
* Needed for: All but Chrome, Firefox, Edge, IE11 and Safari 10
*/
// import 'intl'; // Run `npm install --save intl`.
/**
* Need to import at least one locale-data with intl.
*/
// import 'intl/locale-data/jsonp/en';
global.STORYBOOK_ENV = 'angular';
| code/frameworks/angular/src/client/globals.ts | 0 | https://github.com/storybookjs/storybook/commit/5344bd17421860b917b0828a30c3851d7c0eeaff | [
0.00019284985319245607,
0.0001698284177109599,
0.0001613055355846882,
0.0001654552761465311,
0.000009613474503566977
] |
{
"id": 9,
"code_window": [
" ...context,\n",
" allArgs: context.args,\n",
" argsByTarget,\n",
" args: argsByTarget[NO_TARGET_NAME] || {},\n",
" };\n",
" }\n",
"\n",
" const mappedArgs = Object.entries(finalContext.args).reduce((acc, [key, val]) => {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" args: argsByTarget[UNTARGETED] || {},\n"
],
"file_path": "code/lib/preview-api/src/modules/store/csf/prepareStory.ts",
"type": "replace",
"edit_start_line_idx": 102
} | import { global } from '@storybook/global';
import type {
Renderer,
Args,
ArgsStoryFn,
LegacyStoryFn,
Parameters,
PlayFunction,
PlayFunctionContext,
StepLabel,
NormalizedComponentAnnotations,
NormalizedProjectAnnotations,
NormalizedStoryAnnotations,
PreparedStory,
StoryContext,
StoryContextForEnhancers,
StoryContextForLoaders,
StrictArgTypes,
PreparedMeta,
ModuleExport,
} from '@storybook/types';
import { includeConditionalArg } from '@storybook/csf';
import { applyHooks } from '../../addons';
import { combineParameters } from '../parameters';
import { defaultDecorateStory } from '../decorators';
import { groupArgsByTarget, NO_TARGET_NAME } from '../args';
// Combine all the metadata about a story (both direct and inherited from the component/global scope)
// into a "renderable" story function, with all decorators applied, parameters passed as context etc
//
// Note that this story function is *stateless* in the sense that it does not track args or globals
// Instead, it is expected these are tracked separately (if necessary) and are passed into each invocation.
export function prepareStory<TRenderer extends Renderer>(
storyAnnotations: NormalizedStoryAnnotations<TRenderer>,
componentAnnotations: NormalizedComponentAnnotations<TRenderer>,
projectAnnotations: NormalizedProjectAnnotations<TRenderer>
): PreparedStory<TRenderer> {
// NOTE: in the current implementation we are doing everything once, up front, rather than doing
// anything at render time. The assumption is that as we don't load all the stories at once, this
// will have a limited cost. If this proves misguided, we can refactor it.
const { moduleExport, id, name } = storyAnnotations || {};
const partialAnnotations = preparePartialAnnotations(
storyAnnotations,
componentAnnotations,
projectAnnotations
);
const loaders = [
...(projectAnnotations.loaders || []),
...(componentAnnotations.loaders || []),
...(storyAnnotations?.loaders || []),
];
const applyLoaders = async (context: StoryContextForLoaders<TRenderer>) => {
const loadResults = await Promise.all(loaders.map((loader) => loader(context)));
const loaded = Object.assign({}, ...loadResults);
return { ...context, loaded };
};
const undecoratedStoryFn: LegacyStoryFn<TRenderer> = (context: StoryContext<TRenderer>) => {
const { passArgsFirst: renderTimePassArgsFirst = true } = context.parameters;
return renderTimePassArgsFirst
? (render as ArgsStoryFn<TRenderer>)(context.args, context)
: (render as LegacyStoryFn<TRenderer>)(context);
};
// Currently it is only possible to set these globally
const { applyDecorators = defaultDecorateStory, runStep } = projectAnnotations;
const decorators = [
...(storyAnnotations?.decorators || []),
...(componentAnnotations.decorators || []),
...(projectAnnotations.decorators || []),
];
// The render function on annotations *has* to be an `ArgsStoryFn`, so when we normalize
// CSFv1/2, we use a new field called `userStoryFn` so we know that it can be a LegacyStoryFn
const render =
storyAnnotations?.userStoryFn ||
storyAnnotations?.render ||
componentAnnotations.render ||
projectAnnotations.render;
if (!render) throw new Error(`No render function available for storyId '${id}'`);
const decoratedStoryFn = applyHooks<TRenderer>(applyDecorators)(undecoratedStoryFn, decorators);
const unboundStoryFn = (context: StoryContext<TRenderer>) => decoratedStoryFn(context);
// prepareContext is invoked at StoryRender.render()
// the context is prepared before invoking the render function, instead of here directly
// to ensure args don't loose there special properties set by the renderer
// eg. reactive proxies set by frameworks like SolidJS or Vue
const prepareContext = (context: StoryContext<TRenderer>) => {
let finalContext: StoryContext<TRenderer> = context;
if (global.FEATURES?.argTypeTargetsV7) {
const argsByTarget = groupArgsByTarget(context);
finalContext = {
...context,
allArgs: context.args,
argsByTarget,
args: argsByTarget[NO_TARGET_NAME] || {},
};
}
const mappedArgs = Object.entries(finalContext.args).reduce((acc, [key, val]) => {
const mapping = finalContext.argTypes[key]?.mapping;
acc[key] = mapping && val in mapping ? mapping[val] : val;
return acc;
}, {} as Args);
const includedArgs = Object.entries(mappedArgs).reduce((acc, [key, val]) => {
const argType = finalContext.argTypes[key] || {};
if (includeConditionalArg(argType, mappedArgs, finalContext.globals)) acc[key] = val;
return acc;
}, {} as Args);
return { ...finalContext, args: includedArgs };
};
const play = storyAnnotations?.play || componentAnnotations.play;
const playFunction =
play &&
(async (storyContext: StoryContext<TRenderer>) => {
const playFunctionContext: PlayFunctionContext<TRenderer> = {
...storyContext,
// eslint-disable-next-line @typescript-eslint/no-shadow
step: (label: StepLabel, play: PlayFunction<TRenderer>) =>
// TODO: We know runStep is defined, we need a proper normalized annotations type
runStep!(label, play, playFunctionContext),
};
return play(playFunctionContext);
});
return {
...partialAnnotations,
moduleExport,
id,
name,
story: name,
originalStoryFn: render,
undecoratedStoryFn,
unboundStoryFn,
applyLoaders,
playFunction,
prepareContext,
};
}
export function prepareMeta<TRenderer extends Renderer>(
componentAnnotations: NormalizedComponentAnnotations<TRenderer>,
projectAnnotations: NormalizedProjectAnnotations<TRenderer>,
moduleExport: ModuleExport
): PreparedMeta<TRenderer> {
return {
...preparePartialAnnotations(undefined, componentAnnotations, projectAnnotations),
moduleExport,
};
}
function preparePartialAnnotations<TRenderer extends Renderer>(
storyAnnotations: NormalizedStoryAnnotations<TRenderer> | undefined,
componentAnnotations: NormalizedComponentAnnotations<TRenderer>,
projectAnnotations: NormalizedProjectAnnotations<TRenderer>
): Omit<StoryContextForEnhancers<TRenderer>, 'name' | 'story'> {
// NOTE: in the current implementation we are doing everything once, up front, rather than doing
// anything at render time. The assumption is that as we don't load all the stories at once, this
// will have a limited cost. If this proves misguided, we can refactor it.
const id = storyAnnotations?.id || componentAnnotations.id;
const tags = [...(storyAnnotations?.tags || componentAnnotations.tags || []), 'story'];
const parameters: Parameters = combineParameters(
projectAnnotations.parameters,
componentAnnotations.parameters,
storyAnnotations?.parameters
);
// Currently it is only possible to set these globally
const { argTypesEnhancers = [], argsEnhancers = [] } = projectAnnotations;
// The render function on annotations *has* to be an `ArgsStoryFn`, so when we normalize
// CSFv1/2, we use a new field called `userStoryFn` so we know that it can be a LegacyStoryFn
const render =
storyAnnotations?.userStoryFn ||
storyAnnotations?.render ||
componentAnnotations.render ||
projectAnnotations.render;
if (!render) throw new Error(`No render function available for id '${id}'`);
const passedArgTypes: StrictArgTypes = combineParameters(
projectAnnotations.argTypes,
componentAnnotations.argTypes,
storyAnnotations?.argTypes
) as StrictArgTypes;
const { passArgsFirst = true } = parameters;
// eslint-disable-next-line no-underscore-dangle
parameters.__isArgsStory = passArgsFirst && render.length > 0;
// Pull out args[X] into initialArgs for argTypes enhancers
const passedArgs: Args = {
...projectAnnotations.args,
...componentAnnotations.args,
...storyAnnotations?.args,
} as Args;
const contextForEnhancers: StoryContextForEnhancers<TRenderer> = {
componentId: componentAnnotations.id,
title: componentAnnotations.title,
kind: componentAnnotations.title, // Back compat
id: storyAnnotations?.id || componentAnnotations.id,
// if there's no story name, we create a fake one since enhancers expect a name
name: storyAnnotations?.name || '__meta',
story: storyAnnotations?.name || '__meta', // Back compat
component: componentAnnotations.component,
subcomponents: componentAnnotations.subcomponents,
tags,
parameters,
initialArgs: passedArgs,
argTypes: passedArgTypes,
};
contextForEnhancers.argTypes = argTypesEnhancers.reduce(
(accumulatedArgTypes, enhancer) =>
enhancer({ ...contextForEnhancers, argTypes: accumulatedArgTypes }),
contextForEnhancers.argTypes
);
const initialArgsBeforeEnhancers = { ...passedArgs };
contextForEnhancers.initialArgs = argsEnhancers.reduce(
(accumulatedArgs: Args, enhancer) => ({
...accumulatedArgs,
...enhancer({
...contextForEnhancers,
initialArgs: accumulatedArgs,
}),
}),
initialArgsBeforeEnhancers
);
// Add some of our metadata into parameters as we used to do this in 6.x and users may be relying on it
if (!global.FEATURES?.breakingChangesV7) {
contextForEnhancers.parameters = {
...contextForEnhancers.parameters,
__id: id,
globals: projectAnnotations.globals,
globalTypes: projectAnnotations.globalTypes,
args: contextForEnhancers.initialArgs,
argTypes: contextForEnhancers.argTypes,
};
}
const { name, story, ...withoutStoryIdentifiers } = contextForEnhancers;
return withoutStoryIdentifiers;
}
| code/lib/preview-api/src/modules/store/csf/prepareStory.ts | 1 | https://github.com/storybookjs/storybook/commit/5344bd17421860b917b0828a30c3851d7c0eeaff | [
0.9989674091339111,
0.07452622801065445,
0.00016567188140470535,
0.00017320309416390955,
0.26139435172080994
] |
{
"id": 9,
"code_window": [
" ...context,\n",
" allArgs: context.args,\n",
" argsByTarget,\n",
" args: argsByTarget[NO_TARGET_NAME] || {},\n",
" };\n",
" }\n",
"\n",
" const mappedArgs = Object.entries(finalContext.args).reduce((acc, [key, val]) => {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" args: argsByTarget[UNTARGETED] || {},\n"
],
"file_path": "code/lib/preview-api/src/modules/store/csf/prepareStory.ts",
"type": "replace",
"edit_start_line_idx": 102
} | {
"name": "@storybook/preview",
"version": "7.0.0-beta.34",
"description": "",
"keywords": [
"storybook"
],
"homepage": "https://github.com/storybookjs/storybook/tree/main/code/lib/preview",
"bugs": {
"url": "https://github.com/storybookjs/storybook/issues"
},
"repository": {
"type": "git",
"url": "https://github.com/storybookjs/storybook.git",
"directory": "code/lib/preview"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/storybook"
},
"license": "MIT",
"sideEffects": false,
"exports": {
".": {
"import": "./dist/runtime.mjs",
"require": "./dist/runtime.js",
"types": "./dist/runtime.d.ts"
},
"./globals": {
"import": "./dist/globals.mjs",
"require": "./dist/globals.js",
"types": "./dist/globals.d.ts"
},
"./package.json": "./package.json"
},
"main": "dist/runtime.js",
"module": "dist/runtime.mjs",
"types": "dist/runtime.d.ts",
"typesVersions": {
"*": {
"*": [
"dist/runtime.d.ts"
],
"globals": [
"dist/globals.d.ts"
]
}
},
"files": [
"dist/**/*",
"README.md",
"*.js",
"*.d.ts"
],
"scripts": {
"check": "../../../scripts/node_modules/.bin/tsc --noEmit",
"prep": "../../../scripts/prepare/bundle.ts"
},
"devDependencies": {
"@storybook/channel-postmessage": "7.0.0-beta.34",
"@storybook/channel-websocket": "7.0.0-beta.34",
"@storybook/channels": "7.0.0-beta.34",
"@storybook/client-logger": "7.0.0-beta.34",
"@storybook/core-events": "7.0.0-beta.34",
"@storybook/preview-api": "7.0.0-beta.34",
"typescript": "~4.9.3"
},
"publishConfig": {
"access": "public"
},
"bundler": {
"entries": [
"./src/runtime.ts",
"./src/globals.ts"
]
},
"gitHead": "b8c17b23e92257c5a09b592dc6b557ba7b94ccea"
}
| code/lib/preview/package.json | 0 | https://github.com/storybookjs/storybook/commit/5344bd17421860b917b0828a30c3851d7c0eeaff | [
0.0001777429279172793,
0.00017492074402980506,
0.00017209847283083946,
0.00017486562137492,
0.000001732293526401918
] |
{
"id": 9,
"code_window": [
" ...context,\n",
" allArgs: context.args,\n",
" argsByTarget,\n",
" args: argsByTarget[NO_TARGET_NAME] || {},\n",
" };\n",
" }\n",
"\n",
" const mappedArgs = Object.entries(finalContext.args).reduce((acc, [key, val]) => {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" args: argsByTarget[UNTARGETED] || {},\n"
],
"file_path": "code/lib/preview-api/src/modules/store/csf/prepareStory.ts",
"type": "replace",
"edit_start_line_idx": 102
} | ```js
// Button.js|jsx
import React from 'react';
import PropTypes from 'prop-types';
export function Button({ isDisabled, content }) {
return (
<button type="button" disabled={isDisabled}>
{content}
</button>
);
}
Button.propTypes = {
/**
Checks if the button should be disabled
*/
isDisabled: PropTypes.bool.isRequired,
/**
The display content of the button
*/
content: PropTypes.string.isRequired,
};
```
| docs/snippets/react/button-component-with-proptypes.js.mdx | 0 | https://github.com/storybookjs/storybook/commit/5344bd17421860b917b0828a30c3851d7c0eeaff | [
0.00017473766638431698,
0.00017263107292819768,
0.00017101150297094136,
0.00017214409308508039,
0.0000015596892808389384
] |
{
"id": 9,
"code_window": [
" ...context,\n",
" allArgs: context.args,\n",
" argsByTarget,\n",
" args: argsByTarget[NO_TARGET_NAME] || {},\n",
" };\n",
" }\n",
"\n",
" const mappedArgs = Object.entries(finalContext.args).reduce((acc, [key, val]) => {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" args: argsByTarget[UNTARGETED] || {},\n"
],
"file_path": "code/lib/preview-api/src/modules/store/csf/prepareStory.ts",
"type": "replace",
"edit_start_line_idx": 102
} | // Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`react component properties 9575-ts-camel-case 1`] = `
Object {
"rows": Array [
Object {
"defaultValue": Object {
"detail": undefined,
"summary": "'primary'",
},
"description": "",
"name": "color",
"required": false,
"sbType": Object {
"name": "string",
},
"type": Object {
"detail": undefined,
"summary": "string",
},
},
],
}
`;
| code/renderers/react/template/stories/docgen-components/9575-ts-camel-case/properties.snapshot | 0 | https://github.com/storybookjs/storybook/commit/5344bd17421860b917b0828a30c3851d7c0eeaff | [
0.00017260118329431862,
0.0001713023375486955,
0.000169897815794684,
0.0001714080135570839,
0.0000011061719078497845
] |
{
"id": 0,
"code_window": [
"\t\treturn paths.posix.basename(resource.path);\n",
"\t}\n",
"\n",
"\textname(resource: URI): string {\n",
"\t\tconst resourceExt = paths.posix.extname(resource.path);\n",
"\t\tconst queryStringLocation = resourceExt.indexOf('?');\n",
"\t\treturn queryStringLocation !== -1 ? resourceExt.substr(0, queryStringLocation) : resourceExt;\n",
"\t}\n",
"\n",
"\tdirname(resource: URI): URI {\n",
"\t\tif (resource.path.length === 0) {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\treturn paths.posix.extname(resource.path);\n"
],
"file_path": "src/vs/base/common/resources.ts",
"type": "replace",
"edit_start_line_idx": 197
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { Registry } from 'vs/platform/registry/common/platform';
import { Extensions as WorkbenchExtensions, IWorkbenchContributionsRegistry, IWorkbenchContribution } from 'vs/workbench/common/contributions';
import { LifecyclePhase, ILifecycleService, StartupKind } from 'vs/workbench/services/lifecycle/common/lifecycle';
import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';
import { IWorkspaceContextService, WorkbenchState } from 'vs/platform/workspace/common/workspace';
import { IActivityBarService } from 'vs/workbench/services/activityBar/browser/activityBarService';
import { IEditorService } from 'vs/workbench/services/editor/common/editorService';
import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding';
import { IWorkbenchThemeService } from 'vs/workbench/services/themes/common/workbenchThemeService';
import { IWorkbenchEnvironmentService } from 'vs/workbench/services/environment/common/environmentService';
import { language } from 'vs/base/common/platform';
import { Disposable } from 'vs/base/common/lifecycle';
import ErrorTelemetry from 'vs/platform/telemetry/browser/errorTelemetry';
import { configurationTelemetry } from 'vs/platform/telemetry/common/telemetryUtils';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { IViewletService } from 'vs/workbench/services/viewlet/browser/viewlet';
import { ITextFileService, ITextFileSaveEvent, ITextFileResolveEvent } from 'vs/workbench/services/textfile/common/textfiles';
import { extname, basename, isEqual, isEqualOrParent } from 'vs/base/common/resources';
import { URI } from 'vs/base/common/uri';
import { Schemas } from 'vs/base/common/network';
import { guessMimeTypes } from 'vs/base/common/mime';
import { hash } from 'vs/base/common/hash';
type TelemetryData = {
mimeType: string;
ext: string;
path: number;
reason?: number;
allowlistedjson?: string;
};
type FileTelemetryDataFragment = {
mimeType: { classification: 'SystemMetaData', purpose: 'FeatureInsight' };
ext: { classification: 'SystemMetaData', purpose: 'FeatureInsight' };
path: { classification: 'SystemMetaData', purpose: 'FeatureInsight' };
reason?: { classification: 'SystemMetaData', purpose: 'FeatureInsight', isMeasurement: true };
allowlistedjson?: { classification: 'SystemMetaData', purpose: 'FeatureInsight' };
};
export class TelemetryContribution extends Disposable implements IWorkbenchContribution {
private static ALLOWLIST_JSON = ['package.json', 'package-lock.json', 'tsconfig.json', 'jsconfig.json', 'bower.json', '.eslintrc.json', 'tslint.json', 'composer.json'];
private static ALLOWLIST_WORKSPACE_JSON = ['settings.json', 'extensions.json', 'tasks.json', 'launch.json'];
constructor(
@ITelemetryService private readonly telemetryService: ITelemetryService,
@IWorkspaceContextService private readonly contextService: IWorkspaceContextService,
@IActivityBarService activityBarService: IActivityBarService,
@ILifecycleService lifecycleService: ILifecycleService,
@IEditorService editorService: IEditorService,
@IKeybindingService keybindingsService: IKeybindingService,
@IWorkbenchThemeService themeService: IWorkbenchThemeService,
@IWorkbenchEnvironmentService private readonly environmentService: IWorkbenchEnvironmentService,
@IConfigurationService configurationService: IConfigurationService,
@IViewletService viewletService: IViewletService,
@ITextFileService textFileService: ITextFileService
) {
super();
const { filesToOpenOrCreate, filesToDiff } = environmentService.configuration;
const activeViewlet = viewletService.getActiveViewlet();
type WindowSizeFragment = {
innerHeight: { classification: 'SystemMetaData', purpose: 'FeatureInsight', isMeasurement: true };
innerWidth: { classification: 'SystemMetaData', purpose: 'FeatureInsight', isMeasurement: true };
outerHeight: { classification: 'SystemMetaData', purpose: 'FeatureInsight', isMeasurement: true };
outerWidth: { classification: 'SystemMetaData', purpose: 'FeatureInsight', isMeasurement: true };
};
type WorkspaceLoadClassification = {
userAgent: { classification: 'SystemMetaData', purpose: 'FeatureInsight' };
emptyWorkbench: { classification: 'SystemMetaData', purpose: 'FeatureInsight', isMeasurement: true };
windowSize: WindowSizeFragment;
'workbench.filesToOpenOrCreate': { classification: 'SystemMetaData', purpose: 'FeatureInsight', isMeasurement: true };
'workbench.filesToDiff': { classification: 'SystemMetaData', purpose: 'FeatureInsight', isMeasurement: true };
customKeybindingsCount: { classification: 'SystemMetaData', purpose: 'FeatureInsight', isMeasurement: true };
theme: { classification: 'SystemMetaData', purpose: 'FeatureInsight' };
language: { classification: 'SystemMetaData', purpose: 'BusinessInsight' };
pinnedViewlets: { classification: 'SystemMetaData', purpose: 'FeatureInsight' };
restoredViewlet?: { classification: 'SystemMetaData', purpose: 'FeatureInsight' };
restoredEditors: { classification: 'SystemMetaData', purpose: 'FeatureInsight', isMeasurement: true };
startupKind: { classification: 'SystemMetaData', purpose: 'FeatureInsight', isMeasurement: true };
};
type WorkspaceLoadEvent = {
userAgent: string;
windowSize: { innerHeight: number, innerWidth: number, outerHeight: number, outerWidth: number };
emptyWorkbench: boolean;
'workbench.filesToOpenOrCreate': number;
'workbench.filesToDiff': number;
customKeybindingsCount: number;
theme: string;
language: string;
pinnedViewlets: string[];
restoredViewlet?: string;
restoredEditors: number;
startupKind: StartupKind;
};
telemetryService.publicLog2<WorkspaceLoadEvent, WorkspaceLoadClassification>('workspaceLoad', {
userAgent: navigator.userAgent,
windowSize: { innerHeight: window.innerHeight, innerWidth: window.innerWidth, outerHeight: window.outerHeight, outerWidth: window.outerWidth },
emptyWorkbench: contextService.getWorkbenchState() === WorkbenchState.EMPTY,
'workbench.filesToOpenOrCreate': filesToOpenOrCreate && filesToOpenOrCreate.length || 0,
'workbench.filesToDiff': filesToDiff && filesToDiff.length || 0,
customKeybindingsCount: keybindingsService.customKeybindingsCount(),
theme: themeService.getColorTheme().id,
language,
pinnedViewlets: activityBarService.getPinnedViewContainerIds(),
restoredViewlet: activeViewlet ? activeViewlet.getId() : undefined,
restoredEditors: editorService.visibleEditors.length,
startupKind: lifecycleService.startupKind
});
// Error Telemetry
this._register(new ErrorTelemetry(telemetryService));
// Configuration Telemetry
this._register(configurationTelemetry(telemetryService, configurationService));
// Files Telemetry
this._register(textFileService.files.onDidResolve(e => this.onTextFileModelResolved(e)));
this._register(textFileService.files.onDidSave(e => this.onTextFileModelSaved(e)));
// Lifecycle
this._register(lifecycleService.onDidShutdown(() => this.dispose()));
}
private onTextFileModelResolved(e: ITextFileResolveEvent): void {
const settingsType = this.getTypeIfSettings(e.model.resource);
if (settingsType) {
type SettingsReadClassification = {
settingsType: { classification: 'SystemMetaData', purpose: 'FeatureInsight' };
};
this.telemetryService.publicLog2<{ settingsType: string }, SettingsReadClassification>('settingsRead', { settingsType }); // Do not log read to user settings.json and .vscode folder as a fileGet event as it ruins our JSON usage data
} else {
type FileGetClassification = {} & FileTelemetryDataFragment;
this.telemetryService.publicLog2<TelemetryData, FileGetClassification>('fileGet', this.getTelemetryData(e.model.resource, e.reason));
}
}
private onTextFileModelSaved(e: ITextFileSaveEvent): void {
const settingsType = this.getTypeIfSettings(e.model.resource);
if (settingsType) {
type SettingsWrittenClassification = {
settingsType: { classification: 'SystemMetaData', purpose: 'FeatureInsight' };
};
this.telemetryService.publicLog2<{ settingsType: string }, SettingsWrittenClassification>('settingsWritten', { settingsType }); // Do not log write to user settings.json and .vscode folder as a filePUT event as it ruins our JSON usage data
} else {
type FilePutClassfication = {} & FileTelemetryDataFragment;
this.telemetryService.publicLog2<TelemetryData, FilePutClassfication>('filePUT', this.getTelemetryData(e.model.resource, e.reason));
}
}
private getTypeIfSettings(resource: URI): string {
if (extname(resource) !== '.json') {
return '';
}
// Check for global settings file
if (isEqual(resource, this.environmentService.settingsResource)) {
return 'global-settings';
}
// Check for keybindings file
if (isEqual(resource, this.environmentService.keybindingsResource)) {
return 'keybindings';
}
// Check for snippets
if (isEqualOrParent(resource, this.environmentService.snippetsHome)) {
return 'snippets';
}
// Check for workspace settings file
const folders = this.contextService.getWorkspace().folders;
for (const folder of folders) {
if (isEqualOrParent(resource, folder.toResource('.vscode'))) {
const filename = basename(resource);
if (TelemetryContribution.ALLOWLIST_WORKSPACE_JSON.indexOf(filename) > -1) {
return `.vscode/${filename}`;
}
}
}
return '';
}
private getTelemetryData(resource: URI, reason?: number): TelemetryData {
const ext = extname(resource);
const fileName = basename(resource);
const path = resource.scheme === Schemas.file ? resource.fsPath : resource.path;
const telemetryData = {
mimeType: guessMimeTypes(resource).join(', '),
ext,
path: hash(path),
reason,
allowlistedjson: undefined as string | undefined
};
if (ext === '.json' && TelemetryContribution.ALLOWLIST_JSON.indexOf(fileName) > -1) {
telemetryData['allowlistedjson'] = fileName;
}
return telemetryData;
}
}
Registry.as<IWorkbenchContributionsRegistry>(WorkbenchExtensions.Workbench).registerWorkbenchContribution(TelemetryContribution, LifecyclePhase.Restored);
| src/vs/workbench/contrib/telemetry/browser/telemetry.contribution.ts | 1 | https://github.com/microsoft/vscode/commit/c4fe803132ea8cd9aa903a83d7c5786ac77897b3 | [
0.9973998069763184,
0.09079771488904953,
0.00016631162725389004,
0.00017456564819440246,
0.2861883044242859
] |
{
"id": 0,
"code_window": [
"\t\treturn paths.posix.basename(resource.path);\n",
"\t}\n",
"\n",
"\textname(resource: URI): string {\n",
"\t\tconst resourceExt = paths.posix.extname(resource.path);\n",
"\t\tconst queryStringLocation = resourceExt.indexOf('?');\n",
"\t\treturn queryStringLocation !== -1 ? resourceExt.substr(0, queryStringLocation) : resourceExt;\n",
"\t}\n",
"\n",
"\tdirname(resource: URI): URI {\n",
"\t\tif (resource.path.length === 0) {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\treturn paths.posix.extname(resource.path);\n"
],
"file_path": "src/vs/base/common/resources.ts",
"type": "replace",
"edit_start_line_idx": 197
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
/**
* @param {string} name
* @param {string[]} exclude
*/
function createModuleDescription(name, exclude) {
let excludes = ['vs/css', 'vs/nls'];
if (Array.isArray(exclude) && exclude.length > 0) {
excludes = excludes.concat(exclude);
}
return {
name: name,
include: [],
exclude: excludes
};
}
/**
* @param {string} name
*/
function createEditorWorkerModuleDescription(name) {
return createModuleDescription(name, ['vs/base/common/worker/simpleWorker', 'vs/editor/common/services/editorSimpleWorker']);
}
exports.createModuleDescription = createModuleDescription;
exports.createEditorWorkerModuleDescription = createEditorWorkerModuleDescription;
| src/vs/base/buildfile.js | 0 | https://github.com/microsoft/vscode/commit/c4fe803132ea8cd9aa903a83d7c5786ac77897b3 | [
0.00017583559383638203,
0.00017254872363992035,
0.0001696066465228796,
0.00017237631254829466,
0.0000024219227725552628
] |
{
"id": 0,
"code_window": [
"\t\treturn paths.posix.basename(resource.path);\n",
"\t}\n",
"\n",
"\textname(resource: URI): string {\n",
"\t\tconst resourceExt = paths.posix.extname(resource.path);\n",
"\t\tconst queryStringLocation = resourceExt.indexOf('?');\n",
"\t\treturn queryStringLocation !== -1 ? resourceExt.substr(0, queryStringLocation) : resourceExt;\n",
"\t}\n",
"\n",
"\tdirname(resource: URI): URI {\n",
"\t\tif (resource.path.length === 0) {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\treturn paths.posix.extname(resource.path);\n"
],
"file_path": "src/vs/base/common/resources.ts",
"type": "replace",
"edit_start_line_idx": 197
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { MinimapCharRenderer } from 'vs/editor/browser/viewParts/minimap/minimapCharRenderer';
import { allCharCodes } from 'vs/editor/browser/viewParts/minimap/minimapCharSheet';
import { prebakedMiniMaps } from 'vs/editor/browser/viewParts/minimap/minimapPreBaked';
import { Constants } from './minimapCharSheet';
import { toUint8 } from 'vs/base/common/uint';
/**
* Creates character renderers. It takes a 'scale' that determines how large
* characters should be drawn. Using this, it draws data into a canvas and
* then downsamples the characters as necessary for the current display.
* This makes rendering more efficient, rather than drawing a full (tiny)
* font, or downsampling in real-time.
*/
export class MinimapCharRendererFactory {
private static lastCreated?: MinimapCharRenderer;
private static lastFontFamily?: string;
/**
* Creates a new character renderer factory with the given scale.
*/
public static create(scale: number, fontFamily: string) {
// renderers are immutable. By default we'll 'create' a new minimap
// character renderer whenever we switch editors, no need to do extra work.
if (this.lastCreated && scale === this.lastCreated.scale && fontFamily === this.lastFontFamily) {
return this.lastCreated;
}
let factory: MinimapCharRenderer;
if (prebakedMiniMaps[scale]) {
factory = new MinimapCharRenderer(prebakedMiniMaps[scale](), scale);
} else {
factory = MinimapCharRendererFactory.createFromSampleData(
MinimapCharRendererFactory.createSampleData(fontFamily).data,
scale
);
}
this.lastFontFamily = fontFamily;
this.lastCreated = factory;
return factory;
}
/**
* Creates the font sample data, writing to a canvas.
*/
public static createSampleData(fontFamily: string): ImageData {
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d')!;
canvas.style.height = `${Constants.SAMPLED_CHAR_HEIGHT}px`;
canvas.height = Constants.SAMPLED_CHAR_HEIGHT;
canvas.width = Constants.CHAR_COUNT * Constants.SAMPLED_CHAR_WIDTH;
canvas.style.width = Constants.CHAR_COUNT * Constants.SAMPLED_CHAR_WIDTH + 'px';
ctx.fillStyle = '#ffffff';
ctx.font = `bold ${Constants.SAMPLED_CHAR_HEIGHT}px ${fontFamily}`;
ctx.textBaseline = 'middle';
let x = 0;
for (const code of allCharCodes) {
ctx.fillText(String.fromCharCode(code), x, Constants.SAMPLED_CHAR_HEIGHT / 2);
x += Constants.SAMPLED_CHAR_WIDTH;
}
return ctx.getImageData(0, 0, Constants.CHAR_COUNT * Constants.SAMPLED_CHAR_WIDTH, Constants.SAMPLED_CHAR_HEIGHT);
}
/**
* Creates a character renderer from the canvas sample data.
*/
public static createFromSampleData(source: Uint8ClampedArray, scale: number): MinimapCharRenderer {
const expectedLength =
Constants.SAMPLED_CHAR_HEIGHT * Constants.SAMPLED_CHAR_WIDTH * Constants.RGBA_CHANNELS_CNT * Constants.CHAR_COUNT;
if (source.length !== expectedLength) {
throw new Error('Unexpected source in MinimapCharRenderer');
}
let charData = MinimapCharRendererFactory._downsample(source, scale);
return new MinimapCharRenderer(charData, scale);
}
private static _downsampleChar(
source: Uint8ClampedArray,
sourceOffset: number,
dest: Uint8ClampedArray,
destOffset: number,
scale: number
): number {
const width = Constants.BASE_CHAR_WIDTH * scale;
const height = Constants.BASE_CHAR_HEIGHT * scale;
let targetIndex = destOffset;
let brightest = 0;
// This is essentially an ad-hoc rescaling algorithm. Standard approaches
// like bicubic interpolation are awesome for scaling between image sizes,
// but don't work so well when scaling to very small pixel values, we end
// up with blurry, indistinct forms.
//
// The approach taken here is simply mapping each source pixel to the target
// pixels, and taking the weighted values for all pixels in each, and then
// averaging them out. Finally we apply an intensity boost in _downsample,
// since when scaling to the smallest pixel sizes there's more black space
// which causes characters to be much less distinct.
for (let y = 0; y < height; y++) {
// 1. For this destination pixel, get the source pixels we're sampling
// from (x1, y1) to the next pixel (x2, y2)
const sourceY1 = (y / height) * Constants.SAMPLED_CHAR_HEIGHT;
const sourceY2 = ((y + 1) / height) * Constants.SAMPLED_CHAR_HEIGHT;
for (let x = 0; x < width; x++) {
const sourceX1 = (x / width) * Constants.SAMPLED_CHAR_WIDTH;
const sourceX2 = ((x + 1) / width) * Constants.SAMPLED_CHAR_WIDTH;
// 2. Sample all of them, summing them up and weighting them. Similar
// to bilinear interpolation.
let value = 0;
let samples = 0;
for (let sy = sourceY1; sy < sourceY2; sy++) {
const sourceRow = sourceOffset + Math.floor(sy) * Constants.RGBA_SAMPLED_ROW_WIDTH;
const yBalance = 1 - (sy - Math.floor(sy));
for (let sx = sourceX1; sx < sourceX2; sx++) {
const xBalance = 1 - (sx - Math.floor(sx));
const sourceIndex = sourceRow + Math.floor(sx) * Constants.RGBA_CHANNELS_CNT;
const weight = xBalance * yBalance;
samples += weight;
value += ((source[sourceIndex] * source[sourceIndex + 3]) / 255) * weight;
}
}
const final = value / samples;
brightest = Math.max(brightest, final);
dest[targetIndex++] = toUint8(final);
}
}
return brightest;
}
private static _downsample(data: Uint8ClampedArray, scale: number): Uint8ClampedArray {
const pixelsPerCharacter = Constants.BASE_CHAR_HEIGHT * scale * Constants.BASE_CHAR_WIDTH * scale;
const resultLen = pixelsPerCharacter * Constants.CHAR_COUNT;
const result = new Uint8ClampedArray(resultLen);
let resultOffset = 0;
let sourceOffset = 0;
let brightest = 0;
for (let charIndex = 0; charIndex < Constants.CHAR_COUNT; charIndex++) {
brightest = Math.max(brightest, this._downsampleChar(data, sourceOffset, result, resultOffset, scale));
resultOffset += pixelsPerCharacter;
sourceOffset += Constants.SAMPLED_CHAR_WIDTH * Constants.RGBA_CHANNELS_CNT;
}
if (brightest > 0) {
const adjust = 255 / brightest;
for (let i = 0; i < resultLen; i++) {
result[i] *= adjust;
}
}
return result;
}
}
| src/vs/editor/browser/viewParts/minimap/minimapCharRendererFactory.ts | 0 | https://github.com/microsoft/vscode/commit/c4fe803132ea8cd9aa903a83d7c5786ac77897b3 | [
0.00017670435772743076,
0.00017262189066968858,
0.00016629829769954085,
0.0001733688113745302,
0.0000023714919734629802
] |
{
"id": 0,
"code_window": [
"\t\treturn paths.posix.basename(resource.path);\n",
"\t}\n",
"\n",
"\textname(resource: URI): string {\n",
"\t\tconst resourceExt = paths.posix.extname(resource.path);\n",
"\t\tconst queryStringLocation = resourceExt.indexOf('?');\n",
"\t\treturn queryStringLocation !== -1 ? resourceExt.substr(0, queryStringLocation) : resourceExt;\n",
"\t}\n",
"\n",
"\tdirname(resource: URI): URI {\n",
"\t\tif (resource.path.length === 0) {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\treturn paths.posix.extname(resource.path);\n"
],
"file_path": "src/vs/base/common/resources.ts",
"type": "replace",
"edit_start_line_idx": 197
} | <svg width="14px" height="14px" viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg">
<rect fill="#CC6633" x="0" y="0" width="100" height="100" rx="35" ry="35"/>
<text x="50" y="75" font-size="75" text-anchor="middle" style="font-family: Menlo, Monaco, Consolas, "Droid Sans Mono", "Inconsolata", "Courier New", monospace, "Droid Sans Fallback";" fill="white">
R
</text>
</svg> | extensions/git/resources/icons/light/status-renamed.svg | 0 | https://github.com/microsoft/vscode/commit/c4fe803132ea8cd9aa903a83d7c5786ac77897b3 | [
0.00017466304416302592,
0.00017466304416302592,
0.00017466304416302592,
0.00017466304416302592,
0
] |
{
"id": 1,
"code_window": [
"import { toSlashes } from 'vs/base/common/extpath';\n",
"import { posix, win32 } from 'vs/base/common/path';\n",
"import { isWindows } from 'vs/base/common/platform';\n",
"import { addTrailingPathSeparator, basename, dirname, distinctParents, extname, extUri, extUriIgnorePathCase, hasTrailingPathSeparator, isAbsolutePath, joinPath, normalizePath, relativePath, removeTrailingPathSeparator, resolvePath } from 'vs/base/common/resources';\n",
"import { URI } from 'vs/base/common/uri';\n",
"\n",
"\n",
"suite('Resources', () => {\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { addTrailingPathSeparator, basename, dirname, distinctParents, extUri, extUriIgnorePathCase, hasTrailingPathSeparator, isAbsolutePath, joinPath, normalizePath, relativePath, removeTrailingPathSeparator, resolvePath } from 'vs/base/common/resources';\n"
],
"file_path": "src/vs/base/test/common/resources.test.ts",
"type": "replace",
"edit_start_line_idx": 8
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as assert from 'assert';
import { toSlashes } from 'vs/base/common/extpath';
import { posix, win32 } from 'vs/base/common/path';
import { isWindows } from 'vs/base/common/platform';
import { addTrailingPathSeparator, basename, dirname, distinctParents, extname, extUri, extUriIgnorePathCase, hasTrailingPathSeparator, isAbsolutePath, joinPath, normalizePath, relativePath, removeTrailingPathSeparator, resolvePath } from 'vs/base/common/resources';
import { URI } from 'vs/base/common/uri';
suite('Resources', () => {
test('distinctParents', () => {
// Basic
let resources = [
URI.file('/some/folderA/file.txt'),
URI.file('/some/folderB/file.txt'),
URI.file('/some/folderC/file.txt')
];
let distinct = distinctParents(resources, r => r);
assert.strictEqual(distinct.length, 3);
assert.strictEqual(distinct[0].toString(), resources[0].toString());
assert.strictEqual(distinct[1].toString(), resources[1].toString());
assert.strictEqual(distinct[2].toString(), resources[2].toString());
// Parent / Child
resources = [
URI.file('/some/folderA'),
URI.file('/some/folderA/file.txt'),
URI.file('/some/folderA/child/file.txt'),
URI.file('/some/folderA2/file.txt'),
URI.file('/some/file.txt')
];
distinct = distinctParents(resources, r => r);
assert.strictEqual(distinct.length, 3);
assert.strictEqual(distinct[0].toString(), resources[0].toString());
assert.strictEqual(distinct[1].toString(), resources[3].toString());
assert.strictEqual(distinct[2].toString(), resources[4].toString());
});
test('dirname', () => {
if (isWindows) {
assert.strictEqual(dirname(URI.file('c:\\some\\file\\test.txt')).toString(), 'file:///c%3A/some/file');
assert.strictEqual(dirname(URI.file('c:\\some\\file')).toString(), 'file:///c%3A/some');
assert.strictEqual(dirname(URI.file('c:\\some\\file\\')).toString(), 'file:///c%3A/some');
assert.strictEqual(dirname(URI.file('c:\\some')).toString(), 'file:///c%3A/');
assert.strictEqual(dirname(URI.file('C:\\some')).toString(), 'file:///c%3A/');
assert.strictEqual(dirname(URI.file('c:\\')).toString(), 'file:///c%3A/');
} else {
assert.strictEqual(dirname(URI.file('/some/file/test.txt')).toString(), 'file:///some/file');
assert.strictEqual(dirname(URI.file('/some/file/')).toString(), 'file:///some');
assert.strictEqual(dirname(URI.file('/some/file')).toString(), 'file:///some');
}
assert.strictEqual(dirname(URI.parse('foo://a/some/file/test.txt')).toString(), 'foo://a/some/file');
assert.strictEqual(dirname(URI.parse('foo://a/some/file/')).toString(), 'foo://a/some');
assert.strictEqual(dirname(URI.parse('foo://a/some/file')).toString(), 'foo://a/some');
assert.strictEqual(dirname(URI.parse('foo://a/some')).toString(), 'foo://a/');
assert.strictEqual(dirname(URI.parse('foo://a/')).toString(), 'foo://a/');
assert.strictEqual(dirname(URI.parse('foo://a')).toString(), 'foo://a');
// does not explode (https://github.com/microsoft/vscode/issues/41987)
dirname(URI.from({ scheme: 'file', authority: '/users/someone/portal.h' }));
assert.strictEqual(dirname(URI.parse('foo://a/b/c?q')).toString(), 'foo://a/b?q');
});
test('basename', () => {
if (isWindows) {
assert.strictEqual(basename(URI.file('c:\\some\\file\\test.txt')), 'test.txt');
assert.strictEqual(basename(URI.file('c:\\some\\file')), 'file');
assert.strictEqual(basename(URI.file('c:\\some\\file\\')), 'file');
assert.strictEqual(basename(URI.file('C:\\some\\file\\')), 'file');
} else {
assert.strictEqual(basename(URI.file('/some/file/test.txt')), 'test.txt');
assert.strictEqual(basename(URI.file('/some/file/')), 'file');
assert.strictEqual(basename(URI.file('/some/file')), 'file');
assert.strictEqual(basename(URI.file('/some')), 'some');
}
assert.strictEqual(basename(URI.parse('foo://a/some/file/test.txt')), 'test.txt');
assert.strictEqual(basename(URI.parse('foo://a/some/file/')), 'file');
assert.strictEqual(basename(URI.parse('foo://a/some/file')), 'file');
assert.strictEqual(basename(URI.parse('foo://a/some')), 'some');
assert.strictEqual(basename(URI.parse('foo://a/')), '');
assert.strictEqual(basename(URI.parse('foo://a')), '');
});
test('joinPath', () => {
if (isWindows) {
assert.strictEqual(joinPath(URI.file('c:\\foo\\bar'), '/file.js').toString(), 'file:///c%3A/foo/bar/file.js');
assert.strictEqual(joinPath(URI.file('c:\\foo\\bar\\'), 'file.js').toString(), 'file:///c%3A/foo/bar/file.js');
assert.strictEqual(joinPath(URI.file('c:\\foo\\bar\\'), '/file.js').toString(), 'file:///c%3A/foo/bar/file.js');
assert.strictEqual(joinPath(URI.file('c:\\'), '/file.js').toString(), 'file:///c%3A/file.js');
assert.strictEqual(joinPath(URI.file('c:\\'), 'bar/file.js').toString(), 'file:///c%3A/bar/file.js');
assert.strictEqual(joinPath(URI.file('c:\\foo'), './file.js').toString(), 'file:///c%3A/foo/file.js');
assert.strictEqual(joinPath(URI.file('c:\\foo'), '/./file.js').toString(), 'file:///c%3A/foo/file.js');
assert.strictEqual(joinPath(URI.file('C:\\foo'), '../file.js').toString(), 'file:///c%3A/file.js');
assert.strictEqual(joinPath(URI.file('C:\\foo\\.'), '../file.js').toString(), 'file:///c%3A/file.js');
} else {
assert.strictEqual(joinPath(URI.file('/foo/bar'), '/file.js').toString(), 'file:///foo/bar/file.js');
assert.strictEqual(joinPath(URI.file('/foo/bar'), 'file.js').toString(), 'file:///foo/bar/file.js');
assert.strictEqual(joinPath(URI.file('/foo/bar/'), '/file.js').toString(), 'file:///foo/bar/file.js');
assert.strictEqual(joinPath(URI.file('/'), '/file.js').toString(), 'file:///file.js');
assert.strictEqual(joinPath(URI.file('/foo/bar'), './file.js').toString(), 'file:///foo/bar/file.js');
assert.strictEqual(joinPath(URI.file('/foo/bar'), '/./file.js').toString(), 'file:///foo/bar/file.js');
assert.strictEqual(joinPath(URI.file('/foo/bar'), '../file.js').toString(), 'file:///foo/file.js');
}
assert.strictEqual(joinPath(URI.parse('foo://a/foo/bar')).toString(), 'foo://a/foo/bar');
assert.strictEqual(joinPath(URI.parse('foo://a/foo/bar'), '/file.js').toString(), 'foo://a/foo/bar/file.js');
assert.strictEqual(joinPath(URI.parse('foo://a/foo/bar'), 'file.js').toString(), 'foo://a/foo/bar/file.js');
assert.strictEqual(joinPath(URI.parse('foo://a/foo/bar/'), '/file.js').toString(), 'foo://a/foo/bar/file.js');
assert.strictEqual(joinPath(URI.parse('foo://a/'), '/file.js').toString(), 'foo://a/file.js');
assert.strictEqual(joinPath(URI.parse('foo://a/foo/bar/'), './file.js').toString(), 'foo://a/foo/bar/file.js');
assert.strictEqual(joinPath(URI.parse('foo://a/foo/bar/'), '/./file.js').toString(), 'foo://a/foo/bar/file.js');
assert.strictEqual(joinPath(URI.parse('foo://a/foo/bar/'), '../file.js').toString(), 'foo://a/foo/file.js');
assert.strictEqual(
joinPath(URI.from({ scheme: 'myScheme', authority: 'authority', path: '/path', query: 'query', fragment: 'fragment' }), '/file.js').toString(),
'myScheme://authority/path/file.js?query#fragment');
});
test('normalizePath', () => {
if (isWindows) {
assert.strictEqual(normalizePath(URI.file('c:\\foo\\.\\bar')).toString(), 'file:///c%3A/foo/bar');
assert.strictEqual(normalizePath(URI.file('c:\\foo\\.')).toString(), 'file:///c%3A/foo');
assert.strictEqual(normalizePath(URI.file('c:\\foo\\.\\')).toString(), 'file:///c%3A/foo/');
assert.strictEqual(normalizePath(URI.file('c:\\foo\\..')).toString(), 'file:///c%3A/');
assert.strictEqual(normalizePath(URI.file('c:\\foo\\..\\bar')).toString(), 'file:///c%3A/bar');
assert.strictEqual(normalizePath(URI.file('c:\\foo\\..\\..\\bar')).toString(), 'file:///c%3A/bar');
assert.strictEqual(normalizePath(URI.file('c:\\foo\\foo\\..\\..\\bar')).toString(), 'file:///c%3A/bar');
assert.strictEqual(normalizePath(URI.file('C:\\foo\\foo\\.\\..\\..\\bar')).toString(), 'file:///c%3A/bar');
assert.strictEqual(normalizePath(URI.file('C:\\foo\\foo\\.\\..\\some\\..\\bar')).toString(), 'file:///c%3A/foo/bar');
} else {
assert.strictEqual(normalizePath(URI.file('/foo/./bar')).toString(), 'file:///foo/bar');
assert.strictEqual(normalizePath(URI.file('/foo/.')).toString(), 'file:///foo');
assert.strictEqual(normalizePath(URI.file('/foo/./')).toString(), 'file:///foo/');
assert.strictEqual(normalizePath(URI.file('/foo/..')).toString(), 'file:///');
assert.strictEqual(normalizePath(URI.file('/foo/../bar')).toString(), 'file:///bar');
assert.strictEqual(normalizePath(URI.file('/foo/../../bar')).toString(), 'file:///bar');
assert.strictEqual(normalizePath(URI.file('/foo/foo/../../bar')).toString(), 'file:///bar');
assert.strictEqual(normalizePath(URI.file('/foo/foo/./../../bar')).toString(), 'file:///bar');
assert.strictEqual(normalizePath(URI.file('/foo/foo/./../some/../bar')).toString(), 'file:///foo/bar');
assert.strictEqual(normalizePath(URI.file('/f')).toString(), 'file:///f');
}
assert.strictEqual(normalizePath(URI.parse('foo://a/foo/./bar')).toString(), 'foo://a/foo/bar');
assert.strictEqual(normalizePath(URI.parse('foo://a/foo/.')).toString(), 'foo://a/foo');
assert.strictEqual(normalizePath(URI.parse('foo://a/foo/./')).toString(), 'foo://a/foo/');
assert.strictEqual(normalizePath(URI.parse('foo://a/foo/..')).toString(), 'foo://a/');
assert.strictEqual(normalizePath(URI.parse('foo://a/foo/../bar')).toString(), 'foo://a/bar');
assert.strictEqual(normalizePath(URI.parse('foo://a/foo/../../bar')).toString(), 'foo://a/bar');
assert.strictEqual(normalizePath(URI.parse('foo://a/foo/foo/../../bar')).toString(), 'foo://a/bar');
assert.strictEqual(normalizePath(URI.parse('foo://a/foo/foo/./../../bar')).toString(), 'foo://a/bar');
assert.strictEqual(normalizePath(URI.parse('foo://a/foo/foo/./../some/../bar')).toString(), 'foo://a/foo/bar');
assert.strictEqual(normalizePath(URI.parse('foo://a')).toString(), 'foo://a');
assert.strictEqual(normalizePath(URI.parse('foo://a/')).toString(), 'foo://a/');
assert.strictEqual(normalizePath(URI.parse('foo://a/foo/./bar?q=1')).toString(), URI.parse('foo://a/foo/bar?q%3D1').toString());
});
test('isAbsolute', () => {
if (isWindows) {
assert.strictEqual(isAbsolutePath(URI.file('c:\\foo\\')), true);
assert.strictEqual(isAbsolutePath(URI.file('C:\\foo\\')), true);
assert.strictEqual(isAbsolutePath(URI.file('bar')), true); // URI normalizes all file URIs to be absolute
} else {
assert.strictEqual(isAbsolutePath(URI.file('/foo/bar')), true);
assert.strictEqual(isAbsolutePath(URI.file('bar')), true); // URI normalizes all file URIs to be absolute
}
assert.strictEqual(isAbsolutePath(URI.parse('foo:foo')), false);
assert.strictEqual(isAbsolutePath(URI.parse('foo://a/foo/.')), true);
});
function assertTrailingSeparator(u1: URI, expected: boolean) {
assert.strictEqual(hasTrailingPathSeparator(u1), expected, u1.toString());
}
function assertRemoveTrailingSeparator(u1: URI, expected: URI) {
assertEqualURI(removeTrailingPathSeparator(u1), expected, u1.toString());
}
function assertAddTrailingSeparator(u1: URI, expected: URI) {
assertEqualURI(addTrailingPathSeparator(u1), expected, u1.toString());
}
test('trailingPathSeparator', () => {
assertTrailingSeparator(URI.parse('foo://a/foo'), false);
assertTrailingSeparator(URI.parse('foo://a/foo/'), true);
assertTrailingSeparator(URI.parse('foo://a/'), false);
assertTrailingSeparator(URI.parse('foo://a'), false);
assertRemoveTrailingSeparator(URI.parse('foo://a/foo'), URI.parse('foo://a/foo'));
assertRemoveTrailingSeparator(URI.parse('foo://a/foo/'), URI.parse('foo://a/foo'));
assertRemoveTrailingSeparator(URI.parse('foo://a/'), URI.parse('foo://a/'));
assertRemoveTrailingSeparator(URI.parse('foo://a'), URI.parse('foo://a'));
assertAddTrailingSeparator(URI.parse('foo://a/foo'), URI.parse('foo://a/foo/'));
assertAddTrailingSeparator(URI.parse('foo://a/foo/'), URI.parse('foo://a/foo/'));
assertAddTrailingSeparator(URI.parse('foo://a/'), URI.parse('foo://a/'));
assertAddTrailingSeparator(URI.parse('foo://a'), URI.parse('foo://a/'));
if (isWindows) {
assertTrailingSeparator(URI.file('c:\\a\\foo'), false);
assertTrailingSeparator(URI.file('c:\\a\\foo\\'), true);
assertTrailingSeparator(URI.file('c:\\'), false);
assertTrailingSeparator(URI.file('\\\\server\\share\\some\\'), true);
assertTrailingSeparator(URI.file('\\\\server\\share\\'), false);
assertRemoveTrailingSeparator(URI.file('c:\\a\\foo'), URI.file('c:\\a\\foo'));
assertRemoveTrailingSeparator(URI.file('c:\\a\\foo\\'), URI.file('c:\\a\\foo'));
assertRemoveTrailingSeparator(URI.file('c:\\'), URI.file('c:\\'));
assertRemoveTrailingSeparator(URI.file('\\\\server\\share\\some\\'), URI.file('\\\\server\\share\\some'));
assertRemoveTrailingSeparator(URI.file('\\\\server\\share\\'), URI.file('\\\\server\\share\\'));
assertAddTrailingSeparator(URI.file('c:\\a\\foo'), URI.file('c:\\a\\foo\\'));
assertAddTrailingSeparator(URI.file('c:\\a\\foo\\'), URI.file('c:\\a\\foo\\'));
assertAddTrailingSeparator(URI.file('c:\\'), URI.file('c:\\'));
assertAddTrailingSeparator(URI.file('\\\\server\\share\\some'), URI.file('\\\\server\\share\\some\\'));
assertAddTrailingSeparator(URI.file('\\\\server\\share\\some\\'), URI.file('\\\\server\\share\\some\\'));
} else {
assertTrailingSeparator(URI.file('/foo/bar'), false);
assertTrailingSeparator(URI.file('/foo/bar/'), true);
assertTrailingSeparator(URI.file('/'), false);
assertRemoveTrailingSeparator(URI.file('/foo/bar'), URI.file('/foo/bar'));
assertRemoveTrailingSeparator(URI.file('/foo/bar/'), URI.file('/foo/bar'));
assertRemoveTrailingSeparator(URI.file('/'), URI.file('/'));
assertAddTrailingSeparator(URI.file('/foo/bar'), URI.file('/foo/bar/'));
assertAddTrailingSeparator(URI.file('/foo/bar/'), URI.file('/foo/bar/'));
assertAddTrailingSeparator(URI.file('/'), URI.file('/'));
}
});
function assertEqualURI(actual: URI, expected: URI, message?: string, ignoreCase?: boolean) {
let util = ignoreCase ? extUriIgnorePathCase : extUri;
if (!util.isEqual(expected, actual)) {
assert.strictEqual(actual.toString(), expected.toString(), message);
}
}
function assertRelativePath(u1: URI, u2: URI, expectedPath: string | undefined, ignoreJoin?: boolean, ignoreCase?: boolean) {
let util = ignoreCase ? extUriIgnorePathCase : extUri;
assert.strictEqual(util.relativePath(u1, u2), expectedPath, `from ${u1.toString()} to ${u2.toString()}`);
if (expectedPath !== undefined && !ignoreJoin) {
assertEqualURI(removeTrailingPathSeparator(joinPath(u1, expectedPath)), removeTrailingPathSeparator(u2), 'joinPath on relativePath should be equal', ignoreCase);
}
}
test('relativePath', () => {
assertRelativePath(URI.parse('foo://a/foo'), URI.parse('foo://a/foo/bar'), 'bar');
assertRelativePath(URI.parse('foo://a/foo'), URI.parse('foo://a/foo/bar/'), 'bar');
assertRelativePath(URI.parse('foo://a/foo'), URI.parse('foo://a/foo/bar/goo'), 'bar/goo');
assertRelativePath(URI.parse('foo://a/'), URI.parse('foo://a/foo/bar/goo'), 'foo/bar/goo');
assertRelativePath(URI.parse('foo://a/foo/xoo'), URI.parse('foo://a/foo/bar'), '../bar');
assertRelativePath(URI.parse('foo://a/foo/xoo/yoo'), URI.parse('foo://a'), '../../..', true);
assertRelativePath(URI.parse('foo://a/foo'), URI.parse('foo://a/foo/'), '');
assertRelativePath(URI.parse('foo://a/foo/'), URI.parse('foo://a/foo'), '');
assertRelativePath(URI.parse('foo://a/foo/'), URI.parse('foo://a/foo/'), '');
assertRelativePath(URI.parse('foo://a/foo'), URI.parse('foo://a/foo'), '');
assertRelativePath(URI.parse('foo://a'), URI.parse('foo://a'), '', true);
assertRelativePath(URI.parse('foo://a/'), URI.parse('foo://a/'), '');
assertRelativePath(URI.parse('foo://a/'), URI.parse('foo://a'), '', true);
assertRelativePath(URI.parse('foo://a/foo?q'), URI.parse('foo://a/foo/bar#h'), 'bar', true);
assertRelativePath(URI.parse('foo://'), URI.parse('foo://a/b'), undefined);
assertRelativePath(URI.parse('foo://a2/b'), URI.parse('foo://a/b'), undefined);
assertRelativePath(URI.parse('goo://a/b'), URI.parse('foo://a/b'), undefined);
assertRelativePath(URI.parse('foo://a/foo'), URI.parse('foo://A/FOO/bar/goo'), 'bar/goo', false, true);
assertRelativePath(URI.parse('foo://a/foo'), URI.parse('foo://A/FOO/BAR/GOO'), 'BAR/GOO', false, true);
assertRelativePath(URI.parse('foo://a/foo/xoo'), URI.parse('foo://A/FOO/BAR/GOO'), '../BAR/GOO', false, true);
assertRelativePath(URI.parse('foo:///c:/a/foo'), URI.parse('foo:///C:/a/foo/xoo/'), 'xoo', false, true);
if (isWindows) {
assertRelativePath(URI.file('c:\\foo\\bar'), URI.file('c:\\foo\\bar'), '');
assertRelativePath(URI.file('c:\\foo\\bar\\huu'), URI.file('c:\\foo\\bar'), '..');
assertRelativePath(URI.file('c:\\foo\\bar\\a1\\a2'), URI.file('c:\\foo\\bar'), '../..');
assertRelativePath(URI.file('c:\\foo\\bar\\'), URI.file('c:\\foo\\bar\\a1\\a2'), 'a1/a2');
assertRelativePath(URI.file('c:\\foo\\bar\\'), URI.file('c:\\foo\\bar\\a1\\a2\\'), 'a1/a2');
assertRelativePath(URI.file('c:\\'), URI.file('c:\\foo\\bar'), 'foo/bar');
assertRelativePath(URI.file('\\\\server\\share\\some\\'), URI.file('\\\\server\\share\\some\\path'), 'path');
assertRelativePath(URI.file('\\\\server\\share\\some\\'), URI.file('\\\\server\\share2\\some\\path'), '../../share2/some/path', true); // ignore joinPath assert: path.join is not root aware
} else {
assertRelativePath(URI.file('/a/foo'), URI.file('/a/foo/bar'), 'bar');
assertRelativePath(URI.file('/a/foo'), URI.file('/a/foo/bar/'), 'bar');
assertRelativePath(URI.file('/a/foo'), URI.file('/a/foo/bar/goo'), 'bar/goo');
assertRelativePath(URI.file('/a/'), URI.file('/a/foo/bar/goo'), 'foo/bar/goo');
assertRelativePath(URI.file('/'), URI.file('/a/foo/bar/goo'), 'a/foo/bar/goo');
assertRelativePath(URI.file('/a/foo/xoo'), URI.file('/a/foo/bar'), '../bar');
assertRelativePath(URI.file('/a/foo/xoo/yoo'), URI.file('/a'), '../../..');
assertRelativePath(URI.file('/a/foo'), URI.file('/a/foo/'), '');
assertRelativePath(URI.file('/a/foo'), URI.file('/b/foo/'), '../../b/foo');
}
});
function assertResolve(u1: URI, path: string, expected: URI) {
const actual = resolvePath(u1, path);
assertEqualURI(actual, expected, `from ${u1.toString()} and ${path}`);
const p = path.indexOf('/') !== -1 ? posix : win32;
if (!p.isAbsolute(path)) {
let expectedPath = isWindows ? toSlashes(path) : path;
expectedPath = expectedPath.startsWith('./') ? expectedPath.substr(2) : expectedPath;
assert.strictEqual(relativePath(u1, actual), expectedPath, `relativePath (${u1.toString()}) on actual (${actual.toString()}) should be to path (${expectedPath})`);
}
}
test('resolve', () => {
if (isWindows) {
assertResolve(URI.file('c:\\foo\\bar'), 'file.js', URI.file('c:\\foo\\bar\\file.js'));
assertResolve(URI.file('c:\\foo\\bar'), 't\\file.js', URI.file('c:\\foo\\bar\\t\\file.js'));
assertResolve(URI.file('c:\\foo\\bar'), '.\\t\\file.js', URI.file('c:\\foo\\bar\\t\\file.js'));
assertResolve(URI.file('c:\\foo\\bar'), 'a1/file.js', URI.file('c:\\foo\\bar\\a1\\file.js'));
assertResolve(URI.file('c:\\foo\\bar'), './a1/file.js', URI.file('c:\\foo\\bar\\a1\\file.js'));
assertResolve(URI.file('c:\\foo\\bar'), '\\b1\\file.js', URI.file('c:\\b1\\file.js'));
assertResolve(URI.file('c:\\foo\\bar'), '/b1/file.js', URI.file('c:\\b1\\file.js'));
assertResolve(URI.file('c:\\foo\\bar\\'), 'file.js', URI.file('c:\\foo\\bar\\file.js'));
assertResolve(URI.file('c:\\'), 'file.js', URI.file('c:\\file.js'));
assertResolve(URI.file('c:\\'), '\\b1\\file.js', URI.file('c:\\b1\\file.js'));
assertResolve(URI.file('c:\\'), '/b1/file.js', URI.file('c:\\b1\\file.js'));
assertResolve(URI.file('c:\\'), 'd:\\foo\\bar.txt', URI.file('d:\\foo\\bar.txt'));
assertResolve(URI.file('\\\\server\\share\\some\\'), 'b1\\file.js', URI.file('\\\\server\\share\\some\\b1\\file.js'));
assertResolve(URI.file('\\\\server\\share\\some\\'), '\\file.js', URI.file('\\\\server\\share\\file.js'));
assertResolve(URI.file('c:\\'), '\\\\server\\share\\some\\', URI.file('\\\\server\\share\\some'));
assertResolve(URI.file('\\\\server\\share\\some\\'), 'c:\\', URI.file('c:\\'));
} else {
assertResolve(URI.file('/foo/bar'), 'file.js', URI.file('/foo/bar/file.js'));
assertResolve(URI.file('/foo/bar'), './file.js', URI.file('/foo/bar/file.js'));
assertResolve(URI.file('/foo/bar'), '/file.js', URI.file('/file.js'));
assertResolve(URI.file('/foo/bar/'), 'file.js', URI.file('/foo/bar/file.js'));
assertResolve(URI.file('/'), 'file.js', URI.file('/file.js'));
assertResolve(URI.file(''), './file.js', URI.file('/file.js'));
assertResolve(URI.file(''), '/file.js', URI.file('/file.js'));
}
assertResolve(URI.parse('foo://server/foo/bar'), 'file.js', URI.parse('foo://server/foo/bar/file.js'));
assertResolve(URI.parse('foo://server/foo/bar'), './file.js', URI.parse('foo://server/foo/bar/file.js'));
assertResolve(URI.parse('foo://server/foo/bar'), './file.js', URI.parse('foo://server/foo/bar/file.js'));
assertResolve(URI.parse('foo://server/foo/bar'), 'c:\\a1\\b1', URI.parse('foo://server/c:/a1/b1'));
assertResolve(URI.parse('foo://server/foo/bar'), 'c:\\', URI.parse('foo://server/c:'));
});
function assertIsEqual(u1: URI, u2: URI, ignoreCase: boolean | undefined, expected: boolean) {
let util = ignoreCase ? extUriIgnorePathCase : extUri;
assert.strictEqual(util.isEqual(u1, u2), expected, `${u1.toString()}${expected ? '===' : '!=='}${u2.toString()}`);
assert.strictEqual(util.compare(u1, u2) === 0, expected);
assert.strictEqual(util.getComparisonKey(u1) === util.getComparisonKey(u2), expected, `comparison keys ${u1.toString()}, ${u2.toString()}`);
assert.strictEqual(util.isEqualOrParent(u1, u2), expected, `isEqualOrParent ${u1.toString()}, ${u2.toString()}`);
if (!ignoreCase) {
assert.strictEqual(u1.toString() === u2.toString(), expected);
}
}
test('isEqual', () => {
let fileURI = isWindows ? URI.file('c:\\foo\\bar') : URI.file('/foo/bar');
let fileURI2 = isWindows ? URI.file('C:\\foo\\Bar') : URI.file('/foo/Bar');
assertIsEqual(fileURI, fileURI, true, true);
assertIsEqual(fileURI, fileURI, false, true);
assertIsEqual(fileURI, fileURI, undefined, true);
assertIsEqual(fileURI, fileURI2, true, true);
assertIsEqual(fileURI, fileURI2, false, false);
let fileURI3 = URI.parse('foo://server:453/foo/bar');
let fileURI4 = URI.parse('foo://server:453/foo/Bar');
assertIsEqual(fileURI3, fileURI3, true, true);
assertIsEqual(fileURI3, fileURI3, false, true);
assertIsEqual(fileURI3, fileURI3, undefined, true);
assertIsEqual(fileURI3, fileURI4, true, true);
assertIsEqual(fileURI3, fileURI4, false, false);
assertIsEqual(fileURI, fileURI3, true, false);
assertIsEqual(URI.parse('file://server'), URI.parse('file://server/'), true, true);
assertIsEqual(URI.parse('http://server'), URI.parse('http://server/'), true, true);
assertIsEqual(URI.parse('foo://server'), URI.parse('foo://server/'), true, false); // only selected scheme have / as the default path
assertIsEqual(URI.parse('foo://server/foo'), URI.parse('foo://server/foo/'), true, false);
assertIsEqual(URI.parse('foo://server/foo'), URI.parse('foo://server/foo?'), true, true);
let fileURI5 = URI.parse('foo://server:453/foo/bar?q=1');
let fileURI6 = URI.parse('foo://server:453/foo/bar#xy');
assertIsEqual(fileURI5, fileURI5, true, true);
assertIsEqual(fileURI5, fileURI3, true, false);
assertIsEqual(fileURI6, fileURI6, true, true);
assertIsEqual(fileURI6, fileURI5, true, false);
assertIsEqual(fileURI6, fileURI3, true, false);
});
test('isEqualOrParent', () => {
let fileURI = isWindows ? URI.file('c:\\foo\\bar') : URI.file('/foo/bar');
let fileURI2 = isWindows ? URI.file('c:\\foo') : URI.file('/foo');
let fileURI2b = isWindows ? URI.file('C:\\Foo\\') : URI.file('/Foo/');
assert.strictEqual(extUriIgnorePathCase.isEqualOrParent(fileURI, fileURI), true, '1');
assert.strictEqual(extUri.isEqualOrParent(fileURI, fileURI), true, '2');
assert.strictEqual(extUriIgnorePathCase.isEqualOrParent(fileURI, fileURI2), true, '3');
assert.strictEqual(extUri.isEqualOrParent(fileURI, fileURI2), true, '4');
assert.strictEqual(extUriIgnorePathCase.isEqualOrParent(fileURI, fileURI2b), true, '5');
assert.strictEqual(extUri.isEqualOrParent(fileURI, fileURI2b), false, '6');
assert.strictEqual(extUri.isEqualOrParent(fileURI2, fileURI), false, '7');
assert.strictEqual(extUriIgnorePathCase.isEqualOrParent(fileURI2b, fileURI2), true, '8');
let fileURI3 = URI.parse('foo://server:453/foo/bar/goo');
let fileURI4 = URI.parse('foo://server:453/foo/');
let fileURI5 = URI.parse('foo://server:453/foo');
assert.strictEqual(extUriIgnorePathCase.isEqualOrParent(fileURI3, fileURI3, true), true, '11');
assert.strictEqual(extUri.isEqualOrParent(fileURI3, fileURI3), true, '12');
assert.strictEqual(extUriIgnorePathCase.isEqualOrParent(fileURI3, fileURI4, true), true, '13');
assert.strictEqual(extUri.isEqualOrParent(fileURI3, fileURI4), true, '14');
assert.strictEqual(extUriIgnorePathCase.isEqualOrParent(fileURI3, fileURI, true), false, '15');
assert.strictEqual(extUriIgnorePathCase.isEqualOrParent(fileURI5, fileURI5, true), true, '16');
let fileURI6 = URI.parse('foo://server:453/foo?q=1');
let fileURI7 = URI.parse('foo://server:453/foo/bar?q=1');
assert.strictEqual(extUriIgnorePathCase.isEqualOrParent(fileURI6, fileURI5), false, '17');
assert.strictEqual(extUriIgnorePathCase.isEqualOrParent(fileURI6, fileURI6), true, '18');
assert.strictEqual(extUriIgnorePathCase.isEqualOrParent(fileURI7, fileURI6), true, '19');
assert.strictEqual(extUriIgnorePathCase.isEqualOrParent(fileURI7, fileURI5), false, '20');
});
test('query parameters stripped from extname', () => {
const uriWithQueryParam = URI.file('/test/project/test.txt?q=1');
const uriWithoutQueryParam = URI.file('/test/project/test.txt');
assert.strictEqual(extname(uriWithQueryParam), '.txt');
assert.strictEqual(extname(uriWithoutQueryParam), '.txt');
});
});
| src/vs/base/test/common/resources.test.ts | 1 | https://github.com/microsoft/vscode/commit/c4fe803132ea8cd9aa903a83d7c5786ac77897b3 | [
0.9957953691482544,
0.0735028088092804,
0.00016495278396178037,
0.0003042277821805328,
0.2486809641122818
] |
{
"id": 1,
"code_window": [
"import { toSlashes } from 'vs/base/common/extpath';\n",
"import { posix, win32 } from 'vs/base/common/path';\n",
"import { isWindows } from 'vs/base/common/platform';\n",
"import { addTrailingPathSeparator, basename, dirname, distinctParents, extname, extUri, extUriIgnorePathCase, hasTrailingPathSeparator, isAbsolutePath, joinPath, normalizePath, relativePath, removeTrailingPathSeparator, resolvePath } from 'vs/base/common/resources';\n",
"import { URI } from 'vs/base/common/uri';\n",
"\n",
"\n",
"suite('Resources', () => {\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { addTrailingPathSeparator, basename, dirname, distinctParents, extUri, extUriIgnorePathCase, hasTrailingPathSeparator, isAbsolutePath, joinPath, normalizePath, relativePath, removeTrailingPathSeparator, resolvePath } from 'vs/base/common/resources';\n"
],
"file_path": "src/vs/base/test/common/resources.test.ts",
"type": "replace",
"edit_start_line_idx": 8
} | [
{
"c": "impl",
"t": "source.rust keyword.other.rust",
"r": {
"dark_plus": "keyword: #569CD6",
"light_plus": "keyword: #0000FF",
"dark_vs": "keyword: #569CD6",
"light_vs": "keyword: #0000FF",
"hc_black": "keyword: #569CD6"
}
},
{
"c": " ",
"t": "source.rust",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": "Foo",
"t": "source.rust entity.name.type.rust",
"r": {
"dark_plus": "entity.name.type: #4EC9B0",
"light_plus": "entity.name.type: #267F99",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "entity.name.type: #4EC9B0"
}
},
{
"c": "<",
"t": "source.rust punctuation.brackets.angle.rust",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": "A",
"t": "source.rust entity.name.type.rust",
"r": {
"dark_plus": "entity.name.type: #4EC9B0",
"light_plus": "entity.name.type: #267F99",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "entity.name.type: #4EC9B0"
}
},
{
"c": ",",
"t": "source.rust punctuation.comma.rust",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": "B",
"t": "source.rust entity.name.type.rust",
"r": {
"dark_plus": "entity.name.type: #4EC9B0",
"light_plus": "entity.name.type: #267F99",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "entity.name.type: #4EC9B0"
}
},
{
"c": ">",
"t": "source.rust punctuation.brackets.angle.rust",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": " ",
"t": "source.rust",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": "where",
"t": "source.rust keyword.other.rust",
"r": {
"dark_plus": "keyword: #569CD6",
"light_plus": "keyword: #0000FF",
"dark_vs": "keyword: #569CD6",
"light_vs": "keyword: #0000FF",
"hc_black": "keyword: #569CD6"
}
},
{
"c": " ",
"t": "source.rust",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": "A",
"t": "source.rust entity.name.type.rust",
"r": {
"dark_plus": "entity.name.type: #4EC9B0",
"light_plus": "entity.name.type: #267F99",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "entity.name.type: #4EC9B0"
}
},
{
"c": ":",
"t": "source.rust keyword.operator.key-value.rust",
"r": {
"dark_plus": "keyword.operator: #D4D4D4",
"light_plus": "keyword.operator: #000000",
"dark_vs": "keyword.operator: #D4D4D4",
"light_vs": "keyword.operator: #000000",
"hc_black": "keyword.operator: #D4D4D4"
}
},
{
"c": " ",
"t": "source.rust",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": "B",
"t": "source.rust entity.name.type.rust",
"r": {
"dark_plus": "entity.name.type: #4EC9B0",
"light_plus": "entity.name.type: #267F99",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "entity.name.type: #4EC9B0"
}
},
{
"c": "{",
"t": "source.rust punctuation.brackets.curly.rust",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": " ",
"t": "source.rust",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": "}",
"t": "source.rust punctuation.brackets.curly.rust",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": "impl",
"t": "source.rust keyword.other.rust",
"r": {
"dark_plus": "keyword: #569CD6",
"light_plus": "keyword: #0000FF",
"dark_vs": "keyword: #569CD6",
"light_vs": "keyword: #0000FF",
"hc_black": "keyword: #569CD6"
}
},
{
"c": " ",
"t": "source.rust",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": "Foo",
"t": "source.rust entity.name.type.rust",
"r": {
"dark_plus": "entity.name.type: #4EC9B0",
"light_plus": "entity.name.type: #267F99",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "entity.name.type: #4EC9B0"
}
},
{
"c": "<",
"t": "source.rust punctuation.brackets.angle.rust",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": "A",
"t": "source.rust entity.name.type.rust",
"r": {
"dark_plus": "entity.name.type: #4EC9B0",
"light_plus": "entity.name.type: #267F99",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "entity.name.type: #4EC9B0"
}
},
{
"c": ",",
"t": "source.rust punctuation.comma.rust",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": "B",
"t": "source.rust entity.name.type.rust",
"r": {
"dark_plus": "entity.name.type: #4EC9B0",
"light_plus": "entity.name.type: #267F99",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "entity.name.type: #4EC9B0"
}
},
{
"c": ">",
"t": "source.rust punctuation.brackets.angle.rust",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": " ",
"t": "source.rust",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": "for",
"t": "source.rust keyword.control.rust",
"r": {
"dark_plus": "keyword.control: #C586C0",
"light_plus": "keyword.control: #AF00DB",
"dark_vs": "keyword.control: #569CD6",
"light_vs": "keyword.control: #0000FF",
"hc_black": "keyword.control: #C586C0"
}
},
{
"c": " ",
"t": "source.rust",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": "C",
"t": "source.rust entity.name.type.rust",
"r": {
"dark_plus": "entity.name.type: #4EC9B0",
"light_plus": "entity.name.type: #267F99",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "entity.name.type: #4EC9B0"
}
},
{
"c": " ",
"t": "source.rust",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": "where",
"t": "source.rust keyword.other.rust",
"r": {
"dark_plus": "keyword: #569CD6",
"light_plus": "keyword: #0000FF",
"dark_vs": "keyword: #569CD6",
"light_vs": "keyword: #0000FF",
"hc_black": "keyword: #569CD6"
}
},
{
"c": " ",
"t": "source.rust",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": "A",
"t": "source.rust entity.name.type.rust",
"r": {
"dark_plus": "entity.name.type: #4EC9B0",
"light_plus": "entity.name.type: #267F99",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "entity.name.type: #4EC9B0"
}
},
{
"c": ":",
"t": "source.rust keyword.operator.key-value.rust",
"r": {
"dark_plus": "keyword.operator: #D4D4D4",
"light_plus": "keyword.operator: #000000",
"dark_vs": "keyword.operator: #D4D4D4",
"light_vs": "keyword.operator: #000000",
"hc_black": "keyword.operator: #D4D4D4"
}
},
{
"c": " ",
"t": "source.rust",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": "B",
"t": "source.rust entity.name.type.rust",
"r": {
"dark_plus": "entity.name.type: #4EC9B0",
"light_plus": "entity.name.type: #267F99",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "entity.name.type: #4EC9B0"
}
},
{
"c": "{",
"t": "source.rust punctuation.brackets.curly.rust",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": " ",
"t": "source.rust",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": "}",
"t": "source.rust punctuation.brackets.curly.rust",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": "impl",
"t": "source.rust keyword.other.rust",
"r": {
"dark_plus": "keyword: #569CD6",
"light_plus": "keyword: #0000FF",
"dark_vs": "keyword: #569CD6",
"light_vs": "keyword: #0000FF",
"hc_black": "keyword: #569CD6"
}
},
{
"c": " ",
"t": "source.rust",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": "Foo",
"t": "source.rust entity.name.type.rust",
"r": {
"dark_plus": "entity.name.type: #4EC9B0",
"light_plus": "entity.name.type: #267F99",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "entity.name.type: #4EC9B0"
}
},
{
"c": "<",
"t": "source.rust punctuation.brackets.angle.rust",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": "A",
"t": "source.rust entity.name.type.rust",
"r": {
"dark_plus": "entity.name.type: #4EC9B0",
"light_plus": "entity.name.type: #267F99",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "entity.name.type: #4EC9B0"
}
},
{
"c": ",",
"t": "source.rust punctuation.comma.rust",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": "B",
"t": "source.rust entity.name.type.rust",
"r": {
"dark_plus": "entity.name.type: #4EC9B0",
"light_plus": "entity.name.type: #267F99",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "entity.name.type: #4EC9B0"
}
},
{
"c": ">",
"t": "source.rust punctuation.brackets.angle.rust",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": " ",
"t": "source.rust",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": "for",
"t": "source.rust keyword.control.rust",
"r": {
"dark_plus": "keyword.control: #C586C0",
"light_plus": "keyword.control: #AF00DB",
"dark_vs": "keyword.control: #569CD6",
"light_vs": "keyword.control: #0000FF",
"hc_black": "keyword.control: #C586C0"
}
},
{
"c": " ",
"t": "source.rust",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": "C",
"t": "source.rust entity.name.type.rust",
"r": {
"dark_plus": "entity.name.type: #4EC9B0",
"light_plus": "entity.name.type: #267F99",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "entity.name.type: #4EC9B0"
}
},
{
"c": "{",
"t": "source.rust punctuation.brackets.curly.rust",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": " ",
"t": "source.rust",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": "fn",
"t": "source.rust meta.function.definition.rust keyword.other.fn.rust",
"r": {
"dark_plus": "keyword: #569CD6",
"light_plus": "keyword: #0000FF",
"dark_vs": "keyword: #569CD6",
"light_vs": "keyword: #0000FF",
"hc_black": "keyword: #569CD6"
}
},
{
"c": " ",
"t": "source.rust meta.function.definition.rust",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": "foo",
"t": "source.rust meta.function.definition.rust entity.name.function.rust",
"r": {
"dark_plus": "entity.name.function: #DCDCAA",
"light_plus": "entity.name.function: #795E26",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "entity.name.function: #DCDCAA"
}
},
{
"c": "<",
"t": "source.rust meta.function.definition.rust punctuation.brackets.angle.rust",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": "A",
"t": "source.rust meta.function.definition.rust entity.name.type.rust",
"r": {
"dark_plus": "entity.name.type: #4EC9B0",
"light_plus": "entity.name.type: #267F99",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "entity.name.type: #4EC9B0"
}
},
{
"c": ",",
"t": "source.rust meta.function.definition.rust punctuation.comma.rust",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": "B",
"t": "source.rust meta.function.definition.rust entity.name.type.rust",
"r": {
"dark_plus": "entity.name.type: #4EC9B0",
"light_plus": "entity.name.type: #267F99",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "entity.name.type: #4EC9B0"
}
},
{
"c": ">",
"t": "source.rust meta.function.definition.rust punctuation.brackets.angle.rust",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": " ",
"t": "source.rust meta.function.definition.rust",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": "->",
"t": "source.rust meta.function.definition.rust keyword.operator.arrow.skinny.rust",
"r": {
"dark_plus": "keyword.operator: #D4D4D4",
"light_plus": "keyword.operator: #000000",
"dark_vs": "keyword.operator: #D4D4D4",
"light_vs": "keyword.operator: #000000",
"hc_black": "keyword.operator: #D4D4D4"
}
},
{
"c": " ",
"t": "source.rust meta.function.definition.rust",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": "C",
"t": "source.rust meta.function.definition.rust entity.name.type.rust",
"r": {
"dark_plus": "entity.name.type: #4EC9B0",
"light_plus": "entity.name.type: #267F99",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "entity.name.type: #4EC9B0"
}
},
{
"c": " ",
"t": "source.rust meta.function.definition.rust",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": "where",
"t": "source.rust meta.function.definition.rust keyword.other.rust",
"r": {
"dark_plus": "keyword: #569CD6",
"light_plus": "keyword: #0000FF",
"dark_vs": "keyword: #569CD6",
"light_vs": "keyword: #0000FF",
"hc_black": "keyword: #569CD6"
}
},
{
"c": " ",
"t": "source.rust meta.function.definition.rust",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": "A",
"t": "source.rust meta.function.definition.rust entity.name.type.rust",
"r": {
"dark_plus": "entity.name.type: #4EC9B0",
"light_plus": "entity.name.type: #267F99",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "entity.name.type: #4EC9B0"
}
},
{
"c": ":",
"t": "source.rust meta.function.definition.rust keyword.operator.key-value.rust",
"r": {
"dark_plus": "keyword.operator: #D4D4D4",
"light_plus": "keyword.operator: #000000",
"dark_vs": "keyword.operator: #D4D4D4",
"light_vs": "keyword.operator: #000000",
"hc_black": "keyword.operator: #D4D4D4"
}
},
{
"c": " ",
"t": "source.rust meta.function.definition.rust",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": "B",
"t": "source.rust meta.function.definition.rust entity.name.type.rust",
"r": {
"dark_plus": "entity.name.type: #4EC9B0",
"light_plus": "entity.name.type: #267F99",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "entity.name.type: #4EC9B0"
}
},
{
"c": " ",
"t": "source.rust meta.function.definition.rust",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": "{",
"t": "source.rust meta.function.definition.rust punctuation.brackets.curly.rust",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": " ",
"t": "source.rust",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": "}",
"t": "source.rust punctuation.brackets.curly.rust",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": "}",
"t": "source.rust punctuation.brackets.curly.rust",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": "fn",
"t": "source.rust meta.function.definition.rust keyword.other.fn.rust",
"r": {
"dark_plus": "keyword: #569CD6",
"light_plus": "keyword: #0000FF",
"dark_vs": "keyword: #569CD6",
"light_vs": "keyword: #0000FF",
"hc_black": "keyword: #569CD6"
}
},
{
"c": " ",
"t": "source.rust meta.function.definition.rust",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": "foo",
"t": "source.rust meta.function.definition.rust entity.name.function.rust",
"r": {
"dark_plus": "entity.name.function: #DCDCAA",
"light_plus": "entity.name.function: #795E26",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "entity.name.function: #DCDCAA"
}
},
{
"c": "<",
"t": "source.rust meta.function.definition.rust punctuation.brackets.angle.rust",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": "A",
"t": "source.rust meta.function.definition.rust entity.name.type.rust",
"r": {
"dark_plus": "entity.name.type: #4EC9B0",
"light_plus": "entity.name.type: #267F99",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "entity.name.type: #4EC9B0"
}
},
{
"c": ",",
"t": "source.rust meta.function.definition.rust punctuation.comma.rust",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": "B",
"t": "source.rust meta.function.definition.rust entity.name.type.rust",
"r": {
"dark_plus": "entity.name.type: #4EC9B0",
"light_plus": "entity.name.type: #267F99",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "entity.name.type: #4EC9B0"
}
},
{
"c": ">",
"t": "source.rust meta.function.definition.rust punctuation.brackets.angle.rust",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": " ",
"t": "source.rust meta.function.definition.rust",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": "->",
"t": "source.rust meta.function.definition.rust keyword.operator.arrow.skinny.rust",
"r": {
"dark_plus": "keyword.operator: #D4D4D4",
"light_plus": "keyword.operator: #000000",
"dark_vs": "keyword.operator: #D4D4D4",
"light_vs": "keyword.operator: #000000",
"hc_black": "keyword.operator: #D4D4D4"
}
},
{
"c": " ",
"t": "source.rust meta.function.definition.rust",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": "C",
"t": "source.rust meta.function.definition.rust entity.name.type.rust",
"r": {
"dark_plus": "entity.name.type: #4EC9B0",
"light_plus": "entity.name.type: #267F99",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "entity.name.type: #4EC9B0"
}
},
{
"c": " ",
"t": "source.rust meta.function.definition.rust",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": "where",
"t": "source.rust meta.function.definition.rust keyword.other.rust",
"r": {
"dark_plus": "keyword: #569CD6",
"light_plus": "keyword: #0000FF",
"dark_vs": "keyword: #569CD6",
"light_vs": "keyword: #0000FF",
"hc_black": "keyword: #569CD6"
}
},
{
"c": " ",
"t": "source.rust meta.function.definition.rust",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": "A",
"t": "source.rust meta.function.definition.rust entity.name.type.rust",
"r": {
"dark_plus": "entity.name.type: #4EC9B0",
"light_plus": "entity.name.type: #267F99",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "entity.name.type: #4EC9B0"
}
},
{
"c": ":",
"t": "source.rust meta.function.definition.rust keyword.operator.key-value.rust",
"r": {
"dark_plus": "keyword.operator: #D4D4D4",
"light_plus": "keyword.operator: #000000",
"dark_vs": "keyword.operator: #D4D4D4",
"light_vs": "keyword.operator: #000000",
"hc_black": "keyword.operator: #D4D4D4"
}
},
{
"c": " ",
"t": "source.rust meta.function.definition.rust",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": "B",
"t": "source.rust meta.function.definition.rust entity.name.type.rust",
"r": {
"dark_plus": "entity.name.type: #4EC9B0",
"light_plus": "entity.name.type: #267F99",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "entity.name.type: #4EC9B0"
}
},
{
"c": "{",
"t": "source.rust meta.function.definition.rust punctuation.brackets.curly.rust",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": " ",
"t": "source.rust",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": "}",
"t": "source.rust punctuation.brackets.curly.rust",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": "struct",
"t": "source.rust keyword.declaration.struct.rust storage.type.rust",
"r": {
"dark_plus": "storage.type: #569CD6",
"light_plus": "storage.type: #0000FF",
"dark_vs": "storage.type: #569CD6",
"light_vs": "storage.type: #0000FF",
"hc_black": "storage.type: #569CD6"
}
},
{
"c": " ",
"t": "source.rust",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": "Foo",
"t": "source.rust entity.name.type.struct.rust",
"r": {
"dark_plus": "entity.name.type: #4EC9B0",
"light_plus": "entity.name.type: #267F99",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "entity.name.type: #4EC9B0"
}
},
{
"c": "<",
"t": "source.rust punctuation.brackets.angle.rust",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": "A",
"t": "source.rust entity.name.type.rust",
"r": {
"dark_plus": "entity.name.type: #4EC9B0",
"light_plus": "entity.name.type: #267F99",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "entity.name.type: #4EC9B0"
}
},
{
"c": ",",
"t": "source.rust punctuation.comma.rust",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": "B",
"t": "source.rust entity.name.type.rust",
"r": {
"dark_plus": "entity.name.type: #4EC9B0",
"light_plus": "entity.name.type: #267F99",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "entity.name.type: #4EC9B0"
}
},
{
"c": ">",
"t": "source.rust punctuation.brackets.angle.rust",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": " ",
"t": "source.rust",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": "where",
"t": "source.rust keyword.other.rust",
"r": {
"dark_plus": "keyword: #569CD6",
"light_plus": "keyword: #0000FF",
"dark_vs": "keyword: #569CD6",
"light_vs": "keyword: #0000FF",
"hc_black": "keyword: #569CD6"
}
},
{
"c": " ",
"t": "source.rust",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": "A",
"t": "source.rust entity.name.type.rust",
"r": {
"dark_plus": "entity.name.type: #4EC9B0",
"light_plus": "entity.name.type: #267F99",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "entity.name.type: #4EC9B0"
}
},
{
"c": ":",
"t": "source.rust keyword.operator.key-value.rust",
"r": {
"dark_plus": "keyword.operator: #D4D4D4",
"light_plus": "keyword.operator: #000000",
"dark_vs": "keyword.operator: #D4D4D4",
"light_vs": "keyword.operator: #000000",
"hc_black": "keyword.operator: #D4D4D4"
}
},
{
"c": " ",
"t": "source.rust",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": "B",
"t": "source.rust entity.name.type.rust",
"r": {
"dark_plus": "entity.name.type: #4EC9B0",
"light_plus": "entity.name.type: #267F99",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "entity.name.type: #4EC9B0"
}
},
{
"c": "{",
"t": "source.rust punctuation.brackets.curly.rust",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": " ",
"t": "source.rust",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": "}",
"t": "source.rust punctuation.brackets.curly.rust",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": "trait",
"t": "source.rust keyword.declaration.trait.rust storage.type.rust",
"r": {
"dark_plus": "storage.type: #569CD6",
"light_plus": "storage.type: #0000FF",
"dark_vs": "storage.type: #569CD6",
"light_vs": "storage.type: #0000FF",
"hc_black": "storage.type: #569CD6"
}
},
{
"c": " ",
"t": "source.rust",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": "Foo",
"t": "source.rust entity.name.type.trait.rust",
"r": {
"dark_plus": "entity.name.type: #4EC9B0",
"light_plus": "entity.name.type: #267F99",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "entity.name.type: #4EC9B0"
}
},
{
"c": "<",
"t": "source.rust punctuation.brackets.angle.rust",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": "A",
"t": "source.rust entity.name.type.rust",
"r": {
"dark_plus": "entity.name.type: #4EC9B0",
"light_plus": "entity.name.type: #267F99",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "entity.name.type: #4EC9B0"
}
},
{
"c": ",",
"t": "source.rust punctuation.comma.rust",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": "B",
"t": "source.rust entity.name.type.rust",
"r": {
"dark_plus": "entity.name.type: #4EC9B0",
"light_plus": "entity.name.type: #267F99",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "entity.name.type: #4EC9B0"
}
},
{
"c": ">",
"t": "source.rust punctuation.brackets.angle.rust",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": " ",
"t": "source.rust",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": ":",
"t": "source.rust keyword.operator.key-value.rust",
"r": {
"dark_plus": "keyword.operator: #D4D4D4",
"light_plus": "keyword.operator: #000000",
"dark_vs": "keyword.operator: #D4D4D4",
"light_vs": "keyword.operator: #000000",
"hc_black": "keyword.operator: #D4D4D4"
}
},
{
"c": " ",
"t": "source.rust",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": "C",
"t": "source.rust entity.name.type.rust",
"r": {
"dark_plus": "entity.name.type: #4EC9B0",
"light_plus": "entity.name.type: #267F99",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "entity.name.type: #4EC9B0"
}
},
{
"c": " ",
"t": "source.rust",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": "where",
"t": "source.rust keyword.other.rust",
"r": {
"dark_plus": "keyword: #569CD6",
"light_plus": "keyword: #0000FF",
"dark_vs": "keyword: #569CD6",
"light_vs": "keyword: #0000FF",
"hc_black": "keyword: #569CD6"
}
},
{
"c": " ",
"t": "source.rust",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": "A",
"t": "source.rust entity.name.type.rust",
"r": {
"dark_plus": "entity.name.type: #4EC9B0",
"light_plus": "entity.name.type: #267F99",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "entity.name.type: #4EC9B0"
}
},
{
"c": ":",
"t": "source.rust keyword.operator.key-value.rust",
"r": {
"dark_plus": "keyword.operator: #D4D4D4",
"light_plus": "keyword.operator: #000000",
"dark_vs": "keyword.operator: #D4D4D4",
"light_vs": "keyword.operator: #000000",
"hc_black": "keyword.operator: #D4D4D4"
}
},
{
"c": " ",
"t": "source.rust",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": "B",
"t": "source.rust entity.name.type.rust",
"r": {
"dark_plus": "entity.name.type: #4EC9B0",
"light_plus": "entity.name.type: #267F99",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "entity.name.type: #4EC9B0"
}
},
{
"c": "{",
"t": "source.rust punctuation.brackets.curly.rust",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": " ",
"t": "source.rust",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": "}",
"t": "source.rust punctuation.brackets.curly.rust",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
}
] | extensions/vscode-colorize-tests/test/colorize-results/test-6611_rs.json | 0 | https://github.com/microsoft/vscode/commit/c4fe803132ea8cd9aa903a83d7c5786ac77897b3 | [
0.00017834780737757683,
0.00017403530364390463,
0.00017160426068585366,
0.0001734531542751938,
0.000001512833364358812
] |
{
"id": 1,
"code_window": [
"import { toSlashes } from 'vs/base/common/extpath';\n",
"import { posix, win32 } from 'vs/base/common/path';\n",
"import { isWindows } from 'vs/base/common/platform';\n",
"import { addTrailingPathSeparator, basename, dirname, distinctParents, extname, extUri, extUriIgnorePathCase, hasTrailingPathSeparator, isAbsolutePath, joinPath, normalizePath, relativePath, removeTrailingPathSeparator, resolvePath } from 'vs/base/common/resources';\n",
"import { URI } from 'vs/base/common/uri';\n",
"\n",
"\n",
"suite('Resources', () => {\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { addTrailingPathSeparator, basename, dirname, distinctParents, extUri, extUriIgnorePathCase, hasTrailingPathSeparator, isAbsolutePath, joinPath, normalizePath, relativePath, removeTrailingPathSeparator, resolvePath } from 'vs/base/common/resources';\n"
],
"file_path": "src/vs/base/test/common/resources.test.ts",
"type": "replace",
"edit_start_line_idx": 8
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { Position } from 'vs/editor/common/core/position';
import { Range } from 'vs/editor/common/core/range';
import { ViewportData } from 'vs/editor/common/viewLayout/viewLinesViewportData';
import { IViewLayout, ViewModelDecoration } from 'vs/editor/common/viewModel/viewModel';
export interface IViewLines {
linesVisibleRangesForRange(range: Range, includeNewLines: boolean): LineVisibleRanges[] | null;
visibleRangeForPosition(position: Position): HorizontalPosition | null;
}
export abstract class RestrictedRenderingContext {
_restrictedRenderingContextBrand: void = undefined;
public readonly viewportData: ViewportData;
public readonly scrollWidth: number;
public readonly scrollHeight: number;
public readonly visibleRange: Range;
public readonly bigNumbersDelta: number;
public readonly scrollTop: number;
public readonly scrollLeft: number;
public readonly viewportWidth: number;
public readonly viewportHeight: number;
private readonly _viewLayout: IViewLayout;
constructor(viewLayout: IViewLayout, viewportData: ViewportData) {
this._viewLayout = viewLayout;
this.viewportData = viewportData;
this.scrollWidth = this._viewLayout.getScrollWidth();
this.scrollHeight = this._viewLayout.getScrollHeight();
this.visibleRange = this.viewportData.visibleRange;
this.bigNumbersDelta = this.viewportData.bigNumbersDelta;
const vInfo = this._viewLayout.getCurrentViewport();
this.scrollTop = vInfo.top;
this.scrollLeft = vInfo.left;
this.viewportWidth = vInfo.width;
this.viewportHeight = vInfo.height;
}
public getScrolledTopFromAbsoluteTop(absoluteTop: number): number {
return absoluteTop - this.scrollTop;
}
public getVerticalOffsetForLineNumber(lineNumber: number): number {
return this._viewLayout.getVerticalOffsetForLineNumber(lineNumber);
}
public getDecorationsInViewport(): ViewModelDecoration[] {
return this.viewportData.getDecorationsInViewport();
}
}
export class RenderingContext extends RestrictedRenderingContext {
_renderingContextBrand: void = undefined;
private readonly _viewLines: IViewLines;
constructor(viewLayout: IViewLayout, viewportData: ViewportData, viewLines: IViewLines) {
super(viewLayout, viewportData);
this._viewLines = viewLines;
}
public linesVisibleRangesForRange(range: Range, includeNewLines: boolean): LineVisibleRanges[] | null {
return this._viewLines.linesVisibleRangesForRange(range, includeNewLines);
}
public visibleRangeForPosition(position: Position): HorizontalPosition | null {
return this._viewLines.visibleRangeForPosition(position);
}
}
export class LineVisibleRanges {
constructor(
public readonly outsideRenderedLine: boolean,
public readonly lineNumber: number,
public readonly ranges: HorizontalRange[]
) { }
}
export class HorizontalRange {
_horizontalRangeBrand: void = undefined;
public left: number;
public width: number;
public static from(ranges: FloatHorizontalRange[]): HorizontalRange[] {
const result = new Array(ranges.length);
for (let i = 0, len = ranges.length; i < len; i++) {
const range = ranges[i];
result[i] = new HorizontalRange(range.left, range.width);
}
return result;
}
constructor(left: number, width: number) {
this.left = Math.round(left);
this.width = Math.round(width);
}
public toString(): string {
return `[${this.left},${this.width}]`;
}
}
export class FloatHorizontalRange {
_floatHorizontalRangeBrand: void = undefined;
public left: number;
public width: number;
constructor(left: number, width: number) {
this.left = left;
this.width = width;
}
public toString(): string {
return `[${this.left},${this.width}]`;
}
public static compare(a: FloatHorizontalRange, b: FloatHorizontalRange): number {
return a.left - b.left;
}
}
export class HorizontalPosition {
public outsideRenderedLine: boolean;
/**
* Math.round(this.originalLeft)
*/
public left: number;
public originalLeft: number;
constructor(outsideRenderedLine: boolean, left: number) {
this.outsideRenderedLine = outsideRenderedLine;
this.originalLeft = left;
this.left = Math.round(this.originalLeft);
}
}
export class VisibleRanges {
constructor(
public readonly outsideRenderedLine: boolean,
public readonly ranges: FloatHorizontalRange[]
) {
}
}
| src/vs/editor/common/view/renderingContext.ts | 0 | https://github.com/microsoft/vscode/commit/c4fe803132ea8cd9aa903a83d7c5786ac77897b3 | [
0.00017673250113148242,
0.0001713720557745546,
0.00016299607523251325,
0.0001727734925225377,
0.000003942835974157788
] |
{
"id": 1,
"code_window": [
"import { toSlashes } from 'vs/base/common/extpath';\n",
"import { posix, win32 } from 'vs/base/common/path';\n",
"import { isWindows } from 'vs/base/common/platform';\n",
"import { addTrailingPathSeparator, basename, dirname, distinctParents, extname, extUri, extUriIgnorePathCase, hasTrailingPathSeparator, isAbsolutePath, joinPath, normalizePath, relativePath, removeTrailingPathSeparator, resolvePath } from 'vs/base/common/resources';\n",
"import { URI } from 'vs/base/common/uri';\n",
"\n",
"\n",
"suite('Resources', () => {\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { addTrailingPathSeparator, basename, dirname, distinctParents, extUri, extUriIgnorePathCase, hasTrailingPathSeparator, isAbsolutePath, joinPath, normalizePath, relativePath, removeTrailingPathSeparator, resolvePath } from 'vs/base/common/resources';\n"
],
"file_path": "src/vs/base/test/common/resources.test.ts",
"type": "replace",
"edit_start_line_idx": 8
} | {
"registrations": [
{
"component": {
"type": "git",
"git": {
"name": "vscode-swift",
"repositoryUrl": "https://github.com/owensd/vscode-swift",
"commitHash": "cec27af6662e3799120b208e64483efdfe5521f5"
}
},
"licenseDetail": [
"The MIT License (MIT)",
"",
"Copyright (c) 2015 David Owens II",
"",
"Permission is hereby granted, free of charge, to any person obtaining a copy",
"of this software and associated documentation files (the \"Software\"), to deal",
"in the Software without restriction, including without limitation the rights",
"to use, copy, modify, merge, publish, distribute, sublicense, and/or sell",
"copies of the Software, and to permit persons to whom the Software is",
"furnished to do so, subject to the following conditions:",
"",
"The above copyright notice and this permission notice shall be included in all",
"copies or substantial portions of the Software.",
"",
"THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR",
"IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,",
"FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE",
"AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER",
"LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,",
"OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE."
],
"license": "MIT",
"description": "The files in this folder are based on https://github.com/owensd/vscode-swift.",
"version": "0.0.1"
},
{
"component": {
"type": "git",
"git": {
"name": "freebroccolo/atom-language-swift",
"repositoryUrl": "https://github.com/freebroccolo/atom-language-swift",
"commitHash": "d8f4ed1f79cbb4d5d215e7a68fa8cc6b618e16e0"
}
},
"licenseDetail": [
"The MIT License (MIT)",
"",
"Copyright (c) 2014 Darin Morrison",
"",
"Permission is hereby granted, free of charge, to any person obtaining a copy",
"of this software and associated documentation files (the \"Software\"), to deal",
"in the Software without restriction, including without limitation the rights",
"to use, copy, modify, merge, publish, distribute, sublicense, and/or sell",
"copies of the Software, and to permit persons to whom the Software is",
"furnished to do so, subject to the following conditions:",
"",
"The above copyright notice and this permission notice shall be included in all",
"copies or substantial portions of the Software.",
"",
"THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR",
"IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,",
"FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE",
"AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER",
"LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,",
"OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE."
],
"license": "MIT",
"version": "0.0.0"
}
],
"version": 1
} | extensions/swift/cgmanifest.json | 0 | https://github.com/microsoft/vscode/commit/c4fe803132ea8cd9aa903a83d7c5786ac77897b3 | [
0.00017781209317035973,
0.00017421235679648817,
0.00017086284060496837,
0.00017440959345549345,
0.000002352886212975136
] |
{
"id": 2,
"code_window": [
"\t\tassert.strictEqual(extUriIgnorePathCase.isEqualOrParent(fileURI6, fileURI5), false, '17');\n",
"\t\tassert.strictEqual(extUriIgnorePathCase.isEqualOrParent(fileURI6, fileURI6), true, '18');\n",
"\t\tassert.strictEqual(extUriIgnorePathCase.isEqualOrParent(fileURI7, fileURI6), true, '19');\n",
"\t\tassert.strictEqual(extUriIgnorePathCase.isEqualOrParent(fileURI7, fileURI5), false, '20');\n",
"\t});\n",
"\n",
"\ttest('query parameters stripped from extname', () => {\n",
"\t\tconst uriWithQueryParam = URI.file('/test/project/test.txt?q=1');\n",
"\t\tconst uriWithoutQueryParam = URI.file('/test/project/test.txt');\n",
"\t\tassert.strictEqual(extname(uriWithQueryParam), '.txt');\n",
"\t\tassert.strictEqual(extname(uriWithoutQueryParam), '.txt');\n",
"\t});\n",
"});"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep"
],
"after_edit": [],
"file_path": "src/vs/base/test/common/resources.test.ts",
"type": "replace",
"edit_start_line_idx": 431
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as assert from 'assert';
import { toSlashes } from 'vs/base/common/extpath';
import { posix, win32 } from 'vs/base/common/path';
import { isWindows } from 'vs/base/common/platform';
import { addTrailingPathSeparator, basename, dirname, distinctParents, extname, extUri, extUriIgnorePathCase, hasTrailingPathSeparator, isAbsolutePath, joinPath, normalizePath, relativePath, removeTrailingPathSeparator, resolvePath } from 'vs/base/common/resources';
import { URI } from 'vs/base/common/uri';
suite('Resources', () => {
test('distinctParents', () => {
// Basic
let resources = [
URI.file('/some/folderA/file.txt'),
URI.file('/some/folderB/file.txt'),
URI.file('/some/folderC/file.txt')
];
let distinct = distinctParents(resources, r => r);
assert.strictEqual(distinct.length, 3);
assert.strictEqual(distinct[0].toString(), resources[0].toString());
assert.strictEqual(distinct[1].toString(), resources[1].toString());
assert.strictEqual(distinct[2].toString(), resources[2].toString());
// Parent / Child
resources = [
URI.file('/some/folderA'),
URI.file('/some/folderA/file.txt'),
URI.file('/some/folderA/child/file.txt'),
URI.file('/some/folderA2/file.txt'),
URI.file('/some/file.txt')
];
distinct = distinctParents(resources, r => r);
assert.strictEqual(distinct.length, 3);
assert.strictEqual(distinct[0].toString(), resources[0].toString());
assert.strictEqual(distinct[1].toString(), resources[3].toString());
assert.strictEqual(distinct[2].toString(), resources[4].toString());
});
test('dirname', () => {
if (isWindows) {
assert.strictEqual(dirname(URI.file('c:\\some\\file\\test.txt')).toString(), 'file:///c%3A/some/file');
assert.strictEqual(dirname(URI.file('c:\\some\\file')).toString(), 'file:///c%3A/some');
assert.strictEqual(dirname(URI.file('c:\\some\\file\\')).toString(), 'file:///c%3A/some');
assert.strictEqual(dirname(URI.file('c:\\some')).toString(), 'file:///c%3A/');
assert.strictEqual(dirname(URI.file('C:\\some')).toString(), 'file:///c%3A/');
assert.strictEqual(dirname(URI.file('c:\\')).toString(), 'file:///c%3A/');
} else {
assert.strictEqual(dirname(URI.file('/some/file/test.txt')).toString(), 'file:///some/file');
assert.strictEqual(dirname(URI.file('/some/file/')).toString(), 'file:///some');
assert.strictEqual(dirname(URI.file('/some/file')).toString(), 'file:///some');
}
assert.strictEqual(dirname(URI.parse('foo://a/some/file/test.txt')).toString(), 'foo://a/some/file');
assert.strictEqual(dirname(URI.parse('foo://a/some/file/')).toString(), 'foo://a/some');
assert.strictEqual(dirname(URI.parse('foo://a/some/file')).toString(), 'foo://a/some');
assert.strictEqual(dirname(URI.parse('foo://a/some')).toString(), 'foo://a/');
assert.strictEqual(dirname(URI.parse('foo://a/')).toString(), 'foo://a/');
assert.strictEqual(dirname(URI.parse('foo://a')).toString(), 'foo://a');
// does not explode (https://github.com/microsoft/vscode/issues/41987)
dirname(URI.from({ scheme: 'file', authority: '/users/someone/portal.h' }));
assert.strictEqual(dirname(URI.parse('foo://a/b/c?q')).toString(), 'foo://a/b?q');
});
test('basename', () => {
if (isWindows) {
assert.strictEqual(basename(URI.file('c:\\some\\file\\test.txt')), 'test.txt');
assert.strictEqual(basename(URI.file('c:\\some\\file')), 'file');
assert.strictEqual(basename(URI.file('c:\\some\\file\\')), 'file');
assert.strictEqual(basename(URI.file('C:\\some\\file\\')), 'file');
} else {
assert.strictEqual(basename(URI.file('/some/file/test.txt')), 'test.txt');
assert.strictEqual(basename(URI.file('/some/file/')), 'file');
assert.strictEqual(basename(URI.file('/some/file')), 'file');
assert.strictEqual(basename(URI.file('/some')), 'some');
}
assert.strictEqual(basename(URI.parse('foo://a/some/file/test.txt')), 'test.txt');
assert.strictEqual(basename(URI.parse('foo://a/some/file/')), 'file');
assert.strictEqual(basename(URI.parse('foo://a/some/file')), 'file');
assert.strictEqual(basename(URI.parse('foo://a/some')), 'some');
assert.strictEqual(basename(URI.parse('foo://a/')), '');
assert.strictEqual(basename(URI.parse('foo://a')), '');
});
test('joinPath', () => {
if (isWindows) {
assert.strictEqual(joinPath(URI.file('c:\\foo\\bar'), '/file.js').toString(), 'file:///c%3A/foo/bar/file.js');
assert.strictEqual(joinPath(URI.file('c:\\foo\\bar\\'), 'file.js').toString(), 'file:///c%3A/foo/bar/file.js');
assert.strictEqual(joinPath(URI.file('c:\\foo\\bar\\'), '/file.js').toString(), 'file:///c%3A/foo/bar/file.js');
assert.strictEqual(joinPath(URI.file('c:\\'), '/file.js').toString(), 'file:///c%3A/file.js');
assert.strictEqual(joinPath(URI.file('c:\\'), 'bar/file.js').toString(), 'file:///c%3A/bar/file.js');
assert.strictEqual(joinPath(URI.file('c:\\foo'), './file.js').toString(), 'file:///c%3A/foo/file.js');
assert.strictEqual(joinPath(URI.file('c:\\foo'), '/./file.js').toString(), 'file:///c%3A/foo/file.js');
assert.strictEqual(joinPath(URI.file('C:\\foo'), '../file.js').toString(), 'file:///c%3A/file.js');
assert.strictEqual(joinPath(URI.file('C:\\foo\\.'), '../file.js').toString(), 'file:///c%3A/file.js');
} else {
assert.strictEqual(joinPath(URI.file('/foo/bar'), '/file.js').toString(), 'file:///foo/bar/file.js');
assert.strictEqual(joinPath(URI.file('/foo/bar'), 'file.js').toString(), 'file:///foo/bar/file.js');
assert.strictEqual(joinPath(URI.file('/foo/bar/'), '/file.js').toString(), 'file:///foo/bar/file.js');
assert.strictEqual(joinPath(URI.file('/'), '/file.js').toString(), 'file:///file.js');
assert.strictEqual(joinPath(URI.file('/foo/bar'), './file.js').toString(), 'file:///foo/bar/file.js');
assert.strictEqual(joinPath(URI.file('/foo/bar'), '/./file.js').toString(), 'file:///foo/bar/file.js');
assert.strictEqual(joinPath(URI.file('/foo/bar'), '../file.js').toString(), 'file:///foo/file.js');
}
assert.strictEqual(joinPath(URI.parse('foo://a/foo/bar')).toString(), 'foo://a/foo/bar');
assert.strictEqual(joinPath(URI.parse('foo://a/foo/bar'), '/file.js').toString(), 'foo://a/foo/bar/file.js');
assert.strictEqual(joinPath(URI.parse('foo://a/foo/bar'), 'file.js').toString(), 'foo://a/foo/bar/file.js');
assert.strictEqual(joinPath(URI.parse('foo://a/foo/bar/'), '/file.js').toString(), 'foo://a/foo/bar/file.js');
assert.strictEqual(joinPath(URI.parse('foo://a/'), '/file.js').toString(), 'foo://a/file.js');
assert.strictEqual(joinPath(URI.parse('foo://a/foo/bar/'), './file.js').toString(), 'foo://a/foo/bar/file.js');
assert.strictEqual(joinPath(URI.parse('foo://a/foo/bar/'), '/./file.js').toString(), 'foo://a/foo/bar/file.js');
assert.strictEqual(joinPath(URI.parse('foo://a/foo/bar/'), '../file.js').toString(), 'foo://a/foo/file.js');
assert.strictEqual(
joinPath(URI.from({ scheme: 'myScheme', authority: 'authority', path: '/path', query: 'query', fragment: 'fragment' }), '/file.js').toString(),
'myScheme://authority/path/file.js?query#fragment');
});
test('normalizePath', () => {
if (isWindows) {
assert.strictEqual(normalizePath(URI.file('c:\\foo\\.\\bar')).toString(), 'file:///c%3A/foo/bar');
assert.strictEqual(normalizePath(URI.file('c:\\foo\\.')).toString(), 'file:///c%3A/foo');
assert.strictEqual(normalizePath(URI.file('c:\\foo\\.\\')).toString(), 'file:///c%3A/foo/');
assert.strictEqual(normalizePath(URI.file('c:\\foo\\..')).toString(), 'file:///c%3A/');
assert.strictEqual(normalizePath(URI.file('c:\\foo\\..\\bar')).toString(), 'file:///c%3A/bar');
assert.strictEqual(normalizePath(URI.file('c:\\foo\\..\\..\\bar')).toString(), 'file:///c%3A/bar');
assert.strictEqual(normalizePath(URI.file('c:\\foo\\foo\\..\\..\\bar')).toString(), 'file:///c%3A/bar');
assert.strictEqual(normalizePath(URI.file('C:\\foo\\foo\\.\\..\\..\\bar')).toString(), 'file:///c%3A/bar');
assert.strictEqual(normalizePath(URI.file('C:\\foo\\foo\\.\\..\\some\\..\\bar')).toString(), 'file:///c%3A/foo/bar');
} else {
assert.strictEqual(normalizePath(URI.file('/foo/./bar')).toString(), 'file:///foo/bar');
assert.strictEqual(normalizePath(URI.file('/foo/.')).toString(), 'file:///foo');
assert.strictEqual(normalizePath(URI.file('/foo/./')).toString(), 'file:///foo/');
assert.strictEqual(normalizePath(URI.file('/foo/..')).toString(), 'file:///');
assert.strictEqual(normalizePath(URI.file('/foo/../bar')).toString(), 'file:///bar');
assert.strictEqual(normalizePath(URI.file('/foo/../../bar')).toString(), 'file:///bar');
assert.strictEqual(normalizePath(URI.file('/foo/foo/../../bar')).toString(), 'file:///bar');
assert.strictEqual(normalizePath(URI.file('/foo/foo/./../../bar')).toString(), 'file:///bar');
assert.strictEqual(normalizePath(URI.file('/foo/foo/./../some/../bar')).toString(), 'file:///foo/bar');
assert.strictEqual(normalizePath(URI.file('/f')).toString(), 'file:///f');
}
assert.strictEqual(normalizePath(URI.parse('foo://a/foo/./bar')).toString(), 'foo://a/foo/bar');
assert.strictEqual(normalizePath(URI.parse('foo://a/foo/.')).toString(), 'foo://a/foo');
assert.strictEqual(normalizePath(URI.parse('foo://a/foo/./')).toString(), 'foo://a/foo/');
assert.strictEqual(normalizePath(URI.parse('foo://a/foo/..')).toString(), 'foo://a/');
assert.strictEqual(normalizePath(URI.parse('foo://a/foo/../bar')).toString(), 'foo://a/bar');
assert.strictEqual(normalizePath(URI.parse('foo://a/foo/../../bar')).toString(), 'foo://a/bar');
assert.strictEqual(normalizePath(URI.parse('foo://a/foo/foo/../../bar')).toString(), 'foo://a/bar');
assert.strictEqual(normalizePath(URI.parse('foo://a/foo/foo/./../../bar')).toString(), 'foo://a/bar');
assert.strictEqual(normalizePath(URI.parse('foo://a/foo/foo/./../some/../bar')).toString(), 'foo://a/foo/bar');
assert.strictEqual(normalizePath(URI.parse('foo://a')).toString(), 'foo://a');
assert.strictEqual(normalizePath(URI.parse('foo://a/')).toString(), 'foo://a/');
assert.strictEqual(normalizePath(URI.parse('foo://a/foo/./bar?q=1')).toString(), URI.parse('foo://a/foo/bar?q%3D1').toString());
});
test('isAbsolute', () => {
if (isWindows) {
assert.strictEqual(isAbsolutePath(URI.file('c:\\foo\\')), true);
assert.strictEqual(isAbsolutePath(URI.file('C:\\foo\\')), true);
assert.strictEqual(isAbsolutePath(URI.file('bar')), true); // URI normalizes all file URIs to be absolute
} else {
assert.strictEqual(isAbsolutePath(URI.file('/foo/bar')), true);
assert.strictEqual(isAbsolutePath(URI.file('bar')), true); // URI normalizes all file URIs to be absolute
}
assert.strictEqual(isAbsolutePath(URI.parse('foo:foo')), false);
assert.strictEqual(isAbsolutePath(URI.parse('foo://a/foo/.')), true);
});
function assertTrailingSeparator(u1: URI, expected: boolean) {
assert.strictEqual(hasTrailingPathSeparator(u1), expected, u1.toString());
}
function assertRemoveTrailingSeparator(u1: URI, expected: URI) {
assertEqualURI(removeTrailingPathSeparator(u1), expected, u1.toString());
}
function assertAddTrailingSeparator(u1: URI, expected: URI) {
assertEqualURI(addTrailingPathSeparator(u1), expected, u1.toString());
}
test('trailingPathSeparator', () => {
assertTrailingSeparator(URI.parse('foo://a/foo'), false);
assertTrailingSeparator(URI.parse('foo://a/foo/'), true);
assertTrailingSeparator(URI.parse('foo://a/'), false);
assertTrailingSeparator(URI.parse('foo://a'), false);
assertRemoveTrailingSeparator(URI.parse('foo://a/foo'), URI.parse('foo://a/foo'));
assertRemoveTrailingSeparator(URI.parse('foo://a/foo/'), URI.parse('foo://a/foo'));
assertRemoveTrailingSeparator(URI.parse('foo://a/'), URI.parse('foo://a/'));
assertRemoveTrailingSeparator(URI.parse('foo://a'), URI.parse('foo://a'));
assertAddTrailingSeparator(URI.parse('foo://a/foo'), URI.parse('foo://a/foo/'));
assertAddTrailingSeparator(URI.parse('foo://a/foo/'), URI.parse('foo://a/foo/'));
assertAddTrailingSeparator(URI.parse('foo://a/'), URI.parse('foo://a/'));
assertAddTrailingSeparator(URI.parse('foo://a'), URI.parse('foo://a/'));
if (isWindows) {
assertTrailingSeparator(URI.file('c:\\a\\foo'), false);
assertTrailingSeparator(URI.file('c:\\a\\foo\\'), true);
assertTrailingSeparator(URI.file('c:\\'), false);
assertTrailingSeparator(URI.file('\\\\server\\share\\some\\'), true);
assertTrailingSeparator(URI.file('\\\\server\\share\\'), false);
assertRemoveTrailingSeparator(URI.file('c:\\a\\foo'), URI.file('c:\\a\\foo'));
assertRemoveTrailingSeparator(URI.file('c:\\a\\foo\\'), URI.file('c:\\a\\foo'));
assertRemoveTrailingSeparator(URI.file('c:\\'), URI.file('c:\\'));
assertRemoveTrailingSeparator(URI.file('\\\\server\\share\\some\\'), URI.file('\\\\server\\share\\some'));
assertRemoveTrailingSeparator(URI.file('\\\\server\\share\\'), URI.file('\\\\server\\share\\'));
assertAddTrailingSeparator(URI.file('c:\\a\\foo'), URI.file('c:\\a\\foo\\'));
assertAddTrailingSeparator(URI.file('c:\\a\\foo\\'), URI.file('c:\\a\\foo\\'));
assertAddTrailingSeparator(URI.file('c:\\'), URI.file('c:\\'));
assertAddTrailingSeparator(URI.file('\\\\server\\share\\some'), URI.file('\\\\server\\share\\some\\'));
assertAddTrailingSeparator(URI.file('\\\\server\\share\\some\\'), URI.file('\\\\server\\share\\some\\'));
} else {
assertTrailingSeparator(URI.file('/foo/bar'), false);
assertTrailingSeparator(URI.file('/foo/bar/'), true);
assertTrailingSeparator(URI.file('/'), false);
assertRemoveTrailingSeparator(URI.file('/foo/bar'), URI.file('/foo/bar'));
assertRemoveTrailingSeparator(URI.file('/foo/bar/'), URI.file('/foo/bar'));
assertRemoveTrailingSeparator(URI.file('/'), URI.file('/'));
assertAddTrailingSeparator(URI.file('/foo/bar'), URI.file('/foo/bar/'));
assertAddTrailingSeparator(URI.file('/foo/bar/'), URI.file('/foo/bar/'));
assertAddTrailingSeparator(URI.file('/'), URI.file('/'));
}
});
function assertEqualURI(actual: URI, expected: URI, message?: string, ignoreCase?: boolean) {
let util = ignoreCase ? extUriIgnorePathCase : extUri;
if (!util.isEqual(expected, actual)) {
assert.strictEqual(actual.toString(), expected.toString(), message);
}
}
function assertRelativePath(u1: URI, u2: URI, expectedPath: string | undefined, ignoreJoin?: boolean, ignoreCase?: boolean) {
let util = ignoreCase ? extUriIgnorePathCase : extUri;
assert.strictEqual(util.relativePath(u1, u2), expectedPath, `from ${u1.toString()} to ${u2.toString()}`);
if (expectedPath !== undefined && !ignoreJoin) {
assertEqualURI(removeTrailingPathSeparator(joinPath(u1, expectedPath)), removeTrailingPathSeparator(u2), 'joinPath on relativePath should be equal', ignoreCase);
}
}
test('relativePath', () => {
assertRelativePath(URI.parse('foo://a/foo'), URI.parse('foo://a/foo/bar'), 'bar');
assertRelativePath(URI.parse('foo://a/foo'), URI.parse('foo://a/foo/bar/'), 'bar');
assertRelativePath(URI.parse('foo://a/foo'), URI.parse('foo://a/foo/bar/goo'), 'bar/goo');
assertRelativePath(URI.parse('foo://a/'), URI.parse('foo://a/foo/bar/goo'), 'foo/bar/goo');
assertRelativePath(URI.parse('foo://a/foo/xoo'), URI.parse('foo://a/foo/bar'), '../bar');
assertRelativePath(URI.parse('foo://a/foo/xoo/yoo'), URI.parse('foo://a'), '../../..', true);
assertRelativePath(URI.parse('foo://a/foo'), URI.parse('foo://a/foo/'), '');
assertRelativePath(URI.parse('foo://a/foo/'), URI.parse('foo://a/foo'), '');
assertRelativePath(URI.parse('foo://a/foo/'), URI.parse('foo://a/foo/'), '');
assertRelativePath(URI.parse('foo://a/foo'), URI.parse('foo://a/foo'), '');
assertRelativePath(URI.parse('foo://a'), URI.parse('foo://a'), '', true);
assertRelativePath(URI.parse('foo://a/'), URI.parse('foo://a/'), '');
assertRelativePath(URI.parse('foo://a/'), URI.parse('foo://a'), '', true);
assertRelativePath(URI.parse('foo://a/foo?q'), URI.parse('foo://a/foo/bar#h'), 'bar', true);
assertRelativePath(URI.parse('foo://'), URI.parse('foo://a/b'), undefined);
assertRelativePath(URI.parse('foo://a2/b'), URI.parse('foo://a/b'), undefined);
assertRelativePath(URI.parse('goo://a/b'), URI.parse('foo://a/b'), undefined);
assertRelativePath(URI.parse('foo://a/foo'), URI.parse('foo://A/FOO/bar/goo'), 'bar/goo', false, true);
assertRelativePath(URI.parse('foo://a/foo'), URI.parse('foo://A/FOO/BAR/GOO'), 'BAR/GOO', false, true);
assertRelativePath(URI.parse('foo://a/foo/xoo'), URI.parse('foo://A/FOO/BAR/GOO'), '../BAR/GOO', false, true);
assertRelativePath(URI.parse('foo:///c:/a/foo'), URI.parse('foo:///C:/a/foo/xoo/'), 'xoo', false, true);
if (isWindows) {
assertRelativePath(URI.file('c:\\foo\\bar'), URI.file('c:\\foo\\bar'), '');
assertRelativePath(URI.file('c:\\foo\\bar\\huu'), URI.file('c:\\foo\\bar'), '..');
assertRelativePath(URI.file('c:\\foo\\bar\\a1\\a2'), URI.file('c:\\foo\\bar'), '../..');
assertRelativePath(URI.file('c:\\foo\\bar\\'), URI.file('c:\\foo\\bar\\a1\\a2'), 'a1/a2');
assertRelativePath(URI.file('c:\\foo\\bar\\'), URI.file('c:\\foo\\bar\\a1\\a2\\'), 'a1/a2');
assertRelativePath(URI.file('c:\\'), URI.file('c:\\foo\\bar'), 'foo/bar');
assertRelativePath(URI.file('\\\\server\\share\\some\\'), URI.file('\\\\server\\share\\some\\path'), 'path');
assertRelativePath(URI.file('\\\\server\\share\\some\\'), URI.file('\\\\server\\share2\\some\\path'), '../../share2/some/path', true); // ignore joinPath assert: path.join is not root aware
} else {
assertRelativePath(URI.file('/a/foo'), URI.file('/a/foo/bar'), 'bar');
assertRelativePath(URI.file('/a/foo'), URI.file('/a/foo/bar/'), 'bar');
assertRelativePath(URI.file('/a/foo'), URI.file('/a/foo/bar/goo'), 'bar/goo');
assertRelativePath(URI.file('/a/'), URI.file('/a/foo/bar/goo'), 'foo/bar/goo');
assertRelativePath(URI.file('/'), URI.file('/a/foo/bar/goo'), 'a/foo/bar/goo');
assertRelativePath(URI.file('/a/foo/xoo'), URI.file('/a/foo/bar'), '../bar');
assertRelativePath(URI.file('/a/foo/xoo/yoo'), URI.file('/a'), '../../..');
assertRelativePath(URI.file('/a/foo'), URI.file('/a/foo/'), '');
assertRelativePath(URI.file('/a/foo'), URI.file('/b/foo/'), '../../b/foo');
}
});
function assertResolve(u1: URI, path: string, expected: URI) {
const actual = resolvePath(u1, path);
assertEqualURI(actual, expected, `from ${u1.toString()} and ${path}`);
const p = path.indexOf('/') !== -1 ? posix : win32;
if (!p.isAbsolute(path)) {
let expectedPath = isWindows ? toSlashes(path) : path;
expectedPath = expectedPath.startsWith('./') ? expectedPath.substr(2) : expectedPath;
assert.strictEqual(relativePath(u1, actual), expectedPath, `relativePath (${u1.toString()}) on actual (${actual.toString()}) should be to path (${expectedPath})`);
}
}
test('resolve', () => {
if (isWindows) {
assertResolve(URI.file('c:\\foo\\bar'), 'file.js', URI.file('c:\\foo\\bar\\file.js'));
assertResolve(URI.file('c:\\foo\\bar'), 't\\file.js', URI.file('c:\\foo\\bar\\t\\file.js'));
assertResolve(URI.file('c:\\foo\\bar'), '.\\t\\file.js', URI.file('c:\\foo\\bar\\t\\file.js'));
assertResolve(URI.file('c:\\foo\\bar'), 'a1/file.js', URI.file('c:\\foo\\bar\\a1\\file.js'));
assertResolve(URI.file('c:\\foo\\bar'), './a1/file.js', URI.file('c:\\foo\\bar\\a1\\file.js'));
assertResolve(URI.file('c:\\foo\\bar'), '\\b1\\file.js', URI.file('c:\\b1\\file.js'));
assertResolve(URI.file('c:\\foo\\bar'), '/b1/file.js', URI.file('c:\\b1\\file.js'));
assertResolve(URI.file('c:\\foo\\bar\\'), 'file.js', URI.file('c:\\foo\\bar\\file.js'));
assertResolve(URI.file('c:\\'), 'file.js', URI.file('c:\\file.js'));
assertResolve(URI.file('c:\\'), '\\b1\\file.js', URI.file('c:\\b1\\file.js'));
assertResolve(URI.file('c:\\'), '/b1/file.js', URI.file('c:\\b1\\file.js'));
assertResolve(URI.file('c:\\'), 'd:\\foo\\bar.txt', URI.file('d:\\foo\\bar.txt'));
assertResolve(URI.file('\\\\server\\share\\some\\'), 'b1\\file.js', URI.file('\\\\server\\share\\some\\b1\\file.js'));
assertResolve(URI.file('\\\\server\\share\\some\\'), '\\file.js', URI.file('\\\\server\\share\\file.js'));
assertResolve(URI.file('c:\\'), '\\\\server\\share\\some\\', URI.file('\\\\server\\share\\some'));
assertResolve(URI.file('\\\\server\\share\\some\\'), 'c:\\', URI.file('c:\\'));
} else {
assertResolve(URI.file('/foo/bar'), 'file.js', URI.file('/foo/bar/file.js'));
assertResolve(URI.file('/foo/bar'), './file.js', URI.file('/foo/bar/file.js'));
assertResolve(URI.file('/foo/bar'), '/file.js', URI.file('/file.js'));
assertResolve(URI.file('/foo/bar/'), 'file.js', URI.file('/foo/bar/file.js'));
assertResolve(URI.file('/'), 'file.js', URI.file('/file.js'));
assertResolve(URI.file(''), './file.js', URI.file('/file.js'));
assertResolve(URI.file(''), '/file.js', URI.file('/file.js'));
}
assertResolve(URI.parse('foo://server/foo/bar'), 'file.js', URI.parse('foo://server/foo/bar/file.js'));
assertResolve(URI.parse('foo://server/foo/bar'), './file.js', URI.parse('foo://server/foo/bar/file.js'));
assertResolve(URI.parse('foo://server/foo/bar'), './file.js', URI.parse('foo://server/foo/bar/file.js'));
assertResolve(URI.parse('foo://server/foo/bar'), 'c:\\a1\\b1', URI.parse('foo://server/c:/a1/b1'));
assertResolve(URI.parse('foo://server/foo/bar'), 'c:\\', URI.parse('foo://server/c:'));
});
function assertIsEqual(u1: URI, u2: URI, ignoreCase: boolean | undefined, expected: boolean) {
let util = ignoreCase ? extUriIgnorePathCase : extUri;
assert.strictEqual(util.isEqual(u1, u2), expected, `${u1.toString()}${expected ? '===' : '!=='}${u2.toString()}`);
assert.strictEqual(util.compare(u1, u2) === 0, expected);
assert.strictEqual(util.getComparisonKey(u1) === util.getComparisonKey(u2), expected, `comparison keys ${u1.toString()}, ${u2.toString()}`);
assert.strictEqual(util.isEqualOrParent(u1, u2), expected, `isEqualOrParent ${u1.toString()}, ${u2.toString()}`);
if (!ignoreCase) {
assert.strictEqual(u1.toString() === u2.toString(), expected);
}
}
test('isEqual', () => {
let fileURI = isWindows ? URI.file('c:\\foo\\bar') : URI.file('/foo/bar');
let fileURI2 = isWindows ? URI.file('C:\\foo\\Bar') : URI.file('/foo/Bar');
assertIsEqual(fileURI, fileURI, true, true);
assertIsEqual(fileURI, fileURI, false, true);
assertIsEqual(fileURI, fileURI, undefined, true);
assertIsEqual(fileURI, fileURI2, true, true);
assertIsEqual(fileURI, fileURI2, false, false);
let fileURI3 = URI.parse('foo://server:453/foo/bar');
let fileURI4 = URI.parse('foo://server:453/foo/Bar');
assertIsEqual(fileURI3, fileURI3, true, true);
assertIsEqual(fileURI3, fileURI3, false, true);
assertIsEqual(fileURI3, fileURI3, undefined, true);
assertIsEqual(fileURI3, fileURI4, true, true);
assertIsEqual(fileURI3, fileURI4, false, false);
assertIsEqual(fileURI, fileURI3, true, false);
assertIsEqual(URI.parse('file://server'), URI.parse('file://server/'), true, true);
assertIsEqual(URI.parse('http://server'), URI.parse('http://server/'), true, true);
assertIsEqual(URI.parse('foo://server'), URI.parse('foo://server/'), true, false); // only selected scheme have / as the default path
assertIsEqual(URI.parse('foo://server/foo'), URI.parse('foo://server/foo/'), true, false);
assertIsEqual(URI.parse('foo://server/foo'), URI.parse('foo://server/foo?'), true, true);
let fileURI5 = URI.parse('foo://server:453/foo/bar?q=1');
let fileURI6 = URI.parse('foo://server:453/foo/bar#xy');
assertIsEqual(fileURI5, fileURI5, true, true);
assertIsEqual(fileURI5, fileURI3, true, false);
assertIsEqual(fileURI6, fileURI6, true, true);
assertIsEqual(fileURI6, fileURI5, true, false);
assertIsEqual(fileURI6, fileURI3, true, false);
});
test('isEqualOrParent', () => {
let fileURI = isWindows ? URI.file('c:\\foo\\bar') : URI.file('/foo/bar');
let fileURI2 = isWindows ? URI.file('c:\\foo') : URI.file('/foo');
let fileURI2b = isWindows ? URI.file('C:\\Foo\\') : URI.file('/Foo/');
assert.strictEqual(extUriIgnorePathCase.isEqualOrParent(fileURI, fileURI), true, '1');
assert.strictEqual(extUri.isEqualOrParent(fileURI, fileURI), true, '2');
assert.strictEqual(extUriIgnorePathCase.isEqualOrParent(fileURI, fileURI2), true, '3');
assert.strictEqual(extUri.isEqualOrParent(fileURI, fileURI2), true, '4');
assert.strictEqual(extUriIgnorePathCase.isEqualOrParent(fileURI, fileURI2b), true, '5');
assert.strictEqual(extUri.isEqualOrParent(fileURI, fileURI2b), false, '6');
assert.strictEqual(extUri.isEqualOrParent(fileURI2, fileURI), false, '7');
assert.strictEqual(extUriIgnorePathCase.isEqualOrParent(fileURI2b, fileURI2), true, '8');
let fileURI3 = URI.parse('foo://server:453/foo/bar/goo');
let fileURI4 = URI.parse('foo://server:453/foo/');
let fileURI5 = URI.parse('foo://server:453/foo');
assert.strictEqual(extUriIgnorePathCase.isEqualOrParent(fileURI3, fileURI3, true), true, '11');
assert.strictEqual(extUri.isEqualOrParent(fileURI3, fileURI3), true, '12');
assert.strictEqual(extUriIgnorePathCase.isEqualOrParent(fileURI3, fileURI4, true), true, '13');
assert.strictEqual(extUri.isEqualOrParent(fileURI3, fileURI4), true, '14');
assert.strictEqual(extUriIgnorePathCase.isEqualOrParent(fileURI3, fileURI, true), false, '15');
assert.strictEqual(extUriIgnorePathCase.isEqualOrParent(fileURI5, fileURI5, true), true, '16');
let fileURI6 = URI.parse('foo://server:453/foo?q=1');
let fileURI7 = URI.parse('foo://server:453/foo/bar?q=1');
assert.strictEqual(extUriIgnorePathCase.isEqualOrParent(fileURI6, fileURI5), false, '17');
assert.strictEqual(extUriIgnorePathCase.isEqualOrParent(fileURI6, fileURI6), true, '18');
assert.strictEqual(extUriIgnorePathCase.isEqualOrParent(fileURI7, fileURI6), true, '19');
assert.strictEqual(extUriIgnorePathCase.isEqualOrParent(fileURI7, fileURI5), false, '20');
});
test('query parameters stripped from extname', () => {
const uriWithQueryParam = URI.file('/test/project/test.txt?q=1');
const uriWithoutQueryParam = URI.file('/test/project/test.txt');
assert.strictEqual(extname(uriWithQueryParam), '.txt');
assert.strictEqual(extname(uriWithoutQueryParam), '.txt');
});
});
| src/vs/base/test/common/resources.test.ts | 1 | https://github.com/microsoft/vscode/commit/c4fe803132ea8cd9aa903a83d7c5786ac77897b3 | [
0.9979889392852783,
0.03133287653326988,
0.0001608897146070376,
0.0001684958697296679,
0.15551534295082092
] |
{
"id": 2,
"code_window": [
"\t\tassert.strictEqual(extUriIgnorePathCase.isEqualOrParent(fileURI6, fileURI5), false, '17');\n",
"\t\tassert.strictEqual(extUriIgnorePathCase.isEqualOrParent(fileURI6, fileURI6), true, '18');\n",
"\t\tassert.strictEqual(extUriIgnorePathCase.isEqualOrParent(fileURI7, fileURI6), true, '19');\n",
"\t\tassert.strictEqual(extUriIgnorePathCase.isEqualOrParent(fileURI7, fileURI5), false, '20');\n",
"\t});\n",
"\n",
"\ttest('query parameters stripped from extname', () => {\n",
"\t\tconst uriWithQueryParam = URI.file('/test/project/test.txt?q=1');\n",
"\t\tconst uriWithoutQueryParam = URI.file('/test/project/test.txt');\n",
"\t\tassert.strictEqual(extname(uriWithQueryParam), '.txt');\n",
"\t\tassert.strictEqual(extname(uriWithoutQueryParam), '.txt');\n",
"\t});\n",
"});"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep"
],
"after_edit": [],
"file_path": "src/vs/base/test/common/resources.test.ts",
"type": "replace",
"edit_start_line_idx": 431
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { registerSingleton } from 'vs/platform/instantiation/common/extensions';
import { IEncryptionService } from 'vs/workbench/services/encryption/common/encryptionService';
export class EncryptionService {
declare readonly _serviceBrand: undefined;
encrypt(value: string): Promise<string> {
return Promise.resolve(value);
}
decrypt(value: string): Promise<string> {
return Promise.resolve(value);
}
}
registerSingleton(IEncryptionService, EncryptionService, true);
| src/vs/workbench/services/encryption/browser/encryptionService.ts | 0 | https://github.com/microsoft/vscode/commit/c4fe803132ea8cd9aa903a83d7c5786ac77897b3 | [
0.00017264643975067884,
0.00016971050354186445,
0.00016449195391032845,
0.00017199316062033176,
0.0000036997075767430943
] |
{
"id": 2,
"code_window": [
"\t\tassert.strictEqual(extUriIgnorePathCase.isEqualOrParent(fileURI6, fileURI5), false, '17');\n",
"\t\tassert.strictEqual(extUriIgnorePathCase.isEqualOrParent(fileURI6, fileURI6), true, '18');\n",
"\t\tassert.strictEqual(extUriIgnorePathCase.isEqualOrParent(fileURI7, fileURI6), true, '19');\n",
"\t\tassert.strictEqual(extUriIgnorePathCase.isEqualOrParent(fileURI7, fileURI5), false, '20');\n",
"\t});\n",
"\n",
"\ttest('query parameters stripped from extname', () => {\n",
"\t\tconst uriWithQueryParam = URI.file('/test/project/test.txt?q=1');\n",
"\t\tconst uriWithoutQueryParam = URI.file('/test/project/test.txt');\n",
"\t\tassert.strictEqual(extname(uriWithQueryParam), '.txt');\n",
"\t\tassert.strictEqual(extname(uriWithoutQueryParam), '.txt');\n",
"\t});\n",
"});"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep"
],
"after_edit": [],
"file_path": "src/vs/base/test/common/resources.test.ts",
"type": "replace",
"edit_start_line_idx": 431
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { INotebookEditor, CellFindMatch, CellEditState, CellFindMatchWithIndex } from 'vs/workbench/contrib/notebook/browser/notebookBrowser';
import { Range } from 'vs/editor/common/core/range';
import { FindDecorations } from 'vs/editor/contrib/find/findDecorations';
import { ModelDecorationOptions } from 'vs/editor/common/model/textModel';
import { IModelDeltaDecoration } from 'vs/editor/common/model';
import { ICellModelDeltaDecorations, ICellModelDecorations } from 'vs/workbench/contrib/notebook/browser/viewModel/notebookViewModel';
import { PrefixSumComputer } from 'vs/editor/common/viewModel/prefixSumComputer';
import { FindReplaceState } from 'vs/editor/contrib/find/findState';
import { CellKind, INotebookSearchOptions, NotebookCellsChangeType } from 'vs/workbench/contrib/notebook/common/notebookCommon';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { Disposable, DisposableStore } from 'vs/base/common/lifecycle';
import { findFirstInSorted } from 'vs/base/common/arrays';
import { NotebookTextModel } from 'vs/workbench/contrib/notebook/common/model/notebookTextModel';
export class FindModel extends Disposable {
private _findMatches: CellFindMatch[] = [];
protected _findMatchesStarts: PrefixSumComputer | null = null;
private _currentMatch: number = -1;
private _allMatchesDecorations: ICellModelDecorations[] = [];
private _currentMatchDecorations: ICellModelDecorations[] = [];
private readonly _modelDisposable = this._register(new DisposableStore());
get findMatches() {
return this._findMatches;
}
get currentMatch() {
return this._currentMatch;
}
constructor(
private readonly _notebookEditor: INotebookEditor,
private readonly _state: FindReplaceState,
@IConfigurationService private readonly _configurationService: IConfigurationService
) {
super();
this._register(_state.onFindReplaceStateChange(e => {
if (e.searchString || (e.isRevealed && this._state.isRevealed)) {
this.research();
}
if (e.isRevealed && !this._state.isRevealed) {
this.clear();
}
}));
this._register(this._notebookEditor.onDidChangeModel(e => {
this._registerModelListener(e);
}));
if (this._notebookEditor.hasModel()) {
this._registerModelListener(this._notebookEditor.textModel);
}
}
ensureFindMatches() {
if (!this._findMatchesStarts) {
this.set(this._findMatches, true);
}
}
getCurrentMatch() {
const nextIndex = this._findMatchesStarts!.getIndexOf(this._currentMatch);
const cell = this._findMatches[nextIndex.index].cell;
const match = this._findMatches[nextIndex.index].matches[nextIndex.remainder];
return {
cell,
match
};
}
find(previous: boolean) {
if (!this.findMatches.length) {
return;
}
// let currCell;
if (!this._findMatchesStarts) {
this.set(this._findMatches, true);
} else {
// const currIndex = this._findMatchesStarts!.getIndexOf(this._currentMatch);
// currCell = this._findMatches[currIndex.index].cell;
const totalVal = this._findMatchesStarts.getTotalSum();
if (this._currentMatch === -1) {
this._currentMatch = previous ? totalVal - 1 : 0;
} else {
const nextVal = (this._currentMatch + (previous ? -1 : 1) + totalVal) % totalVal;
this._currentMatch = nextVal;
}
}
const nextIndex = this._findMatchesStarts!.getIndexOf(this._currentMatch);
// const newFocusedCell = this._findMatches[nextIndex.index].cell;
this.setCurrentFindMatchDecoration(nextIndex.index, nextIndex.remainder);
this.revealCellRange(nextIndex.index, nextIndex.remainder);
this._state.changeMatchInfo(
this._currentMatch,
this._findMatches.reduce((p, c) => p + c.matches.length, 0),
undefined
);
}
private revealCellRange(cellIndex: number, matchIndex: number) {
this._findMatches[cellIndex].cell.updateEditState(CellEditState.Editing, 'find');
this._notebookEditor.focusElement(this._findMatches[cellIndex].cell);
this._notebookEditor.setCellEditorSelection(this._findMatches[cellIndex].cell, this._findMatches[cellIndex].matches[matchIndex].range);
this._notebookEditor.revealRangeInCenterIfOutsideViewportAsync(this._findMatches[cellIndex].cell, this._findMatches[cellIndex].matches[matchIndex].range);
}
private _registerModelListener(notebookTextModel?: NotebookTextModel) {
this._modelDisposable.clear();
if (notebookTextModel) {
this._modelDisposable.add(notebookTextModel.onDidChangeContent((e) => {
if (!e.rawEvents.some(event => event.kind === NotebookCellsChangeType.ChangeCellContent || event.kind === NotebookCellsChangeType.ModelChange)) {
return;
}
this.research();
}));
}
this.research();
}
research() {
if (!this._state.isRevealed) {
this.set([], false);
return;
}
const findMatches = this._getFindMatches();
if (!findMatches) {
return;
}
if (findMatches.length === 0) {
this.set([], false);
return;
}
if (this._currentMatch === -1) {
// no active current match
this.set(findMatches, false);
return;
}
const oldCurrIndex = this._findMatchesStarts!.getIndexOf(this._currentMatch);
const oldCurrCell = this._findMatches[oldCurrIndex.index].cell;
const oldCurrMatchCellIndex = this._notebookEditor.viewModel!.getCellIndex(oldCurrCell);
if (oldCurrMatchCellIndex < 0) {
// the cell containing the active match is deleted
const focusedCell = this._notebookEditor.viewModel!.viewCells[this._notebookEditor.viewModel!.getFocus().start];
if (!focusedCell) {
this.set(findMatches, false);
return;
}
const matchAfterSelection = findFirstInSorted(findMatches.map(match => match.index), index => index >= oldCurrMatchCellIndex);
this._updateCurrentMatch(findMatches, this._matchesCountBeforeIndex(findMatches, matchAfterSelection));
return;
}
// the cell still exist
const cell = this._notebookEditor.viewModel!.viewCells[oldCurrMatchCellIndex];
if (cell.cellKind === CellKind.Markup && cell.getEditState() === CellEditState.Preview) {
// find the nearest match above this cell
const matchAfterSelection = findFirstInSorted(findMatches.map(match => match.index), index => index >= oldCurrMatchCellIndex);
this._updateCurrentMatch(findMatches, this._matchesCountBeforeIndex(findMatches, matchAfterSelection));
return;
}
if ((cell.cellKind === CellKind.Markup && cell.getEditState() === CellEditState.Editing) || cell.cellKind === CellKind.Code) {
// check if there is monaco editor selection and find the first match, otherwise find the first match above current cell
// this._findMatches[cellIndex].matches[matchIndex].range
const currentMatchDecorationId = this._currentMatchDecorations.find(decoration => decoration.ownerId === cell.handle);
if (currentMatchDecorationId) {
const currMatchRangeInEditor = (cell.editorAttached && currentMatchDecorationId.decorations[0] ? cell.getCellDecorationRange(currentMatchDecorationId.decorations[0]) : null)
?? this._findMatches[oldCurrIndex.index].matches[oldCurrIndex.remainder].range;
// not attached, just use the range
const matchAfterSelection = findFirstInSorted(findMatches, match => match.index >= oldCurrMatchCellIndex) % findMatches.length;
if (findMatches[matchAfterSelection].index > oldCurrMatchCellIndex) {
// there is no search result in curr cell anymore
this._updateCurrentMatch(findMatches, this._matchesCountBeforeIndex(findMatches, matchAfterSelection));
} else {
// findMatches[matchAfterSelection].index === currMatchCellIndex
const cellMatch = findMatches[matchAfterSelection];
const matchAfterOldSelection = findFirstInSorted(cellMatch.matches, match => Range.compareRangesUsingStarts(match.range, currMatchRangeInEditor) >= 0);
this._updateCurrentMatch(findMatches, this._matchesCountBeforeIndex(findMatches, matchAfterSelection) + matchAfterOldSelection);
}
} else {
const matchAfterSelection = findFirstInSorted(findMatches.map(match => match.index), index => index >= oldCurrMatchCellIndex);
this._updateCurrentMatch(findMatches, this._matchesCountBeforeIndex(findMatches, matchAfterSelection));
}
return;
}
this.set(findMatches, false);
}
private set(cellFindMatches: CellFindMatch[] | null, autoStart: boolean): void {
if (!cellFindMatches || !cellFindMatches.length) {
this._findMatches = [];
this.setAllFindMatchesDecorations([]);
this.constructFindMatchesStarts();
this._currentMatch = -1;
this.clearCurrentFindMatchDecoration();
this._state.changeMatchInfo(
this._currentMatch,
this._findMatches.reduce((p, c) => p + c.matches.length, 0),
undefined
);
return;
}
// all matches
this._findMatches = cellFindMatches;
this.setAllFindMatchesDecorations(cellFindMatches || []);
// current match
this.constructFindMatchesStarts();
if (autoStart) {
this._currentMatch = 0;
this.setCurrentFindMatchDecoration(0, 0);
}
this._state.changeMatchInfo(
this._currentMatch,
this._findMatches.reduce((p, c) => p + c.matches.length, 0),
undefined
);
}
private _getFindMatches(): CellFindMatchWithIndex[] | null {
const val = this._state.searchString;
const wordSeparators = this._configurationService.inspect<string>('editor.wordSeparators').value;
const options: INotebookSearchOptions = { regex: this._state.isRegex, wholeWord: this._state.wholeWord, caseSensitive: this._state.matchCase, wordSeparators: wordSeparators };
if (!val) {
return null;
}
const findMatches = this._notebookEditor.viewModel!.find(val, options).filter(match => match.matches.length > 0);
return findMatches;
}
private _updateCurrentMatch(findMatches: CellFindMatchWithIndex[], currentMatchesPosition: number) {
this.set(findMatches, false);
this._currentMatch = currentMatchesPosition;
const nextIndex = this._findMatchesStarts!.getIndexOf(this._currentMatch);
this.setCurrentFindMatchDecoration(nextIndex.index, nextIndex.remainder);
this._state.changeMatchInfo(
this._currentMatch,
this._findMatches.reduce((p, c) => p + c.matches.length, 0),
undefined
);
}
private _matchesCountBeforeIndex(findMatches: CellFindMatchWithIndex[], index: number) {
let prevMatchesCount = 0;
for (let i = 0; i < index; i++) {
prevMatchesCount += findMatches[i].matches.length;
}
return prevMatchesCount;
}
private constructFindMatchesStarts() {
if (this._findMatches && this._findMatches.length) {
const values = new Uint32Array(this._findMatches.length);
for (let i = 0; i < this._findMatches.length; i++) {
values[i] = this._findMatches[i].matches.length;
}
this._findMatchesStarts = new PrefixSumComputer(values);
} else {
this._findMatchesStarts = null;
}
}
private setCurrentFindMatchDecoration(cellIndex: number, matchIndex: number) {
this._notebookEditor.changeModelDecorations(accessor => {
const findMatchesOptions: ModelDecorationOptions = FindDecorations._CURRENT_FIND_MATCH_DECORATION;
const cell = this._findMatches[cellIndex].cell;
const match = this._findMatches[cellIndex].matches[matchIndex];
const decorations: IModelDeltaDecoration[] = [
{ range: match.range, options: findMatchesOptions }
];
const deltaDecoration: ICellModelDeltaDecorations = {
ownerId: cell.handle,
decorations: decorations
};
this._currentMatchDecorations = accessor.deltaDecorations(this._currentMatchDecorations, [deltaDecoration]);
});
}
private clearCurrentFindMatchDecoration() {
this._notebookEditor.changeModelDecorations(accessor => {
this._currentMatchDecorations = accessor.deltaDecorations(this._currentMatchDecorations, []);
});
}
private setAllFindMatchesDecorations(cellFindMatches: CellFindMatch[]) {
this._notebookEditor.changeModelDecorations((accessor) => {
const findMatchesOptions: ModelDecorationOptions = FindDecorations._FIND_MATCH_DECORATION;
const deltaDecorations: ICellModelDeltaDecorations[] = cellFindMatches.map(cellFindMatch => {
const findMatches = cellFindMatch.matches;
// Find matches
const newFindMatchesDecorations: IModelDeltaDecoration[] = new Array<IModelDeltaDecoration>(findMatches.length);
for (let i = 0, len = findMatches.length; i < len; i++) {
newFindMatchesDecorations[i] = {
range: findMatches[i].range,
options: findMatchesOptions
};
}
return { ownerId: cellFindMatch.cell.handle, decorations: newFindMatchesDecorations };
});
this._allMatchesDecorations = accessor.deltaDecorations(this._allMatchesDecorations, deltaDecorations);
});
}
clear() {
this.set([], false);
}
}
| src/vs/workbench/contrib/notebook/browser/contrib/find/findModel.ts | 0 | https://github.com/microsoft/vscode/commit/c4fe803132ea8cd9aa903a83d7c5786ac77897b3 | [
0.0001747296773828566,
0.00017079072131309658,
0.00016247405437752604,
0.00017056227079592645,
0.00000218471473090176
] |
{
"id": 2,
"code_window": [
"\t\tassert.strictEqual(extUriIgnorePathCase.isEqualOrParent(fileURI6, fileURI5), false, '17');\n",
"\t\tassert.strictEqual(extUriIgnorePathCase.isEqualOrParent(fileURI6, fileURI6), true, '18');\n",
"\t\tassert.strictEqual(extUriIgnorePathCase.isEqualOrParent(fileURI7, fileURI6), true, '19');\n",
"\t\tassert.strictEqual(extUriIgnorePathCase.isEqualOrParent(fileURI7, fileURI5), false, '20');\n",
"\t});\n",
"\n",
"\ttest('query parameters stripped from extname', () => {\n",
"\t\tconst uriWithQueryParam = URI.file('/test/project/test.txt?q=1');\n",
"\t\tconst uriWithoutQueryParam = URI.file('/test/project/test.txt');\n",
"\t\tassert.strictEqual(extname(uriWithQueryParam), '.txt');\n",
"\t\tassert.strictEqual(extname(uriWithoutQueryParam), '.txt');\n",
"\t});\n",
"});"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep"
],
"after_edit": [],
"file_path": "src/vs/base/test/common/resources.test.ts",
"type": "replace",
"edit_start_line_idx": 431
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
export const testUrlMatchesGlob = (url: string, globUrl: string): boolean => {
const normalize = (url: string) => url.replace(/\/+$/, '');
globUrl = normalize(globUrl);
url = normalize(url);
const memo = Array.from({ length: url.length + 1 }).map(() =>
Array.from({ length: globUrl.length + 1 }).map(() => undefined),
);
if (/^[^./:]*:\/\//.test(globUrl)) {
return doUrlMatch(memo, url, globUrl, 0, 0);
}
const scheme = /^(https?):\/\//.exec(url)?.[1];
if (scheme) {
return doUrlMatch(memo, url, `${scheme}://${globUrl}`, 0, 0);
}
return false;
};
const doUrlMatch = (
memo: (boolean | undefined)[][],
url: string,
globUrl: string,
urlOffset: number,
globUrlOffset: number,
): boolean => {
if (memo[urlOffset]?.[globUrlOffset] !== undefined) {
return memo[urlOffset][globUrlOffset]!;
}
const options = [];
// Endgame.
// Fully exact match
if (urlOffset === url.length) {
return globUrlOffset === globUrl.length;
}
// Some path remaining in url
if (globUrlOffset === globUrl.length) {
const remaining = url.slice(urlOffset);
return remaining[0] === '/';
}
if (url[urlOffset] === globUrl[globUrlOffset]) {
// Exact match.
options.push(doUrlMatch(memo, url, globUrl, urlOffset + 1, globUrlOffset + 1));
}
if (globUrl[globUrlOffset] + globUrl[globUrlOffset + 1] === '*.') {
// Any subdomain match. Either consume one thing that's not a / or : and don't advance base or consume nothing and do.
if (!['/', ':'].includes(url[urlOffset])) {
options.push(doUrlMatch(memo, url, globUrl, urlOffset + 1, globUrlOffset));
}
options.push(doUrlMatch(memo, url, globUrl, urlOffset, globUrlOffset + 2));
}
if (globUrl[globUrlOffset] === '*') {
// Any match. Either consume one thing and don't advance base or consume nothing and do.
if (urlOffset + 1 === url.length) {
// If we're at the end of the input url consume one from both.
options.push(doUrlMatch(memo, url, globUrl, urlOffset + 1, globUrlOffset + 1));
} else {
options.push(doUrlMatch(memo, url, globUrl, urlOffset + 1, globUrlOffset));
}
options.push(doUrlMatch(memo, url, globUrl, urlOffset, globUrlOffset + 1));
}
if (globUrl[globUrlOffset] + globUrl[globUrlOffset + 1] === ':*') {
// any port match. Consume a port if it exists otherwise nothing. Always comsume the base.
if (url[urlOffset] === ':') {
let endPortIndex = urlOffset + 1;
do { endPortIndex++; } while (/[0-9]/.test(url[endPortIndex]));
options.push(doUrlMatch(memo, url, globUrl, endPortIndex, globUrlOffset + 2));
} else {
options.push(doUrlMatch(memo, url, globUrl, urlOffset, globUrlOffset + 2));
}
}
return (memo[urlOffset][globUrlOffset] = options.some(a => a === true));
};
| src/vs/workbench/contrib/url/common/urlGlob.ts | 0 | https://github.com/microsoft/vscode/commit/c4fe803132ea8cd9aa903a83d7c5786ac77897b3 | [
0.00017216148262377828,
0.00017015771300066262,
0.00016742748266551644,
0.0001705548638710752,
0.000001699738163551956
] |
{
"id": 3,
"code_window": [
"\t\tconst resource = EditorResourceAccessor.getOriginalUri(editor);\n",
"\t\tconst path = resource ? resource.scheme === Schemas.file ? resource.fsPath : resource.path : undefined;\n",
"\t\tif (resource && path) {\n",
"\t\t\tlet resourceExt = extname(resource);\n",
"\t\t\tdescriptor['resource'] = { mimeType: guessMimeTypes(resource).join(', '), scheme: resource.scheme, ext: resourceExt, path: hash(path) };\n",
"\n",
"\t\t\t/* __GDPR__FRAGMENT__\n",
"\t\t\t\t\"EditorTelemetryDescriptor\" : {\n",
"\t\t\t\t\t\"resource\": { \"${inline}\": [ \"${URIDescriptor}\" ] }\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t// Remove query parameters from the resource extension\n",
"\t\t\tconst queryStringLocation = resourceExt.indexOf('?');\n",
"\t\t\tresourceExt = queryStringLocation !== -1 ? resourceExt.substr(0, queryStringLocation) : resourceExt;\n"
],
"file_path": "src/vs/workbench/browser/parts/editor/editorGroupView.ts",
"type": "add",
"edit_start_line_idx": 633
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { Registry } from 'vs/platform/registry/common/platform';
import { Extensions as WorkbenchExtensions, IWorkbenchContributionsRegistry, IWorkbenchContribution } from 'vs/workbench/common/contributions';
import { LifecyclePhase, ILifecycleService, StartupKind } from 'vs/workbench/services/lifecycle/common/lifecycle';
import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';
import { IWorkspaceContextService, WorkbenchState } from 'vs/platform/workspace/common/workspace';
import { IActivityBarService } from 'vs/workbench/services/activityBar/browser/activityBarService';
import { IEditorService } from 'vs/workbench/services/editor/common/editorService';
import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding';
import { IWorkbenchThemeService } from 'vs/workbench/services/themes/common/workbenchThemeService';
import { IWorkbenchEnvironmentService } from 'vs/workbench/services/environment/common/environmentService';
import { language } from 'vs/base/common/platform';
import { Disposable } from 'vs/base/common/lifecycle';
import ErrorTelemetry from 'vs/platform/telemetry/browser/errorTelemetry';
import { configurationTelemetry } from 'vs/platform/telemetry/common/telemetryUtils';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { IViewletService } from 'vs/workbench/services/viewlet/browser/viewlet';
import { ITextFileService, ITextFileSaveEvent, ITextFileResolveEvent } from 'vs/workbench/services/textfile/common/textfiles';
import { extname, basename, isEqual, isEqualOrParent } from 'vs/base/common/resources';
import { URI } from 'vs/base/common/uri';
import { Schemas } from 'vs/base/common/network';
import { guessMimeTypes } from 'vs/base/common/mime';
import { hash } from 'vs/base/common/hash';
type TelemetryData = {
mimeType: string;
ext: string;
path: number;
reason?: number;
allowlistedjson?: string;
};
type FileTelemetryDataFragment = {
mimeType: { classification: 'SystemMetaData', purpose: 'FeatureInsight' };
ext: { classification: 'SystemMetaData', purpose: 'FeatureInsight' };
path: { classification: 'SystemMetaData', purpose: 'FeatureInsight' };
reason?: { classification: 'SystemMetaData', purpose: 'FeatureInsight', isMeasurement: true };
allowlistedjson?: { classification: 'SystemMetaData', purpose: 'FeatureInsight' };
};
export class TelemetryContribution extends Disposable implements IWorkbenchContribution {
private static ALLOWLIST_JSON = ['package.json', 'package-lock.json', 'tsconfig.json', 'jsconfig.json', 'bower.json', '.eslintrc.json', 'tslint.json', 'composer.json'];
private static ALLOWLIST_WORKSPACE_JSON = ['settings.json', 'extensions.json', 'tasks.json', 'launch.json'];
constructor(
@ITelemetryService private readonly telemetryService: ITelemetryService,
@IWorkspaceContextService private readonly contextService: IWorkspaceContextService,
@IActivityBarService activityBarService: IActivityBarService,
@ILifecycleService lifecycleService: ILifecycleService,
@IEditorService editorService: IEditorService,
@IKeybindingService keybindingsService: IKeybindingService,
@IWorkbenchThemeService themeService: IWorkbenchThemeService,
@IWorkbenchEnvironmentService private readonly environmentService: IWorkbenchEnvironmentService,
@IConfigurationService configurationService: IConfigurationService,
@IViewletService viewletService: IViewletService,
@ITextFileService textFileService: ITextFileService
) {
super();
const { filesToOpenOrCreate, filesToDiff } = environmentService.configuration;
const activeViewlet = viewletService.getActiveViewlet();
type WindowSizeFragment = {
innerHeight: { classification: 'SystemMetaData', purpose: 'FeatureInsight', isMeasurement: true };
innerWidth: { classification: 'SystemMetaData', purpose: 'FeatureInsight', isMeasurement: true };
outerHeight: { classification: 'SystemMetaData', purpose: 'FeatureInsight', isMeasurement: true };
outerWidth: { classification: 'SystemMetaData', purpose: 'FeatureInsight', isMeasurement: true };
};
type WorkspaceLoadClassification = {
userAgent: { classification: 'SystemMetaData', purpose: 'FeatureInsight' };
emptyWorkbench: { classification: 'SystemMetaData', purpose: 'FeatureInsight', isMeasurement: true };
windowSize: WindowSizeFragment;
'workbench.filesToOpenOrCreate': { classification: 'SystemMetaData', purpose: 'FeatureInsight', isMeasurement: true };
'workbench.filesToDiff': { classification: 'SystemMetaData', purpose: 'FeatureInsight', isMeasurement: true };
customKeybindingsCount: { classification: 'SystemMetaData', purpose: 'FeatureInsight', isMeasurement: true };
theme: { classification: 'SystemMetaData', purpose: 'FeatureInsight' };
language: { classification: 'SystemMetaData', purpose: 'BusinessInsight' };
pinnedViewlets: { classification: 'SystemMetaData', purpose: 'FeatureInsight' };
restoredViewlet?: { classification: 'SystemMetaData', purpose: 'FeatureInsight' };
restoredEditors: { classification: 'SystemMetaData', purpose: 'FeatureInsight', isMeasurement: true };
startupKind: { classification: 'SystemMetaData', purpose: 'FeatureInsight', isMeasurement: true };
};
type WorkspaceLoadEvent = {
userAgent: string;
windowSize: { innerHeight: number, innerWidth: number, outerHeight: number, outerWidth: number };
emptyWorkbench: boolean;
'workbench.filesToOpenOrCreate': number;
'workbench.filesToDiff': number;
customKeybindingsCount: number;
theme: string;
language: string;
pinnedViewlets: string[];
restoredViewlet?: string;
restoredEditors: number;
startupKind: StartupKind;
};
telemetryService.publicLog2<WorkspaceLoadEvent, WorkspaceLoadClassification>('workspaceLoad', {
userAgent: navigator.userAgent,
windowSize: { innerHeight: window.innerHeight, innerWidth: window.innerWidth, outerHeight: window.outerHeight, outerWidth: window.outerWidth },
emptyWorkbench: contextService.getWorkbenchState() === WorkbenchState.EMPTY,
'workbench.filesToOpenOrCreate': filesToOpenOrCreate && filesToOpenOrCreate.length || 0,
'workbench.filesToDiff': filesToDiff && filesToDiff.length || 0,
customKeybindingsCount: keybindingsService.customKeybindingsCount(),
theme: themeService.getColorTheme().id,
language,
pinnedViewlets: activityBarService.getPinnedViewContainerIds(),
restoredViewlet: activeViewlet ? activeViewlet.getId() : undefined,
restoredEditors: editorService.visibleEditors.length,
startupKind: lifecycleService.startupKind
});
// Error Telemetry
this._register(new ErrorTelemetry(telemetryService));
// Configuration Telemetry
this._register(configurationTelemetry(telemetryService, configurationService));
// Files Telemetry
this._register(textFileService.files.onDidResolve(e => this.onTextFileModelResolved(e)));
this._register(textFileService.files.onDidSave(e => this.onTextFileModelSaved(e)));
// Lifecycle
this._register(lifecycleService.onDidShutdown(() => this.dispose()));
}
private onTextFileModelResolved(e: ITextFileResolveEvent): void {
const settingsType = this.getTypeIfSettings(e.model.resource);
if (settingsType) {
type SettingsReadClassification = {
settingsType: { classification: 'SystemMetaData', purpose: 'FeatureInsight' };
};
this.telemetryService.publicLog2<{ settingsType: string }, SettingsReadClassification>('settingsRead', { settingsType }); // Do not log read to user settings.json and .vscode folder as a fileGet event as it ruins our JSON usage data
} else {
type FileGetClassification = {} & FileTelemetryDataFragment;
this.telemetryService.publicLog2<TelemetryData, FileGetClassification>('fileGet', this.getTelemetryData(e.model.resource, e.reason));
}
}
private onTextFileModelSaved(e: ITextFileSaveEvent): void {
const settingsType = this.getTypeIfSettings(e.model.resource);
if (settingsType) {
type SettingsWrittenClassification = {
settingsType: { classification: 'SystemMetaData', purpose: 'FeatureInsight' };
};
this.telemetryService.publicLog2<{ settingsType: string }, SettingsWrittenClassification>('settingsWritten', { settingsType }); // Do not log write to user settings.json and .vscode folder as a filePUT event as it ruins our JSON usage data
} else {
type FilePutClassfication = {} & FileTelemetryDataFragment;
this.telemetryService.publicLog2<TelemetryData, FilePutClassfication>('filePUT', this.getTelemetryData(e.model.resource, e.reason));
}
}
private getTypeIfSettings(resource: URI): string {
if (extname(resource) !== '.json') {
return '';
}
// Check for global settings file
if (isEqual(resource, this.environmentService.settingsResource)) {
return 'global-settings';
}
// Check for keybindings file
if (isEqual(resource, this.environmentService.keybindingsResource)) {
return 'keybindings';
}
// Check for snippets
if (isEqualOrParent(resource, this.environmentService.snippetsHome)) {
return 'snippets';
}
// Check for workspace settings file
const folders = this.contextService.getWorkspace().folders;
for (const folder of folders) {
if (isEqualOrParent(resource, folder.toResource('.vscode'))) {
const filename = basename(resource);
if (TelemetryContribution.ALLOWLIST_WORKSPACE_JSON.indexOf(filename) > -1) {
return `.vscode/${filename}`;
}
}
}
return '';
}
private getTelemetryData(resource: URI, reason?: number): TelemetryData {
const ext = extname(resource);
const fileName = basename(resource);
const path = resource.scheme === Schemas.file ? resource.fsPath : resource.path;
const telemetryData = {
mimeType: guessMimeTypes(resource).join(', '),
ext,
path: hash(path),
reason,
allowlistedjson: undefined as string | undefined
};
if (ext === '.json' && TelemetryContribution.ALLOWLIST_JSON.indexOf(fileName) > -1) {
telemetryData['allowlistedjson'] = fileName;
}
return telemetryData;
}
}
Registry.as<IWorkbenchContributionsRegistry>(WorkbenchExtensions.Workbench).registerWorkbenchContribution(TelemetryContribution, LifecyclePhase.Restored);
| src/vs/workbench/contrib/telemetry/browser/telemetry.contribution.ts | 1 | https://github.com/microsoft/vscode/commit/c4fe803132ea8cd9aa903a83d7c5786ac77897b3 | [
0.022207235917448997,
0.0017567501636222005,
0.0001621171977603808,
0.00017180939903482795,
0.004931993782520294
] |
{
"id": 3,
"code_window": [
"\t\tconst resource = EditorResourceAccessor.getOriginalUri(editor);\n",
"\t\tconst path = resource ? resource.scheme === Schemas.file ? resource.fsPath : resource.path : undefined;\n",
"\t\tif (resource && path) {\n",
"\t\t\tlet resourceExt = extname(resource);\n",
"\t\t\tdescriptor['resource'] = { mimeType: guessMimeTypes(resource).join(', '), scheme: resource.scheme, ext: resourceExt, path: hash(path) };\n",
"\n",
"\t\t\t/* __GDPR__FRAGMENT__\n",
"\t\t\t\t\"EditorTelemetryDescriptor\" : {\n",
"\t\t\t\t\t\"resource\": { \"${inline}\": [ \"${URIDescriptor}\" ] }\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t// Remove query parameters from the resource extension\n",
"\t\t\tconst queryStringLocation = resourceExt.indexOf('?');\n",
"\t\t\tresourceExt = queryStringLocation !== -1 ? resourceExt.substr(0, queryStringLocation) : resourceExt;\n"
],
"file_path": "src/vs/workbench/browser/parts/editor/editorGroupView.ts",
"type": "add",
"edit_start_line_idx": 633
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { MarshalledId, MarshalledObject } from 'vs/base/common/marshalling';
import { URI, UriComponents } from 'vs/base/common/uri';
export interface IURITransformer {
transformIncoming(uri: UriComponents): UriComponents;
transformOutgoing(uri: UriComponents): UriComponents;
transformOutgoingURI(uri: URI): URI;
transformOutgoingScheme(scheme: string): string;
}
export interface UriParts {
scheme: string;
authority?: string;
path?: string;
}
export interface IRawURITransformer {
transformIncoming(uri: UriParts): UriParts;
transformOutgoing(uri: UriParts): UriParts;
transformOutgoingScheme(scheme: string): string;
}
function toJSON(uri: URI): UriComponents {
return <UriComponents><any>uri.toJSON();
}
export class URITransformer implements IURITransformer {
private readonly _uriTransformer: IRawURITransformer;
constructor(uriTransformer: IRawURITransformer) {
this._uriTransformer = uriTransformer;
}
public transformIncoming(uri: UriComponents): UriComponents {
const result = this._uriTransformer.transformIncoming(uri);
return (result === uri ? uri : toJSON(URI.from(result)));
}
public transformOutgoing(uri: UriComponents): UriComponents {
const result = this._uriTransformer.transformOutgoing(uri);
return (result === uri ? uri : toJSON(URI.from(result)));
}
public transformOutgoingURI(uri: URI): URI {
const result = this._uriTransformer.transformOutgoing(uri);
return (result === uri ? uri : URI.from(result));
}
public transformOutgoingScheme(scheme: string): string {
return this._uriTransformer.transformOutgoingScheme(scheme);
}
}
export const DefaultURITransformer: IURITransformer = new class {
transformIncoming(uri: UriComponents) {
return uri;
}
transformOutgoing(uri: UriComponents): UriComponents {
return uri;
}
transformOutgoingURI(uri: URI): URI {
return uri;
}
transformOutgoingScheme(scheme: string): string {
return scheme;
}
};
function _transformOutgoingURIs(obj: any, transformer: IURITransformer, depth: number): any {
if (!obj || depth > 200) {
return null;
}
if (typeof obj === 'object') {
if (obj instanceof URI) {
return transformer.transformOutgoing(obj);
}
// walk object (or array)
for (let key in obj) {
if (Object.hasOwnProperty.call(obj, key)) {
const r = _transformOutgoingURIs(obj[key], transformer, depth + 1);
if (r !== null) {
obj[key] = r;
}
}
}
}
return null;
}
export function transformOutgoingURIs<T>(obj: T, transformer: IURITransformer): T {
const result = _transformOutgoingURIs(obj, transformer, 0);
if (result === null) {
// no change
return obj;
}
return result;
}
function _transformIncomingURIs(obj: any, transformer: IURITransformer, revive: boolean, depth: number): any {
if (!obj || depth > 200) {
return null;
}
if (typeof obj === 'object') {
if ((<MarshalledObject>obj).$mid === MarshalledId.Uri) {
return revive ? URI.revive(transformer.transformIncoming(obj)) : transformer.transformIncoming(obj);
}
// walk object (or array)
for (let key in obj) {
if (Object.hasOwnProperty.call(obj, key)) {
const r = _transformIncomingURIs(obj[key], transformer, revive, depth + 1);
if (r !== null) {
obj[key] = r;
}
}
}
}
return null;
}
export function transformIncomingURIs<T>(obj: T, transformer: IURITransformer): T {
const result = _transformIncomingURIs(obj, transformer, false, 0);
if (result === null) {
// no change
return obj;
}
return result;
}
export function transformAndReviveIncomingURIs<T>(obj: T, transformer: IURITransformer): T {
const result = _transformIncomingURIs(obj, transformer, true, 0);
if (result === null) {
// no change
return obj;
}
return result;
}
| src/vs/base/common/uriIpc.ts | 0 | https://github.com/microsoft/vscode/commit/c4fe803132ea8cd9aa903a83d7c5786ac77897b3 | [
0.00022579966753255576,
0.0001753883552737534,
0.00016347762721125036,
0.00017159298295155168,
0.000014229878615878988
] |
{
"id": 3,
"code_window": [
"\t\tconst resource = EditorResourceAccessor.getOriginalUri(editor);\n",
"\t\tconst path = resource ? resource.scheme === Schemas.file ? resource.fsPath : resource.path : undefined;\n",
"\t\tif (resource && path) {\n",
"\t\t\tlet resourceExt = extname(resource);\n",
"\t\t\tdescriptor['resource'] = { mimeType: guessMimeTypes(resource).join(', '), scheme: resource.scheme, ext: resourceExt, path: hash(path) };\n",
"\n",
"\t\t\t/* __GDPR__FRAGMENT__\n",
"\t\t\t\t\"EditorTelemetryDescriptor\" : {\n",
"\t\t\t\t\t\"resource\": { \"${inline}\": [ \"${URIDescriptor}\" ] }\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t// Remove query parameters from the resource extension\n",
"\t\t\tconst queryStringLocation = resourceExt.indexOf('?');\n",
"\t\t\tresourceExt = queryStringLocation !== -1 ? resourceExt.substr(0, queryStringLocation) : resourceExt;\n"
],
"file_path": "src/vs/workbench/browser/parts/editor/editorGroupView.ts",
"type": "add",
"edit_start_line_idx": 633
} | {
"name": "perl",
"displayName": "%displayName%",
"description": "%description%",
"version": "1.0.0",
"publisher": "vscode",
"license": "MIT",
"engines": {
"vscode": "*"
},
"scripts": {
"update-grammar": "node ../node_modules/vscode-grammar-updater/bin textmate/perl.tmbundle Syntaxes/Perl.plist ./syntaxes/perl.tmLanguage.json Syntaxes/Perl%206.tmLanguage ./syntaxes/perl6.tmLanguage.json"
},
"contributes": {
"languages": [
{
"id": "perl",
"aliases": [
"Perl",
"perl"
],
"extensions": [
".pl",
".pm",
".pod",
".t",
".PL",
".psgi"
],
"firstLine": "^#!.*\\bperl\\b",
"configuration": "./perl.language-configuration.json"
},
{
"id": "perl6",
"aliases": [
"Perl 6",
"perl6"
],
"extensions": [
".p6",
".pl6",
".pm6",
".nqp"
],
"firstLine": "(^#!.*\\bperl6\\b)|use\\s+v6",
"configuration": "./perl6.language-configuration.json"
}
],
"grammars": [
{
"language": "perl",
"scopeName": "source.perl",
"path": "./syntaxes/perl.tmLanguage.json"
},
{
"language": "perl6",
"scopeName": "source.perl.6",
"path": "./syntaxes/perl6.tmLanguage.json"
}
]
},
"repository": {
"type": "git",
"url": "https://github.com/microsoft/vscode.git"
}
}
| extensions/perl/package.json | 0 | https://github.com/microsoft/vscode/commit/c4fe803132ea8cd9aa903a83d7c5786ac77897b3 | [
0.00017878469952847809,
0.00017501683032605797,
0.00017237897554878145,
0.00017471502360422164,
0.000002354786829528166
] |
{
"id": 3,
"code_window": [
"\t\tconst resource = EditorResourceAccessor.getOriginalUri(editor);\n",
"\t\tconst path = resource ? resource.scheme === Schemas.file ? resource.fsPath : resource.path : undefined;\n",
"\t\tif (resource && path) {\n",
"\t\t\tlet resourceExt = extname(resource);\n",
"\t\t\tdescriptor['resource'] = { mimeType: guessMimeTypes(resource).join(', '), scheme: resource.scheme, ext: resourceExt, path: hash(path) };\n",
"\n",
"\t\t\t/* __GDPR__FRAGMENT__\n",
"\t\t\t\t\"EditorTelemetryDescriptor\" : {\n",
"\t\t\t\t\t\"resource\": { \"${inline}\": [ \"${URIDescriptor}\" ] }\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t// Remove query parameters from the resource extension\n",
"\t\t\tconst queryStringLocation = resourceExt.indexOf('?');\n",
"\t\t\tresourceExt = queryStringLocation !== -1 ? resourceExt.substr(0, queryStringLocation) : resourceExt;\n"
],
"file_path": "src/vs/workbench/browser/parts/editor/editorGroupView.ts",
"type": "add",
"edit_start_line_idx": 633
} | <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script>
Polymer({
is: "chat-messages",
properties: {
user: {},
friend: {
observer: "_friendChanged"
}
},
});
</script>
</head>
<body>
</body>
</html> | extensions/html-language-features/server/src/test/fixtures/expected/19813-4spaces.html | 0 | https://github.com/microsoft/vscode/commit/c4fe803132ea8cd9aa903a83d7c5786ac77897b3 | [
0.00017255939019378275,
0.000171433508512564,
0.00017055000353138894,
0.0001711911172606051,
8.380421832043794e-7
] |
{
"id": 4,
"code_window": [
"\n",
"\t\treturn '';\n",
"\t}\n",
"\n",
"\tprivate getTelemetryData(resource: URI, reason?: number): TelemetryData {\n",
"\t\tconst ext = extname(resource);\n",
"\t\tconst fileName = basename(resource);\n",
"\t\tconst path = resource.scheme === Schemas.file ? resource.fsPath : resource.path;\n",
"\t\tconst telemetryData = {\n",
"\t\t\tmimeType: guessMimeTypes(resource).join(', '),\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tlet ext = extname(resource);\n",
"\t\t// Remove query parameters from the resource extension\n",
"\t\tconst queryStringLocation = ext.indexOf('?');\n",
"\t\text = queryStringLocation !== -1 ? ext.substr(0, queryStringLocation) : ext;\n"
],
"file_path": "src/vs/workbench/contrib/telemetry/browser/telemetry.contribution.ts",
"type": "replace",
"edit_start_line_idx": 196
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { Registry } from 'vs/platform/registry/common/platform';
import { Extensions as WorkbenchExtensions, IWorkbenchContributionsRegistry, IWorkbenchContribution } from 'vs/workbench/common/contributions';
import { LifecyclePhase, ILifecycleService, StartupKind } from 'vs/workbench/services/lifecycle/common/lifecycle';
import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';
import { IWorkspaceContextService, WorkbenchState } from 'vs/platform/workspace/common/workspace';
import { IActivityBarService } from 'vs/workbench/services/activityBar/browser/activityBarService';
import { IEditorService } from 'vs/workbench/services/editor/common/editorService';
import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding';
import { IWorkbenchThemeService } from 'vs/workbench/services/themes/common/workbenchThemeService';
import { IWorkbenchEnvironmentService } from 'vs/workbench/services/environment/common/environmentService';
import { language } from 'vs/base/common/platform';
import { Disposable } from 'vs/base/common/lifecycle';
import ErrorTelemetry from 'vs/platform/telemetry/browser/errorTelemetry';
import { configurationTelemetry } from 'vs/platform/telemetry/common/telemetryUtils';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { IViewletService } from 'vs/workbench/services/viewlet/browser/viewlet';
import { ITextFileService, ITextFileSaveEvent, ITextFileResolveEvent } from 'vs/workbench/services/textfile/common/textfiles';
import { extname, basename, isEqual, isEqualOrParent } from 'vs/base/common/resources';
import { URI } from 'vs/base/common/uri';
import { Schemas } from 'vs/base/common/network';
import { guessMimeTypes } from 'vs/base/common/mime';
import { hash } from 'vs/base/common/hash';
type TelemetryData = {
mimeType: string;
ext: string;
path: number;
reason?: number;
allowlistedjson?: string;
};
type FileTelemetryDataFragment = {
mimeType: { classification: 'SystemMetaData', purpose: 'FeatureInsight' };
ext: { classification: 'SystemMetaData', purpose: 'FeatureInsight' };
path: { classification: 'SystemMetaData', purpose: 'FeatureInsight' };
reason?: { classification: 'SystemMetaData', purpose: 'FeatureInsight', isMeasurement: true };
allowlistedjson?: { classification: 'SystemMetaData', purpose: 'FeatureInsight' };
};
export class TelemetryContribution extends Disposable implements IWorkbenchContribution {
private static ALLOWLIST_JSON = ['package.json', 'package-lock.json', 'tsconfig.json', 'jsconfig.json', 'bower.json', '.eslintrc.json', 'tslint.json', 'composer.json'];
private static ALLOWLIST_WORKSPACE_JSON = ['settings.json', 'extensions.json', 'tasks.json', 'launch.json'];
constructor(
@ITelemetryService private readonly telemetryService: ITelemetryService,
@IWorkspaceContextService private readonly contextService: IWorkspaceContextService,
@IActivityBarService activityBarService: IActivityBarService,
@ILifecycleService lifecycleService: ILifecycleService,
@IEditorService editorService: IEditorService,
@IKeybindingService keybindingsService: IKeybindingService,
@IWorkbenchThemeService themeService: IWorkbenchThemeService,
@IWorkbenchEnvironmentService private readonly environmentService: IWorkbenchEnvironmentService,
@IConfigurationService configurationService: IConfigurationService,
@IViewletService viewletService: IViewletService,
@ITextFileService textFileService: ITextFileService
) {
super();
const { filesToOpenOrCreate, filesToDiff } = environmentService.configuration;
const activeViewlet = viewletService.getActiveViewlet();
type WindowSizeFragment = {
innerHeight: { classification: 'SystemMetaData', purpose: 'FeatureInsight', isMeasurement: true };
innerWidth: { classification: 'SystemMetaData', purpose: 'FeatureInsight', isMeasurement: true };
outerHeight: { classification: 'SystemMetaData', purpose: 'FeatureInsight', isMeasurement: true };
outerWidth: { classification: 'SystemMetaData', purpose: 'FeatureInsight', isMeasurement: true };
};
type WorkspaceLoadClassification = {
userAgent: { classification: 'SystemMetaData', purpose: 'FeatureInsight' };
emptyWorkbench: { classification: 'SystemMetaData', purpose: 'FeatureInsight', isMeasurement: true };
windowSize: WindowSizeFragment;
'workbench.filesToOpenOrCreate': { classification: 'SystemMetaData', purpose: 'FeatureInsight', isMeasurement: true };
'workbench.filesToDiff': { classification: 'SystemMetaData', purpose: 'FeatureInsight', isMeasurement: true };
customKeybindingsCount: { classification: 'SystemMetaData', purpose: 'FeatureInsight', isMeasurement: true };
theme: { classification: 'SystemMetaData', purpose: 'FeatureInsight' };
language: { classification: 'SystemMetaData', purpose: 'BusinessInsight' };
pinnedViewlets: { classification: 'SystemMetaData', purpose: 'FeatureInsight' };
restoredViewlet?: { classification: 'SystemMetaData', purpose: 'FeatureInsight' };
restoredEditors: { classification: 'SystemMetaData', purpose: 'FeatureInsight', isMeasurement: true };
startupKind: { classification: 'SystemMetaData', purpose: 'FeatureInsight', isMeasurement: true };
};
type WorkspaceLoadEvent = {
userAgent: string;
windowSize: { innerHeight: number, innerWidth: number, outerHeight: number, outerWidth: number };
emptyWorkbench: boolean;
'workbench.filesToOpenOrCreate': number;
'workbench.filesToDiff': number;
customKeybindingsCount: number;
theme: string;
language: string;
pinnedViewlets: string[];
restoredViewlet?: string;
restoredEditors: number;
startupKind: StartupKind;
};
telemetryService.publicLog2<WorkspaceLoadEvent, WorkspaceLoadClassification>('workspaceLoad', {
userAgent: navigator.userAgent,
windowSize: { innerHeight: window.innerHeight, innerWidth: window.innerWidth, outerHeight: window.outerHeight, outerWidth: window.outerWidth },
emptyWorkbench: contextService.getWorkbenchState() === WorkbenchState.EMPTY,
'workbench.filesToOpenOrCreate': filesToOpenOrCreate && filesToOpenOrCreate.length || 0,
'workbench.filesToDiff': filesToDiff && filesToDiff.length || 0,
customKeybindingsCount: keybindingsService.customKeybindingsCount(),
theme: themeService.getColorTheme().id,
language,
pinnedViewlets: activityBarService.getPinnedViewContainerIds(),
restoredViewlet: activeViewlet ? activeViewlet.getId() : undefined,
restoredEditors: editorService.visibleEditors.length,
startupKind: lifecycleService.startupKind
});
// Error Telemetry
this._register(new ErrorTelemetry(telemetryService));
// Configuration Telemetry
this._register(configurationTelemetry(telemetryService, configurationService));
// Files Telemetry
this._register(textFileService.files.onDidResolve(e => this.onTextFileModelResolved(e)));
this._register(textFileService.files.onDidSave(e => this.onTextFileModelSaved(e)));
// Lifecycle
this._register(lifecycleService.onDidShutdown(() => this.dispose()));
}
private onTextFileModelResolved(e: ITextFileResolveEvent): void {
const settingsType = this.getTypeIfSettings(e.model.resource);
if (settingsType) {
type SettingsReadClassification = {
settingsType: { classification: 'SystemMetaData', purpose: 'FeatureInsight' };
};
this.telemetryService.publicLog2<{ settingsType: string }, SettingsReadClassification>('settingsRead', { settingsType }); // Do not log read to user settings.json and .vscode folder as a fileGet event as it ruins our JSON usage data
} else {
type FileGetClassification = {} & FileTelemetryDataFragment;
this.telemetryService.publicLog2<TelemetryData, FileGetClassification>('fileGet', this.getTelemetryData(e.model.resource, e.reason));
}
}
private onTextFileModelSaved(e: ITextFileSaveEvent): void {
const settingsType = this.getTypeIfSettings(e.model.resource);
if (settingsType) {
type SettingsWrittenClassification = {
settingsType: { classification: 'SystemMetaData', purpose: 'FeatureInsight' };
};
this.telemetryService.publicLog2<{ settingsType: string }, SettingsWrittenClassification>('settingsWritten', { settingsType }); // Do not log write to user settings.json and .vscode folder as a filePUT event as it ruins our JSON usage data
} else {
type FilePutClassfication = {} & FileTelemetryDataFragment;
this.telemetryService.publicLog2<TelemetryData, FilePutClassfication>('filePUT', this.getTelemetryData(e.model.resource, e.reason));
}
}
private getTypeIfSettings(resource: URI): string {
if (extname(resource) !== '.json') {
return '';
}
// Check for global settings file
if (isEqual(resource, this.environmentService.settingsResource)) {
return 'global-settings';
}
// Check for keybindings file
if (isEqual(resource, this.environmentService.keybindingsResource)) {
return 'keybindings';
}
// Check for snippets
if (isEqualOrParent(resource, this.environmentService.snippetsHome)) {
return 'snippets';
}
// Check for workspace settings file
const folders = this.contextService.getWorkspace().folders;
for (const folder of folders) {
if (isEqualOrParent(resource, folder.toResource('.vscode'))) {
const filename = basename(resource);
if (TelemetryContribution.ALLOWLIST_WORKSPACE_JSON.indexOf(filename) > -1) {
return `.vscode/${filename}`;
}
}
}
return '';
}
private getTelemetryData(resource: URI, reason?: number): TelemetryData {
const ext = extname(resource);
const fileName = basename(resource);
const path = resource.scheme === Schemas.file ? resource.fsPath : resource.path;
const telemetryData = {
mimeType: guessMimeTypes(resource).join(', '),
ext,
path: hash(path),
reason,
allowlistedjson: undefined as string | undefined
};
if (ext === '.json' && TelemetryContribution.ALLOWLIST_JSON.indexOf(fileName) > -1) {
telemetryData['allowlistedjson'] = fileName;
}
return telemetryData;
}
}
Registry.as<IWorkbenchContributionsRegistry>(WorkbenchExtensions.Workbench).registerWorkbenchContribution(TelemetryContribution, LifecyclePhase.Restored);
| src/vs/workbench/contrib/telemetry/browser/telemetry.contribution.ts | 1 | https://github.com/microsoft/vscode/commit/c4fe803132ea8cd9aa903a83d7c5786ac77897b3 | [
0.9991777539253235,
0.2300693839788437,
0.00016538746422156692,
0.0002525727904867381,
0.4169941246509552
] |
{
"id": 4,
"code_window": [
"\n",
"\t\treturn '';\n",
"\t}\n",
"\n",
"\tprivate getTelemetryData(resource: URI, reason?: number): TelemetryData {\n",
"\t\tconst ext = extname(resource);\n",
"\t\tconst fileName = basename(resource);\n",
"\t\tconst path = resource.scheme === Schemas.file ? resource.fsPath : resource.path;\n",
"\t\tconst telemetryData = {\n",
"\t\t\tmimeType: guessMimeTypes(resource).join(', '),\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tlet ext = extname(resource);\n",
"\t\t// Remove query parameters from the resource extension\n",
"\t\tconst queryStringLocation = ext.indexOf('?');\n",
"\t\text = queryStringLocation !== -1 ? ext.substr(0, queryStringLocation) : ext;\n"
],
"file_path": "src/vs/workbench/contrib/telemetry/browser/telemetry.contribution.ts",
"type": "replace",
"edit_start_line_idx": 196
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as assert from 'assert';
import * as fs from 'fs';
import { basename, join, posix } from 'path';
import * as vscode from 'vscode';
import { TestFS } from '../memfs';
import { assertNoRpc, closeAllEditors, createRandomFile, delay, deleteFile, disposeAll, pathEquals, revertAllDirty, rndName, testFs, withLogDisabled } from '../utils';
suite('vscode API - workspace', () => {
teardown(async function () {
assertNoRpc();
await closeAllEditors();
});
test('MarkdownString', function () {
let md = new vscode.MarkdownString();
assert.strictEqual(md.value, '');
assert.strictEqual(md.isTrusted, undefined);
md = new vscode.MarkdownString('**bold**');
assert.strictEqual(md.value, '**bold**');
md.appendText('**bold?**');
assert.strictEqual(md.value, '**bold**\\*\\*bold?\\*\\*');
md.appendMarkdown('**bold**');
assert.strictEqual(md.value, '**bold**\\*\\*bold?\\*\\***bold**');
});
test('textDocuments', () => {
assert.ok(Array.isArray(vscode.workspace.textDocuments));
assert.throws(() => (<any>vscode.workspace).textDocuments = null);
});
test('rootPath', () => {
assert.ok(pathEquals(vscode.workspace.rootPath!, join(__dirname, '../../testWorkspace')));
assert.throws(() => (vscode.workspace as any).rootPath = 'farboo');
});
test('workspaceFile', () => {
assert.ok(!vscode.workspace.workspaceFile);
});
test('workspaceFolders', () => {
if (vscode.workspace.workspaceFolders) {
assert.strictEqual(vscode.workspace.workspaceFolders.length, 1);
assert.ok(pathEquals(vscode.workspace.workspaceFolders[0].uri.fsPath, join(__dirname, '../../testWorkspace')));
}
});
test('getWorkspaceFolder', () => {
const folder = vscode.workspace.getWorkspaceFolder(vscode.Uri.file(join(__dirname, '../../testWorkspace/far.js')));
assert.ok(!!folder);
if (folder) {
assert.ok(pathEquals(folder.uri.fsPath, join(__dirname, '../../testWorkspace')));
}
});
test('openTextDocument', async () => {
const uri = await createRandomFile();
// not yet there
const existing1 = vscode.workspace.textDocuments.find(doc => doc.uri.toString() === uri.toString());
assert.strictEqual(existing1, undefined);
// open and assert its there
const doc = await vscode.workspace.openTextDocument(uri);
assert.ok(doc);
assert.strictEqual(doc.uri.toString(), uri.toString());
const existing2 = vscode.workspace.textDocuments.find(doc => doc.uri.toString() === uri.toString());
assert.strictEqual(existing2 === doc, true);
});
test('openTextDocument, illegal path', () => {
return vscode.workspace.openTextDocument('funkydonky.txt').then(_doc => {
throw new Error('missing error');
}, _err => {
// good!
});
});
test('openTextDocument, untitled is dirty', async function () {
return vscode.workspace.openTextDocument(vscode.workspace.workspaceFolders![0].uri.with({ scheme: 'untitled', path: posix.join(vscode.workspace.workspaceFolders![0].uri.path, 'newfile.txt') })).then(doc => {
assert.strictEqual(doc.uri.scheme, 'untitled');
assert.ok(doc.isDirty);
});
});
test('openTextDocument, untitled with host', function () {
const uri = vscode.Uri.parse('untitled://localhost/c%24/Users/jrieken/code/samples/foobar.txt');
return vscode.workspace.openTextDocument(uri).then(doc => {
assert.strictEqual(doc.uri.scheme, 'untitled');
});
});
test('openTextDocument, untitled without path', function () {
return vscode.workspace.openTextDocument().then(doc => {
assert.strictEqual(doc.uri.scheme, 'untitled');
assert.ok(doc.isDirty);
});
});
test('openTextDocument, untitled without path but language ID', function () {
return vscode.workspace.openTextDocument({ language: 'xml' }).then(doc => {
assert.strictEqual(doc.uri.scheme, 'untitled');
assert.strictEqual(doc.languageId, 'xml');
assert.ok(doc.isDirty);
});
});
test('openTextDocument, untitled without path but language ID and content', function () {
return vscode.workspace.openTextDocument({ language: 'html', content: '<h1>Hello world!</h1>' }).then(doc => {
assert.strictEqual(doc.uri.scheme, 'untitled');
assert.strictEqual(doc.languageId, 'html');
assert.ok(doc.isDirty);
assert.strictEqual(doc.getText(), '<h1>Hello world!</h1>');
});
});
test('openTextDocument, untitled closes on save', function () {
const path = join(vscode.workspace.rootPath || '', './newfile.txt');
return vscode.workspace.openTextDocument(vscode.Uri.parse('untitled:' + path)).then(doc => {
assert.strictEqual(doc.uri.scheme, 'untitled');
assert.ok(doc.isDirty);
let closed: vscode.TextDocument;
let d0 = vscode.workspace.onDidCloseTextDocument(e => closed = e);
return vscode.window.showTextDocument(doc).then(() => {
return doc.save().then((didSave: boolean) => {
assert.strictEqual(didSave, true, `FAILED to save${doc.uri.toString()}`);
assert.ok(closed === doc);
assert.ok(!doc.isDirty);
assert.ok(fs.existsSync(path));
d0.dispose();
fs.unlinkSync(join(vscode.workspace.rootPath || '', './newfile.txt'));
});
});
});
});
test('openTextDocument, uri scheme/auth/path', function () {
let registration = vscode.workspace.registerTextDocumentContentProvider('sc', {
provideTextDocumentContent() {
return 'SC';
}
});
return Promise.all([
vscode.workspace.openTextDocument(vscode.Uri.parse('sc://auth')).then(doc => {
assert.strictEqual(doc.uri.authority, 'auth');
assert.strictEqual(doc.uri.path, '');
}),
vscode.workspace.openTextDocument(vscode.Uri.parse('sc:///path')).then(doc => {
assert.strictEqual(doc.uri.authority, '');
assert.strictEqual(doc.uri.path, '/path');
}),
vscode.workspace.openTextDocument(vscode.Uri.parse('sc://auth/path')).then(doc => {
assert.strictEqual(doc.uri.authority, 'auth');
assert.strictEqual(doc.uri.path, '/path');
})
]).then(() => {
registration.dispose();
});
});
test('openTextDocument, actual casing first', async function () {
const fs = new TestFS('this-fs', false);
const reg = vscode.workspace.registerFileSystemProvider(fs.scheme, fs, { isCaseSensitive: fs.isCaseSensitive });
let uriOne = vscode.Uri.parse('this-fs:/one');
let uriTwo = vscode.Uri.parse('this-fs:/two');
let uriONE = vscode.Uri.parse('this-fs:/ONE'); // same resource, different uri
let uriTWO = vscode.Uri.parse('this-fs:/TWO');
fs.writeFile(uriOne, Buffer.from('one'), { create: true, overwrite: true });
fs.writeFile(uriTwo, Buffer.from('two'), { create: true, overwrite: true });
// lower case (actual case) comes first
let docOne = await vscode.workspace.openTextDocument(uriOne);
assert.strictEqual(docOne.uri.toString(), uriOne.toString());
let docONE = await vscode.workspace.openTextDocument(uriONE);
assert.strictEqual(docONE === docOne, true);
assert.strictEqual(docONE.uri.toString(), uriOne.toString());
assert.strictEqual(docONE.uri.toString() !== uriONE.toString(), true); // yep
// upper case (NOT the actual case) comes first
let docTWO = await vscode.workspace.openTextDocument(uriTWO);
assert.strictEqual(docTWO.uri.toString(), uriTWO.toString());
let docTwo = await vscode.workspace.openTextDocument(uriTwo);
assert.strictEqual(docTWO === docTwo, true);
assert.strictEqual(docTwo.uri.toString(), uriTWO.toString());
assert.strictEqual(docTwo.uri.toString() !== uriTwo.toString(), true); // yep
reg.dispose();
});
test('eol, read', () => {
const a = createRandomFile('foo\nbar\nbar').then(file => {
return vscode.workspace.openTextDocument(file).then(doc => {
assert.strictEqual(doc.eol, vscode.EndOfLine.LF);
});
});
const b = createRandomFile('foo\nbar\nbar\r\nbaz').then(file => {
return vscode.workspace.openTextDocument(file).then(doc => {
assert.strictEqual(doc.eol, vscode.EndOfLine.LF);
});
});
const c = createRandomFile('foo\r\nbar\r\nbar').then(file => {
return vscode.workspace.openTextDocument(file).then(doc => {
assert.strictEqual(doc.eol, vscode.EndOfLine.CRLF);
});
});
return Promise.all([a, b, c]);
});
test('eol, change via editor', () => {
return createRandomFile('foo\nbar\nbar').then(file => {
return vscode.workspace.openTextDocument(file).then(doc => {
assert.strictEqual(doc.eol, vscode.EndOfLine.LF);
return vscode.window.showTextDocument(doc).then(editor => {
return editor.edit(builder => builder.setEndOfLine(vscode.EndOfLine.CRLF));
}).then(value => {
assert.ok(value);
assert.ok(doc.isDirty);
assert.strictEqual(doc.eol, vscode.EndOfLine.CRLF);
});
});
});
});
test('eol, change via applyEdit', () => {
return createRandomFile('foo\nbar\nbar').then(file => {
return vscode.workspace.openTextDocument(file).then(doc => {
assert.strictEqual(doc.eol, vscode.EndOfLine.LF);
const edit = new vscode.WorkspaceEdit();
edit.set(file, [vscode.TextEdit.setEndOfLine(vscode.EndOfLine.CRLF)]);
return vscode.workspace.applyEdit(edit).then(value => {
assert.ok(value);
assert.ok(doc.isDirty);
assert.strictEqual(doc.eol, vscode.EndOfLine.CRLF);
});
});
});
});
test('eol, change via onWillSave', async function () {
let called = false;
let sub = vscode.workspace.onWillSaveTextDocument(e => {
called = true;
e.waitUntil(Promise.resolve([vscode.TextEdit.setEndOfLine(vscode.EndOfLine.LF)]));
});
const file = await createRandomFile('foo\r\nbar\r\nbar');
const doc = await vscode.workspace.openTextDocument(file);
assert.strictEqual(doc.eol, vscode.EndOfLine.CRLF);
const edit = new vscode.WorkspaceEdit();
edit.set(file, [vscode.TextEdit.insert(new vscode.Position(0, 0), '-changes-')]);
const successEdit = await vscode.workspace.applyEdit(edit);
assert.ok(successEdit);
const successSave = await doc.save();
assert.ok(successSave);
assert.ok(called);
assert.ok(!doc.isDirty);
assert.strictEqual(doc.eol, vscode.EndOfLine.LF);
sub.dispose();
});
function assertEqualPath(a: string, b: string): void {
assert.ok(pathEquals(a, b), `${a} <-> ${b}`);
}
test('events: onDidOpenTextDocument, onDidChangeTextDocument, onDidSaveTextDocument', async () => {
const file = await createRandomFile();
let disposables: vscode.Disposable[] = [];
await revertAllDirty(); // needed for a clean state for `onDidSaveTextDocument` (#102365)
let pendingAsserts: Function[] = [];
let onDidOpenTextDocument = false;
disposables.push(vscode.workspace.onDidOpenTextDocument(e => {
pendingAsserts.push(() => assertEqualPath(e.uri.fsPath, file.fsPath));
onDidOpenTextDocument = true;
}));
let onDidChangeTextDocument = false;
disposables.push(vscode.workspace.onDidChangeTextDocument(e => {
pendingAsserts.push(() => assertEqualPath(e.document.uri.fsPath, file.fsPath));
onDidChangeTextDocument = true;
}));
let onDidSaveTextDocument = false;
disposables.push(vscode.workspace.onDidSaveTextDocument(e => {
pendingAsserts.push(() => assertEqualPath(e.uri.fsPath, file.fsPath));
onDidSaveTextDocument = true;
}));
const doc = await vscode.workspace.openTextDocument(file);
const editor = await vscode.window.showTextDocument(doc);
await editor.edit((builder) => {
builder.insert(new vscode.Position(0, 0), 'Hello World');
});
await doc.save();
assert.ok(onDidOpenTextDocument);
assert.ok(onDidChangeTextDocument);
assert.ok(onDidSaveTextDocument);
pendingAsserts.forEach(assert => assert());
disposeAll(disposables);
return deleteFile(file);
});
test('events: onDidSaveTextDocument fires even for non dirty file when saved', async () => {
const file = await createRandomFile();
let disposables: vscode.Disposable[] = [];
let pendingAsserts: Function[] = [];
await revertAllDirty(); // needed for a clean state for `onDidSaveTextDocument` (#102365)
let onDidSaveTextDocument = false;
disposables.push(vscode.workspace.onDidSaveTextDocument(e => {
pendingAsserts.push(() => assertEqualPath(e.uri.fsPath, file.fsPath));
onDidSaveTextDocument = true;
}));
const doc = await vscode.workspace.openTextDocument(file);
await vscode.window.showTextDocument(doc);
await vscode.commands.executeCommand('workbench.action.files.save');
assert.ok(onDidSaveTextDocument);
pendingAsserts.forEach(fn => fn());
disposeAll(disposables);
return deleteFile(file);
});
test('openTextDocument, with selection', function () {
return createRandomFile('foo\nbar\nbar').then(file => {
return vscode.workspace.openTextDocument(file).then(doc => {
return vscode.window.showTextDocument(doc, { selection: new vscode.Range(new vscode.Position(1, 1), new vscode.Position(1, 2)) }).then(editor => {
assert.strictEqual(editor.selection.start.line, 1);
assert.strictEqual(editor.selection.start.character, 1);
assert.strictEqual(editor.selection.end.line, 1);
assert.strictEqual(editor.selection.end.character, 2);
});
});
});
});
test('registerTextDocumentContentProvider, simple', function () {
let registration = vscode.workspace.registerTextDocumentContentProvider('foo', {
provideTextDocumentContent(uri) {
return uri.toString();
}
});
const uri = vscode.Uri.parse('foo://testing/virtual.js');
return vscode.workspace.openTextDocument(uri).then(doc => {
assert.strictEqual(doc.getText(), uri.toString());
assert.strictEqual(doc.isDirty, false);
assert.strictEqual(doc.uri.toString(), uri.toString());
registration.dispose();
});
});
test('registerTextDocumentContentProvider, constrains', function () {
// built-in
assert.throws(function () {
vscode.workspace.registerTextDocumentContentProvider('untitled', { provideTextDocumentContent() { return null; } });
});
// built-in
assert.throws(function () {
vscode.workspace.registerTextDocumentContentProvider('file', { provideTextDocumentContent() { return null; } });
});
// missing scheme
return vscode.workspace.openTextDocument(vscode.Uri.parse('notThere://foo/far/boo/bar')).then(() => {
assert.ok(false, 'expected failure');
}, _err => {
// expected
});
});
test('registerTextDocumentContentProvider, multiple', function () {
// duplicate registration
let registration1 = vscode.workspace.registerTextDocumentContentProvider('foo', {
provideTextDocumentContent(uri) {
if (uri.authority === 'foo') {
return '1';
}
return undefined;
}
});
let registration2 = vscode.workspace.registerTextDocumentContentProvider('foo', {
provideTextDocumentContent(uri) {
if (uri.authority === 'bar') {
return '2';
}
return undefined;
}
});
return Promise.all([
vscode.workspace.openTextDocument(vscode.Uri.parse('foo://foo/bla')).then(doc => { assert.strictEqual(doc.getText(), '1'); }),
vscode.workspace.openTextDocument(vscode.Uri.parse('foo://bar/bla')).then(doc => { assert.strictEqual(doc.getText(), '2'); })
]).then(() => {
registration1.dispose();
registration2.dispose();
});
});
test('registerTextDocumentContentProvider, evil provider', function () {
// duplicate registration
let registration1 = vscode.workspace.registerTextDocumentContentProvider('foo', {
provideTextDocumentContent(_uri) {
return '1';
}
});
let registration2 = vscode.workspace.registerTextDocumentContentProvider('foo', {
provideTextDocumentContent(_uri): string {
throw new Error('fail');
}
});
return vscode.workspace.openTextDocument(vscode.Uri.parse('foo://foo/bla')).then(doc => {
assert.strictEqual(doc.getText(), '1');
registration1.dispose();
registration2.dispose();
});
});
test('registerTextDocumentContentProvider, invalid text', function () {
let registration = vscode.workspace.registerTextDocumentContentProvider('foo', {
provideTextDocumentContent(_uri) {
return <any>123;
}
});
return vscode.workspace.openTextDocument(vscode.Uri.parse('foo://auth/path')).then(() => {
assert.ok(false, 'expected failure');
}, _err => {
// expected
registration.dispose();
});
});
test('registerTextDocumentContentProvider, show virtual document', function () {
let registration = vscode.workspace.registerTextDocumentContentProvider('foo', {
provideTextDocumentContent(_uri) {
return 'I am virtual';
}
});
return vscode.workspace.openTextDocument(vscode.Uri.parse('foo://something/path')).then(doc => {
return vscode.window.showTextDocument(doc).then(editor => {
assert.ok(editor.document === doc);
assert.strictEqual(editor.document.getText(), 'I am virtual');
registration.dispose();
});
});
});
test('registerTextDocumentContentProvider, open/open document', function () {
let callCount = 0;
let registration = vscode.workspace.registerTextDocumentContentProvider('foo', {
provideTextDocumentContent(_uri) {
callCount += 1;
return 'I am virtual';
}
});
const uri = vscode.Uri.parse('foo://testing/path');
return Promise.all([vscode.workspace.openTextDocument(uri), vscode.workspace.openTextDocument(uri)]).then(docs => {
let [first, second] = docs;
assert.ok(first === second);
assert.ok(vscode.workspace.textDocuments.some(doc => doc.uri.toString() === uri.toString()));
assert.strictEqual(callCount, 1);
registration.dispose();
});
});
test('registerTextDocumentContentProvider, empty doc', function () {
let registration = vscode.workspace.registerTextDocumentContentProvider('foo', {
provideTextDocumentContent(_uri) {
return '';
}
});
const uri = vscode.Uri.parse('foo:doc/empty');
return vscode.workspace.openTextDocument(uri).then(doc => {
assert.strictEqual(doc.getText(), '');
assert.strictEqual(doc.uri.toString(), uri.toString());
registration.dispose();
});
});
test('registerTextDocumentContentProvider, change event', async function () {
let callCount = 0;
let emitter = new vscode.EventEmitter<vscode.Uri>();
let registration = vscode.workspace.registerTextDocumentContentProvider('foo', {
onDidChange: emitter.event,
provideTextDocumentContent(_uri) {
return 'call' + (callCount++);
}
});
const uri = vscode.Uri.parse('foo://testing/path3');
const doc = await vscode.workspace.openTextDocument(uri);
assert.strictEqual(callCount, 1);
assert.strictEqual(doc.getText(), 'call0');
return new Promise<void>(resolve => {
let subscription = vscode.workspace.onDidChangeTextDocument(event => {
assert.ok(event.document === doc);
assert.strictEqual(event.document.getText(), 'call1');
subscription.dispose();
registration.dispose();
resolve();
});
emitter.fire(doc.uri);
});
});
test('findFiles', () => {
return vscode.workspace.findFiles('**/image.png').then((res) => {
assert.strictEqual(res.length, 2);
assert.strictEqual(basename(vscode.workspace.asRelativePath(res[0])), 'image.png');
});
});
test('findFiles - null exclude', async () => {
await vscode.workspace.findFiles('**/file.txt').then((res) => {
// search.exclude folder is still searched, files.exclude folder is not
assert.strictEqual(res.length, 1);
assert.strictEqual(basename(vscode.workspace.asRelativePath(res[0])), 'file.txt');
});
await vscode.workspace.findFiles('**/file.txt', null).then((res) => {
// search.exclude and files.exclude folders are both searched
assert.strictEqual(res.length, 2);
assert.strictEqual(basename(vscode.workspace.asRelativePath(res[0])), 'file.txt');
});
});
test('findFiles - exclude', () => {
return vscode.workspace.findFiles('**/image.png').then((res) => {
assert.strictEqual(res.length, 2);
assert.strictEqual(basename(vscode.workspace.asRelativePath(res[0])), 'image.png');
});
});
test('findFiles, exclude', () => {
return vscode.workspace.findFiles('**/image.png', '**/sub/**').then((res) => {
assert.strictEqual(res.length, 1);
assert.strictEqual(basename(vscode.workspace.asRelativePath(res[0])), 'image.png');
});
});
test('findFiles, cancellation', () => {
const source = new vscode.CancellationTokenSource();
const token = source.token; // just to get an instance first
source.cancel();
return vscode.workspace.findFiles('*.js', null, 100, token).then((res) => {
assert.deepStrictEqual(res, []);
});
});
test('findTextInFiles', async () => {
const options: vscode.FindTextInFilesOptions = {
include: '*.ts',
previewOptions: {
matchLines: 1,
charsPerLine: 100
}
};
const results: vscode.TextSearchResult[] = [];
await vscode.workspace.findTextInFiles({ pattern: 'foo' }, options, result => {
results.push(result);
});
assert.strictEqual(results.length, 1);
const match = <vscode.TextSearchMatch>results[0];
assert(match.preview.text.indexOf('foo') >= 0);
assert.strictEqual(basename(vscode.workspace.asRelativePath(match.uri)), '10linefile.ts');
});
test('findTextInFiles, cancellation', async () => {
const results: vscode.TextSearchResult[] = [];
const cancellation = new vscode.CancellationTokenSource();
cancellation.cancel();
await vscode.workspace.findTextInFiles({ pattern: 'foo' }, result => {
results.push(result);
}, cancellation.token);
});
test('applyEdit', async () => {
const doc = await vscode.workspace.openTextDocument(vscode.Uri.parse('untitled:' + join(vscode.workspace.rootPath || '', './new2.txt')));
let edit = new vscode.WorkspaceEdit();
edit.insert(doc.uri, new vscode.Position(0, 0), new Array(1000).join('Hello World'));
let success = await vscode.workspace.applyEdit(edit);
assert.strictEqual(success, true);
assert.strictEqual(doc.isDirty, true);
});
test('applyEdit should fail when editing deleted resource', withLogDisabled(async () => {
const resource = await createRandomFile();
const edit = new vscode.WorkspaceEdit();
edit.deleteFile(resource);
edit.insert(resource, new vscode.Position(0, 0), '');
let success = await vscode.workspace.applyEdit(edit);
assert.strictEqual(success, false);
}));
test('applyEdit should fail when renaming deleted resource', withLogDisabled(async () => {
const resource = await createRandomFile();
const edit = new vscode.WorkspaceEdit();
edit.deleteFile(resource);
edit.renameFile(resource, resource);
let success = await vscode.workspace.applyEdit(edit);
assert.strictEqual(success, false);
}));
test('applyEdit should fail when editing renamed from resource', withLogDisabled(async () => {
const resource = await createRandomFile();
const newResource = vscode.Uri.file(resource.fsPath + '.1');
const edit = new vscode.WorkspaceEdit();
edit.renameFile(resource, newResource);
edit.insert(resource, new vscode.Position(0, 0), '');
let success = await vscode.workspace.applyEdit(edit);
assert.strictEqual(success, false);
}));
test('applyEdit "edit A -> rename A to B -> edit B"', async () => {
await testEditRenameEdit(oldUri => oldUri.with({ path: oldUri.path + 'NEW' }));
});
test('applyEdit "edit A -> rename A to B (different case)" -> edit B', async () => {
await testEditRenameEdit(oldUri => oldUri.with({ path: oldUri.path.toUpperCase() }));
});
test('applyEdit "edit A -> rename A to B (same case)" -> edit B', async () => {
await testEditRenameEdit(oldUri => oldUri);
});
async function testEditRenameEdit(newUriCreator: (oldUri: vscode.Uri) => vscode.Uri): Promise<void> {
const oldUri = await createRandomFile();
const newUri = newUriCreator(oldUri);
const edit = new vscode.WorkspaceEdit();
edit.insert(oldUri, new vscode.Position(0, 0), 'BEFORE');
edit.renameFile(oldUri, newUri);
edit.insert(newUri, new vscode.Position(0, 0), 'AFTER');
assert.ok(await vscode.workspace.applyEdit(edit));
let doc = await vscode.workspace.openTextDocument(newUri);
assert.strictEqual(doc.getText(), 'AFTERBEFORE');
assert.strictEqual(doc.isDirty, true);
}
function nameWithUnderscore(uri: vscode.Uri) {
return uri.with({ path: posix.join(posix.dirname(uri.path), `_${posix.basename(uri.path)}`) });
}
test('WorkspaceEdit: applying edits before and after rename duplicates resource #42633', withLogDisabled(async function () {
let docUri = await createRandomFile();
let newUri = nameWithUnderscore(docUri);
let we = new vscode.WorkspaceEdit();
we.insert(docUri, new vscode.Position(0, 0), 'Hello');
we.insert(docUri, new vscode.Position(0, 0), 'Foo');
we.renameFile(docUri, newUri);
we.insert(newUri, new vscode.Position(0, 0), 'Bar');
assert.ok(await vscode.workspace.applyEdit(we));
let doc = await vscode.workspace.openTextDocument(newUri);
assert.strictEqual(doc.getText(), 'BarHelloFoo');
}));
test('WorkspaceEdit: Problem recreating a renamed resource #42634', withLogDisabled(async function () {
let docUri = await createRandomFile();
let newUri = nameWithUnderscore(docUri);
let we = new vscode.WorkspaceEdit();
we.insert(docUri, new vscode.Position(0, 0), 'Hello');
we.insert(docUri, new vscode.Position(0, 0), 'Foo');
we.renameFile(docUri, newUri);
we.createFile(docUri);
we.insert(docUri, new vscode.Position(0, 0), 'Bar');
assert.ok(await vscode.workspace.applyEdit(we));
let newDoc = await vscode.workspace.openTextDocument(newUri);
assert.strictEqual(newDoc.getText(), 'HelloFoo');
let doc = await vscode.workspace.openTextDocument(docUri);
assert.strictEqual(doc.getText(), 'Bar');
}));
test('WorkspaceEdit api - after saving a deleted file, it still shows up as deleted. #42667', withLogDisabled(async function () {
let docUri = await createRandomFile();
let we = new vscode.WorkspaceEdit();
we.deleteFile(docUri);
we.insert(docUri, new vscode.Position(0, 0), 'InsertText');
assert.ok(!(await vscode.workspace.applyEdit(we)));
try {
await vscode.workspace.openTextDocument(docUri);
assert.ok(false);
} catch (e) {
assert.ok(true);
}
}));
test('WorkspaceEdit: edit and rename parent folder duplicates resource #42641', async function () {
let dir = vscode.Uri.parse(`${testFs.scheme}:/before-${rndName()}`);
await testFs.createDirectory(dir);
let docUri = await createRandomFile('', dir);
let docParent = docUri.with({ path: posix.dirname(docUri.path) });
let newParent = nameWithUnderscore(docParent);
let we = new vscode.WorkspaceEdit();
we.insert(docUri, new vscode.Position(0, 0), 'Hello');
we.renameFile(docParent, newParent);
assert.ok(await vscode.workspace.applyEdit(we));
try {
await vscode.workspace.openTextDocument(docUri);
assert.ok(false);
} catch (e) {
assert.ok(true);
}
let newUri = newParent.with({ path: posix.join(newParent.path, posix.basename(docUri.path)) });
let doc = await vscode.workspace.openTextDocument(newUri);
assert.ok(doc);
assert.strictEqual(doc.getText(), 'Hello');
});
test('WorkspaceEdit: rename resource followed by edit does not work #42638', withLogDisabled(async function () {
let docUri = await createRandomFile();
let newUri = nameWithUnderscore(docUri);
let we = new vscode.WorkspaceEdit();
we.renameFile(docUri, newUri);
we.insert(newUri, new vscode.Position(0, 0), 'Hello');
assert.ok(await vscode.workspace.applyEdit(we));
let doc = await vscode.workspace.openTextDocument(newUri);
assert.strictEqual(doc.getText(), 'Hello');
}));
test('WorkspaceEdit: create & override', withLogDisabled(async function () {
let docUri = await createRandomFile('before');
let we = new vscode.WorkspaceEdit();
we.createFile(docUri);
assert.ok(!await vscode.workspace.applyEdit(we));
assert.strictEqual((await vscode.workspace.openTextDocument(docUri)).getText(), 'before');
we = new vscode.WorkspaceEdit();
we.createFile(docUri, { overwrite: true });
assert.ok(await vscode.workspace.applyEdit(we));
assert.strictEqual((await vscode.workspace.openTextDocument(docUri)).getText(), '');
}));
test('WorkspaceEdit: create & ignoreIfExists', withLogDisabled(async function () {
let docUri = await createRandomFile('before');
let we = new vscode.WorkspaceEdit();
we.createFile(docUri, { ignoreIfExists: true });
assert.ok(await vscode.workspace.applyEdit(we));
assert.strictEqual((await vscode.workspace.openTextDocument(docUri)).getText(), 'before');
we = new vscode.WorkspaceEdit();
we.createFile(docUri, { overwrite: true, ignoreIfExists: true });
assert.ok(await vscode.workspace.applyEdit(we));
assert.strictEqual((await vscode.workspace.openTextDocument(docUri)).getText(), '');
}));
test('WorkspaceEdit: rename & ignoreIfExists', withLogDisabled(async function () {
let aUri = await createRandomFile('aaa');
let bUri = await createRandomFile('bbb');
let we = new vscode.WorkspaceEdit();
we.renameFile(aUri, bUri);
assert.ok(!await vscode.workspace.applyEdit(we));
we = new vscode.WorkspaceEdit();
we.renameFile(aUri, bUri, { ignoreIfExists: true });
assert.ok(await vscode.workspace.applyEdit(we));
we = new vscode.WorkspaceEdit();
we.renameFile(aUri, bUri, { overwrite: false, ignoreIfExists: true });
assert.ok(!await vscode.workspace.applyEdit(we));
we = new vscode.WorkspaceEdit();
we.renameFile(aUri, bUri, { overwrite: true, ignoreIfExists: true });
assert.ok(await vscode.workspace.applyEdit(we));
}));
test('WorkspaceEdit: delete & ignoreIfNotExists', withLogDisabled(async function () {
let docUri = await createRandomFile();
let we = new vscode.WorkspaceEdit();
we.deleteFile(docUri, { ignoreIfNotExists: false });
assert.ok(await vscode.workspace.applyEdit(we));
we = new vscode.WorkspaceEdit();
we.deleteFile(docUri, { ignoreIfNotExists: false });
assert.ok(!await vscode.workspace.applyEdit(we));
we = new vscode.WorkspaceEdit();
we.deleteFile(docUri, { ignoreIfNotExists: true });
assert.ok(await vscode.workspace.applyEdit(we));
}));
test('WorkspaceEdit: insert & rename multiple', async function () {
let [f1, f2, f3] = await Promise.all([createRandomFile(), createRandomFile(), createRandomFile()]);
let we = new vscode.WorkspaceEdit();
we.insert(f1, new vscode.Position(0, 0), 'f1');
we.insert(f2, new vscode.Position(0, 0), 'f2');
we.insert(f3, new vscode.Position(0, 0), 'f3');
let f1_ = nameWithUnderscore(f1);
we.renameFile(f1, f1_);
assert.ok(await vscode.workspace.applyEdit(we));
assert.strictEqual((await vscode.workspace.openTextDocument(f3)).getText(), 'f3');
assert.strictEqual((await vscode.workspace.openTextDocument(f2)).getText(), 'f2');
assert.strictEqual((await vscode.workspace.openTextDocument(f1_)).getText(), 'f1');
try {
await vscode.workspace.fs.stat(f1);
assert.ok(false);
} catch {
assert.ok(true);
}
});
test('workspace.applyEdit drops the TextEdit if there is a RenameFile later #77735 (with opened editor)', async function () {
await test77735(true);
});
test('workspace.applyEdit drops the TextEdit if there is a RenameFile later #77735 (without opened editor)', async function () {
await test77735(false);
});
async function test77735(withOpenedEditor: boolean): Promise<void> {
const docUriOriginal = await createRandomFile();
const docUriMoved = docUriOriginal.with({ path: `${docUriOriginal.path}.moved` });
if (withOpenedEditor) {
const document = await vscode.workspace.openTextDocument(docUriOriginal);
await vscode.window.showTextDocument(document);
} else {
await vscode.commands.executeCommand('workbench.action.closeAllEditors');
}
for (let i = 0; i < 4; i++) {
let we = new vscode.WorkspaceEdit();
let oldUri: vscode.Uri;
let newUri: vscode.Uri;
let expected: string;
if (i % 2 === 0) {
oldUri = docUriOriginal;
newUri = docUriMoved;
we.insert(oldUri, new vscode.Position(0, 0), 'Hello');
expected = 'Hello';
} else {
oldUri = docUriMoved;
newUri = docUriOriginal;
we.delete(oldUri, new vscode.Range(new vscode.Position(0, 0), new vscode.Position(0, 5)));
expected = '';
}
we.renameFile(oldUri, newUri);
assert.ok(await vscode.workspace.applyEdit(we));
const document = await vscode.workspace.openTextDocument(newUri);
assert.strictEqual(document.isDirty, true);
await document.save();
assert.strictEqual(document.isDirty, false);
assert.strictEqual(document.getText(), expected);
await delay(10);
}
}
test('The api workspace.applyEdit failed for some case of mixing resourceChange and textEdit #80688', async function () {
const file1 = await createRandomFile();
const file2 = await createRandomFile();
let we = new vscode.WorkspaceEdit();
we.insert(file1, new vscode.Position(0, 0), 'import1;');
const file2Name = basename(file2.fsPath);
const file2NewUri = vscode.Uri.parse(file2.toString().replace(file2Name, `new/${file2Name}`));
we.renameFile(file2, file2NewUri);
we.insert(file1, new vscode.Position(0, 0), 'import2;');
await vscode.workspace.applyEdit(we);
const document = await vscode.workspace.openTextDocument(file1);
// const expected = 'import1;import2;';
const expected2 = 'import2;import1;';
assert.strictEqual(document.getText(), expected2);
});
test('The api workspace.applyEdit failed for some case of mixing resourceChange and textEdit #80688', async function () {
const file1 = await createRandomFile();
const file2 = await createRandomFile();
let we = new vscode.WorkspaceEdit();
we.insert(file1, new vscode.Position(0, 0), 'import1;');
we.insert(file1, new vscode.Position(0, 0), 'import2;');
const file2Name = basename(file2.fsPath);
const file2NewUri = vscode.Uri.parse(file2.toString().replace(file2Name, `new/${file2Name}`));
we.renameFile(file2, file2NewUri);
await vscode.workspace.applyEdit(we);
const document = await vscode.workspace.openTextDocument(file1);
const expected = 'import1;import2;';
// const expected2 = 'import2;import1;';
assert.strictEqual(document.getText(), expected);
});
test('Should send a single FileWillRenameEvent instead of separate events when moving multiple files at once#111867', async function () {
const file1 = await createRandomFile();
const file2 = await createRandomFile();
const file1New = await createRandomFile();
const file2New = await createRandomFile();
const event = new Promise<vscode.FileWillRenameEvent>(resolve => {
let sub = vscode.workspace.onWillRenameFiles(e => {
sub.dispose();
resolve(e);
});
});
const we = new vscode.WorkspaceEdit();
we.renameFile(file1, file1New, { overwrite: true });
we.renameFile(file2, file2New, { overwrite: true });
await vscode.workspace.applyEdit(we);
const e = await event;
assert.strictEqual(e.files.length, 2);
assert.strictEqual(e.files[0].oldUri.toString(), file1.toString());
assert.strictEqual(e.files[1].oldUri.toString(), file2.toString());
});
test('Should send a single FileWillRenameEvent instead of separate events when moving multiple files at once#111867', async function () {
const event = new Promise<vscode.FileWillCreateEvent>(resolve => {
let sub = vscode.workspace.onWillCreateFiles(e => {
sub.dispose();
resolve(e);
});
});
const file1 = vscode.Uri.parse(`fake-fs:/${rndName()}`);
const file2 = vscode.Uri.parse(`fake-fs:/${rndName()}`);
const we = new vscode.WorkspaceEdit();
we.createFile(file1, { overwrite: true });
we.createFile(file2, { overwrite: true });
await vscode.workspace.applyEdit(we);
const e = await event;
assert.strictEqual(e.files.length, 2);
assert.strictEqual(e.files[0].toString(), file1.toString());
assert.strictEqual(e.files[1].toString(), file2.toString());
});
test('Should send a single FileWillRenameEvent instead of separate events when moving multiple files at once#111867', async function () {
const file1 = await createRandomFile();
const file2 = await createRandomFile();
const event = new Promise<vscode.FileWillDeleteEvent>(resolve => {
let sub = vscode.workspace.onWillDeleteFiles(e => {
sub.dispose();
resolve(e);
});
});
const we = new vscode.WorkspaceEdit();
we.deleteFile(file1);
we.deleteFile(file2);
await vscode.workspace.applyEdit(we);
const e = await event;
assert.strictEqual(e.files.length, 2);
assert.strictEqual(e.files[0].toString(), file1.toString());
assert.strictEqual(e.files[1].toString(), file2.toString());
});
test('issue #107739 - Redo of rename Java Class name has no effect', async () => {
const file = await createRandomFile('hello');
const fileName = basename(file.fsPath);
const newFile = vscode.Uri.parse(file.toString().replace(fileName, `${fileName}2`));
// apply edit
{
const we = new vscode.WorkspaceEdit();
we.insert(file, new vscode.Position(0, 5), '2');
we.renameFile(file, newFile);
await vscode.workspace.applyEdit(we);
}
// show the new document
{
const document = await vscode.workspace.openTextDocument(newFile);
await vscode.window.showTextDocument(document);
assert.strictEqual(document.getText(), 'hello2');
assert.strictEqual(document.isDirty, true);
}
// undo and show the old document
{
await vscode.commands.executeCommand('undo');
const document = await vscode.workspace.openTextDocument(file);
await vscode.window.showTextDocument(document);
assert.strictEqual(document.getText(), 'hello');
}
// redo and show the new document
{
await vscode.commands.executeCommand('redo');
const document = await vscode.workspace.openTextDocument(newFile);
await vscode.window.showTextDocument(document);
assert.strictEqual(document.getText(), 'hello2');
assert.strictEqual(document.isDirty, true);
}
});
test('issue #110141 - TextEdit.setEndOfLine applies an edit and invalidates redo stack even when no change is made', async () => {
const file = await createRandomFile('hello\nworld');
const document = await vscode.workspace.openTextDocument(file);
await vscode.window.showTextDocument(document);
// apply edit
{
const we = new vscode.WorkspaceEdit();
we.insert(file, new vscode.Position(0, 5), '2');
await vscode.workspace.applyEdit(we);
}
// check the document
{
assert.strictEqual(document.getText(), 'hello2\nworld');
assert.strictEqual(document.isDirty, true);
}
// apply no-op edit
{
const we = new vscode.WorkspaceEdit();
we.set(file, [vscode.TextEdit.setEndOfLine(vscode.EndOfLine.LF)]);
await vscode.workspace.applyEdit(we);
}
// undo
{
await vscode.commands.executeCommand('undo');
assert.strictEqual(document.getText(), 'hello\nworld');
assert.strictEqual(document.isDirty, false);
}
});
});
| extensions/vscode-api-tests/src/singlefolder-tests/workspace.test.ts | 0 | https://github.com/microsoft/vscode/commit/c4fe803132ea8cd9aa903a83d7c5786ac77897b3 | [
0.29773861169815063,
0.005238709971308708,
0.00016463098290842026,
0.0001740117440931499,
0.032809510827064514
] |
{
"id": 4,
"code_window": [
"\n",
"\t\treturn '';\n",
"\t}\n",
"\n",
"\tprivate getTelemetryData(resource: URI, reason?: number): TelemetryData {\n",
"\t\tconst ext = extname(resource);\n",
"\t\tconst fileName = basename(resource);\n",
"\t\tconst path = resource.scheme === Schemas.file ? resource.fsPath : resource.path;\n",
"\t\tconst telemetryData = {\n",
"\t\t\tmimeType: guessMimeTypes(resource).join(', '),\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tlet ext = extname(resource);\n",
"\t\t// Remove query parameters from the resource extension\n",
"\t\tconst queryStringLocation = ext.indexOf('?');\n",
"\t\text = queryStringLocation !== -1 ? ext.substr(0, queryStringLocation) : ext;\n"
],
"file_path": "src/vs/workbench/contrib/telemetry/browser/telemetry.contribution.ts",
"type": "replace",
"edit_start_line_idx": 196
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { binarySearch, isFalsyOrEmpty } from 'vs/base/common/arrays';
import { ICodeEditor } from 'vs/editor/browser/editorBrowser';
import { IEditorWorkerService } from 'vs/editor/common/services/editorWorkerService';
import { IPosition } from 'vs/editor/common/core/position';
import { Range } from 'vs/editor/common/core/range';
import { CompletionItem, CompletionItemKind } from 'vs/editor/common/modes';
import { BracketSelectionRangeProvider } from 'vs/editor/contrib/smartSelect/bracketSelections';
import { EditorOption } from 'vs/editor/common/config/editorOptions';
export abstract class WordDistance {
static readonly None = new class extends WordDistance {
distance() { return 0; }
};
static async create(service: IEditorWorkerService, editor: ICodeEditor): Promise<WordDistance> {
if (!editor.getOption(EditorOption.suggest).localityBonus) {
return WordDistance.None;
}
if (!editor.hasModel()) {
return WordDistance.None;
}
const model = editor.getModel();
const position = editor.getPosition();
if (!service.canComputeWordRanges(model.uri)) {
return WordDistance.None;
}
const [ranges] = await new BracketSelectionRangeProvider().provideSelectionRanges(model, [position]);
if (ranges.length === 0) {
return WordDistance.None;
}
const wordRanges = await service.computeWordRanges(model.uri, ranges[0].range);
if (!wordRanges) {
return WordDistance.None;
}
// remove current word
const wordUntilPos = model.getWordUntilPosition(position);
delete wordRanges[wordUntilPos.word];
return new class extends WordDistance {
distance(anchor: IPosition, item: CompletionItem) {
if (!position.equals(editor.getPosition())) {
return 0;
}
if (item.kind === CompletionItemKind.Keyword) {
return 2 << 20;
}
let word = typeof item.label === 'string' ? item.label : item.label.label;
let wordLines = wordRanges[word];
if (isFalsyOrEmpty(wordLines)) {
return 2 << 20;
}
let idx = binarySearch(wordLines, Range.fromPositions(anchor), Range.compareRangesUsingStarts);
let bestWordRange = idx >= 0 ? wordLines[idx] : wordLines[Math.max(0, ~idx - 1)];
let blockDistance = ranges.length;
for (const range of ranges) {
if (!Range.containsRange(range.range, bestWordRange)) {
break;
}
blockDistance -= 1;
}
return blockDistance;
}
};
}
abstract distance(anchor: IPosition, suggestion: CompletionItem): number;
}
| src/vs/editor/contrib/suggest/wordDistance.ts | 0 | https://github.com/microsoft/vscode/commit/c4fe803132ea8cd9aa903a83d7c5786ac77897b3 | [
0.0001813795097405091,
0.00017374799062963575,
0.00016466192028019577,
0.00017402037337888032,
0.000004188502316537779
] |
{
"id": 4,
"code_window": [
"\n",
"\t\treturn '';\n",
"\t}\n",
"\n",
"\tprivate getTelemetryData(resource: URI, reason?: number): TelemetryData {\n",
"\t\tconst ext = extname(resource);\n",
"\t\tconst fileName = basename(resource);\n",
"\t\tconst path = resource.scheme === Schemas.file ? resource.fsPath : resource.path;\n",
"\t\tconst telemetryData = {\n",
"\t\t\tmimeType: guessMimeTypes(resource).join(', '),\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tlet ext = extname(resource);\n",
"\t\t// Remove query parameters from the resource extension\n",
"\t\tconst queryStringLocation = ext.indexOf('?');\n",
"\t\text = queryStringLocation !== -1 ? ext.substr(0, queryStringLocation) : ext;\n"
],
"file_path": "src/vs/workbench/contrib/telemetry/browser/telemetry.contribution.ts",
"type": "replace",
"edit_start_line_idx": 196
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { BareFontInfo } from 'vs/editor/common/config/fontInfo';
export const enum CharWidthRequestType {
Regular = 0,
Italic = 1,
Bold = 2
}
export class CharWidthRequest {
public readonly chr: string;
public readonly type: CharWidthRequestType;
public width: number;
constructor(chr: string, type: CharWidthRequestType) {
this.chr = chr;
this.type = type;
this.width = 0;
}
public fulfill(width: number) {
this.width = width;
}
}
class DomCharWidthReader {
private readonly _bareFontInfo: BareFontInfo;
private readonly _requests: CharWidthRequest[];
private _container: HTMLElement | null;
private _testElements: HTMLSpanElement[] | null;
constructor(bareFontInfo: BareFontInfo, requests: CharWidthRequest[]) {
this._bareFontInfo = bareFontInfo;
this._requests = requests;
this._container = null;
this._testElements = null;
}
public read(): void {
// Create a test container with all these test elements
this._createDomElements();
// Add the container to the DOM
document.body.appendChild(this._container!);
// Read character widths
this._readFromDomElements();
// Remove the container from the DOM
document.body.removeChild(this._container!);
this._container = null;
this._testElements = null;
}
private _createDomElements(): void {
const container = document.createElement('div');
container.style.position = 'absolute';
container.style.top = '-50000px';
container.style.width = '50000px';
const regularDomNode = document.createElement('div');
regularDomNode.style.fontFamily = this._bareFontInfo.getMassagedFontFamily();
regularDomNode.style.fontWeight = this._bareFontInfo.fontWeight;
regularDomNode.style.fontSize = this._bareFontInfo.fontSize + 'px';
regularDomNode.style.fontFeatureSettings = this._bareFontInfo.fontFeatureSettings;
regularDomNode.style.lineHeight = this._bareFontInfo.lineHeight + 'px';
regularDomNode.style.letterSpacing = this._bareFontInfo.letterSpacing + 'px';
container.appendChild(regularDomNode);
const boldDomNode = document.createElement('div');
boldDomNode.style.fontFamily = this._bareFontInfo.getMassagedFontFamily();
boldDomNode.style.fontWeight = 'bold';
boldDomNode.style.fontSize = this._bareFontInfo.fontSize + 'px';
boldDomNode.style.fontFeatureSettings = this._bareFontInfo.fontFeatureSettings;
boldDomNode.style.lineHeight = this._bareFontInfo.lineHeight + 'px';
boldDomNode.style.letterSpacing = this._bareFontInfo.letterSpacing + 'px';
container.appendChild(boldDomNode);
const italicDomNode = document.createElement('div');
italicDomNode.style.fontFamily = this._bareFontInfo.getMassagedFontFamily();
italicDomNode.style.fontWeight = this._bareFontInfo.fontWeight;
italicDomNode.style.fontSize = this._bareFontInfo.fontSize + 'px';
italicDomNode.style.fontFeatureSettings = this._bareFontInfo.fontFeatureSettings;
italicDomNode.style.lineHeight = this._bareFontInfo.lineHeight + 'px';
italicDomNode.style.letterSpacing = this._bareFontInfo.letterSpacing + 'px';
italicDomNode.style.fontStyle = 'italic';
container.appendChild(italicDomNode);
const testElements: HTMLSpanElement[] = [];
for (const request of this._requests) {
let parent: HTMLElement;
if (request.type === CharWidthRequestType.Regular) {
parent = regularDomNode;
}
if (request.type === CharWidthRequestType.Bold) {
parent = boldDomNode;
}
if (request.type === CharWidthRequestType.Italic) {
parent = italicDomNode;
}
parent!.appendChild(document.createElement('br'));
const testElement = document.createElement('span');
DomCharWidthReader._render(testElement, request);
parent!.appendChild(testElement);
testElements.push(testElement);
}
this._container = container;
this._testElements = testElements;
}
private static _render(testElement: HTMLElement, request: CharWidthRequest): void {
if (request.chr === ' ') {
let htmlString = '\u00a0';
// Repeat character 256 (2^8) times
for (let i = 0; i < 8; i++) {
htmlString += htmlString;
}
testElement.innerText = htmlString;
} else {
let testString = request.chr;
// Repeat character 256 (2^8) times
for (let i = 0; i < 8; i++) {
testString += testString;
}
testElement.textContent = testString;
}
}
private _readFromDomElements(): void {
for (let i = 0, len = this._requests.length; i < len; i++) {
const request = this._requests[i];
const testElement = this._testElements![i];
request.fulfill(testElement.offsetWidth / 256);
}
}
}
export function readCharWidths(bareFontInfo: BareFontInfo, requests: CharWidthRequest[]): void {
const reader = new DomCharWidthReader(bareFontInfo, requests);
reader.read();
}
| src/vs/editor/browser/config/charWidthReader.ts | 0 | https://github.com/microsoft/vscode/commit/c4fe803132ea8cd9aa903a83d7c5786ac77897b3 | [
0.00018416873353999108,
0.00017296615988016129,
0.00016623664123471826,
0.0001732839155010879,
0.000004154152065893868
] |
{
"id": 0,
"code_window": [
"cf = cf.has([predicate, predicate], 'Stuart');\n",
"cf = cf.has(predicate, [literal, literal]);\n",
"\n",
"// .in\n",
"cf = cf.in(node);\n",
"cf = cf.in([node, node]);\n",
"cf = cf.in(cf.node(node));\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"cf = cf.in();\n"
],
"file_path": "types/clownface/clownface-tests.ts",
"type": "add",
"edit_start_line_idx": 119
} | import { Term, NamedNode, Dataset, Literal, DatasetCore, BlankNode } from 'rdf-js';
import Clownface = require('clownface/lib/Clownface');
import clownface = require('clownface');
const node: NamedNode = <any> {};
const blankNode: BlankNode = <any> {};
const predicate: NamedNode = <any> {};
const literal: Literal = <any> {};
let term: Term = <any> {};
// .ctor
const dataset: Dataset = <any> {};
const graph: NamedNode = <any> {};
let cf: Clownface<Dataset> = new Clownface({ dataset });
cf = new Clownface({ dataset, graph });
const typedByTerm: Clownface<DatasetCore, NamedNode> = new Clownface({ dataset, term: node });
const typedByTerms: Clownface<DatasetCore, NamedNode | BlankNode> = new Clownface({ dataset, term: [node, blankNode] });
cf = new Clownface({ dataset, value: 'foo' });
cf = new Clownface({ dataset, value: ['foo', 'bar'] });
cf = new Clownface({ dataset, term: [term, term], value: ['foo', 'bar'] });
// .addIn
cf = cf.addIn(node);
cf = cf.addIn(node, node);
cf = cf.addIn([ node, node ], node);
cf = cf.addIn(node, [ node, node ]);
cf = cf.addIn([ node, node ], [ node, node ], child => {
const values: string[] = child.values;
});
cf = cf.addIn(node, child => {
cf = child;
});
cf = cf.addIn(cf.node(node), cf.node(node));
// .addList
cf = cf.addList(predicate, [node, node]);
// .addOut
cf = cf.addOut(predicate, node);
cf = cf.addOut(predicate);
cf = cf.addOut(predicate, ['', 0]);
cf = cf.addOut([predicate, predicate], node);
cf = cf.addOut(predicate, [node, node]);
cf = cf.addOut([predicate, predicate], [node, node], child => {
const values: string[] = child.values;
});
cf = cf.addOut(predicate, child => {
const values: string[] = child.values;
});
cf = cf.addOut(cf.node(predicate), cf.node(node));
// .blankNode
let blankContext: Clownface;
blankContext = cf.blankNode();
blankContext = cf.blankNode('label');
blankContext = cf.blankNode([ 'b1', 'b2' ]);
// .deleteIn
cf = cf.deleteIn();
cf = cf.deleteIn(node);
cf = cf.deleteIn([node, node]);
// .deleteList
cf = cf.deleteList(predicate);
// .deleteOut
cf = cf.deleteOut();
cf = cf.deleteOut(node);
cf = cf.deleteOut([node, node]);
// factory
cf = clownface({ dataset });
const namedGraph: clownface.Clownface<Dataset, NamedNode> = clownface({ dataset, graph });
const singleFromValue: clownface.SingleContextClownface = clownface({ dataset, value: 'foo' });
const termContext: clownface.SingleContextClownface = clownface({
dataset,
term
});
const namedContext: clownface.SingleContextClownface<DatasetCore, NamedNode> = clownface({
dataset,
term: node,
});
const namedMutlipleTerms: clownface.SafeClownface<DatasetCore, NamedNode> = clownface({
dataset,
term: [node, node],
});
const mutlipleValues: clownface.SafeClownface = clownface({
dataset,
value: ['foo', 'bar'],
});
const maybeNamed: BlankNode | NamedNode = <any> {};
const altContext: clownface.SingleContextClownface<DatasetCore, BlankNode | NamedNode> = clownface({
dataset,
term: maybeNamed,
});
const literalContext: clownface.SingleContextClownface<Dataset, Literal> = <any> {};
const deriveContextFromOtherGraph: clownface.SingleContextClownface<Dataset, Literal> = clownface(literalContext);
// .filter
cf = cf.filter(() => true);
cf = cf.filter((thus: Clownface) => true);
// .forEach
cf.forEach(() => {});
cf.forEach((thus: Clownface) => {});
// .has
cf = cf.has(predicate, 'Stuart');
cf = cf.has([predicate, predicate], 'Stuart');
cf = cf.has(predicate, [literal, literal]);
// .in
cf = cf.in(node);
cf = cf.in([node, node]);
cf = cf.in(cf.node(node));
// .list
const listNodes: Iterable<clownface.SingleContextClownface<Dataset>> = cf.list();
// .literal
cf = cf.literal('foo');
cf = cf.literal(['foo', 'bar']);
cf = cf.literal('foo', node);
cf = cf.literal('foo', 'en');
// .map
const arr: Clownface[] = cf.map((item: Clownface) => item);
const nums: number[] = cf.map((item: Clownface, index: number) => index);
// .namedNode
cf = cf.namedNode(node);
cf = cf.namedNode('http://example.com/');
cf = cf.namedNode(['http://example.com/', 'http://example.org/']);
// .node
cf = cf.node(node);
cf = cf.node('foo');
cf = cf.node(123);
cf = cf.node(['foo', 'bar']);
cf = cf.node('http://example.org/', { type: 'NamedNode' });
cf = cf.node(null, { type: 'BlankNode' });
cf = cf.node('example', { datatype: node.value });
cf = cf.node('example', { datatype: node });
// .out
cf = cf.out(node);
cf = cf.out([node, node]);
cf = cf.out(cf.node([node, node]));
// .term
if (cf.term) {
term = cf.term;
}
// .terms
const terms: Term[] = cf.terms;
// .toArray
const toArray: Clownface[] = cf.toArray();
// .value
if (cf.value) {
const valueProp: string = cf.value;
}
// .values
const values: string[] = cf.values;
const safeCf: clownface.SafeClownface<Dataset> = <any> {};
let singleBlank: clownface.SingleContextClownface<Dataset, BlankNode> = safeCf.blankNode();
singleBlank = clownface({ dataset }).blankNode();
singleBlank = safeCf.blankNode('blank');
singleBlank = clownface({ dataset }).node(null);
let singleNamed: clownface.SingleContextClownface<Dataset, NamedNode> = clownface({ dataset }).namedNode('urn:foo:bar');
singleNamed = safeCf.namedNode('http://example.com/a');
singleNamed = clownface({ dataset }).node(node);
let singleLiteral: clownface.SingleContextClownface<Dataset, Literal> = clownface({ dataset }).literal('foo');
singleLiteral = safeCf.literal('a');
singleLiteral = clownface({ dataset }).node('b');
const fromSingleArrayBLank: clownface.SingleContextClownface<Dataset, BlankNode> = safeCf.blankNode([ 'b1' ]);
const fromSingleArrayNamed: clownface.SingleContextClownface<Dataset, NamedNode> = safeCf.namedNode([ 'http://example.com/a' ]);
const fromSingleArrayLiteral: clownface.SingleContextClownface<Dataset, Literal> = safeCf.literal([ 'a' ]);
let multipleBlanks: clownface.SafeClownface<Dataset, BlankNode> = safeCf.blankNode([ 'b1', 'b2' ]);
multipleBlanks = clownface({ dataset }).node([ null, null ]);
let multipleNamed: clownface.SafeClownface<Dataset, NamedNode> = safeCf.namedNode([ 'http://example.com/a', 'http://example.com/b' ]);
multipleNamed = clownface({ dataset }).node([ node, node ]);
let multipleLiterals: clownface.SafeClownface<Dataset, Literal> = safeCf.literal([ 'a', 'b' ]);
multipleLiterals = clownface({ dataset }).node([ 'a', 10, false ]);
const multipleMixedTerms: clownface.SafeClownface<Dataset> = clownface({ dataset }).node([ 'a', node, null ]);
| types/clownface/clownface-tests.ts | 1 | https://github.com/DefinitelyTyped/DefinitelyTyped/commit/fed60e05ada31c2fac709c638bd797fa6fb9252b | [
0.9981131553649902,
0.6614646911621094,
0.0001714196114335209,
0.9886221289634705,
0.46728622913360596
] |
{
"id": 0,
"code_window": [
"cf = cf.has([predicate, predicate], 'Stuart');\n",
"cf = cf.has(predicate, [literal, literal]);\n",
"\n",
"// .in\n",
"cf = cf.in(node);\n",
"cf = cf.in([node, node]);\n",
"cf = cf.in(cf.node(node));\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"cf = cf.in();\n"
],
"file_path": "types/clownface/clownface-tests.ts",
"type": "add",
"edit_start_line_idx": 119
} | {
"extends": "dtslint/dt.json"
}
| types/turbolinks/tslint.json | 0 | https://github.com/DefinitelyTyped/DefinitelyTyped/commit/fed60e05ada31c2fac709c638bd797fa6fb9252b | [
0.00017243667389266193,
0.00017243667389266193,
0.00017243667389266193,
0.00017243667389266193,
0
] |
{
"id": 0,
"code_window": [
"cf = cf.has([predicate, predicate], 'Stuart');\n",
"cf = cf.has(predicate, [literal, literal]);\n",
"\n",
"// .in\n",
"cf = cf.in(node);\n",
"cf = cf.in([node, node]);\n",
"cf = cf.in(cf.node(node));\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"cf = cf.in();\n"
],
"file_path": "types/clownface/clownface-tests.ts",
"type": "add",
"edit_start_line_idx": 119
} | { "extends": "dtslint/dt.json" }
| types/react-dynamic-number/tslint.json | 0 | https://github.com/DefinitelyTyped/DefinitelyTyped/commit/fed60e05ada31c2fac709c638bd797fa6fb9252b | [
0.00017291383119300008,
0.00017291383119300008,
0.00017291383119300008,
0.00017291383119300008,
0
] |
{
"id": 0,
"code_window": [
"cf = cf.has([predicate, predicate], 'Stuart');\n",
"cf = cf.has(predicate, [literal, literal]);\n",
"\n",
"// .in\n",
"cf = cf.in(node);\n",
"cf = cf.in([node, node]);\n",
"cf = cf.in(cf.node(node));\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"cf = cf.in();\n"
],
"file_path": "types/clownface/clownface-tests.ts",
"type": "add",
"edit_start_line_idx": 119
} | {
"extends": "dtslint/dt.json"
}
| types/json-js/tslint.json | 0 | https://github.com/DefinitelyTyped/DefinitelyTyped/commit/fed60e05ada31c2fac709c638bd797fa6fb9252b | [
0.00017243667389266193,
0.00017243667389266193,
0.00017243667389266193,
0.00017243667389266193,
0
] |
{
"id": 1,
"code_window": [
"cf = cf.node(null, { type: 'BlankNode' });\n",
"cf = cf.node('example', { datatype: node.value });\n",
"cf = cf.node('example', { datatype: node });\n",
"\n",
"// .out\n",
"cf = cf.out(node);\n",
"cf = cf.out([node, node]);\n",
"cf = cf.out(cf.node([node, node]));\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"cf = cf.out();\n"
],
"file_path": "types/clownface/clownface-tests.ts",
"type": "add",
"edit_start_line_idx": 152
} | // Type definitions for clownface 0.12
// Project: https://github.com/rdf-ext/clownface
// Definitions by: tpluscode <https://github.com/tpluscode>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.3
import { Term, DatasetCore, Quad_Graph, NamedNode, BlankNode, Literal } from 'rdf-js';
declare namespace clownface {
type TermOrClownface = Clownface | Term;
type TermOrLiteral = TermOrClownface | string | number | boolean;
type AddCallback<D extends DatasetCore, X extends Term> = (added: SingleContextClownface<D, X>) => void;
type SingleOrArray<T> = T | T[];
type SingleOrOneElementArray<T> = T | [T];
type SingleOrArrayOfTerms = SingleOrArray<TermOrClownface>;
type SingleOrArrayOfTermsOrLiterals = SingleOrArray<TermOrLiteral>;
interface NodeOptions {
type?: 'BlankNode' | 'Literal' | 'NamedNode';
datatype?: Term | { toString(): string };
language?: string;
}
type ClownfaceInit<D extends DatasetCore = DatasetCore, T extends Term = Term>
= Partial<Pick<Clownface<D, T>, 'dataset' | '_context'> & { graph: Quad_Graph }>;
interface WithSingleValue {
value: string;
}
interface WithValues {
value: string[];
}
interface WithSingleTerm<T extends Term = Term> {
term: T;
}
interface WithTerms<T extends Term = Term> {
term: T[];
}
interface Clownface<D extends DatasetCore = DatasetCore, T extends Term = Term> {
readonly term: T | undefined;
readonly terms: T[];
readonly value: string | undefined;
readonly values: string[];
readonly dataset: D;
readonly datasets: D[];
readonly _context: any;
list(): Iterable<SingleContextClownface<D>>;
toArray(): Array<Clownface<D, T>>;
filter(cb: (quad: Clownface<D, T>) => boolean): Clownface<D, T>;
forEach(cb: (quad: Clownface<D, T>) => void): void;
map<X>(cb: (quad: Clownface<D, T>, index: number) => X): X[];
node(value: SingleOrOneElementArray<boolean | string | number>, options?: NodeOptions): SingleContextClownface<D, Literal>;
node(values: Array<boolean | string | number>, options?: NodeOptions): SafeClownface<D, Literal>;
node<X extends Term>(value: SingleOrOneElementArray<X>, options?: NodeOptions): SingleContextClownface<D, X>;
node<X extends Term>(values: X[], options?: NodeOptions): SafeClownface<D, X>;
node(value: null, options?: NodeOptions): SingleContextClownface<D, BlankNode>;
node(values: null[], options?: NodeOptions): SafeClownface<D, BlankNode>;
node(values: SingleOrArray<boolean | string | number | Term | null>, options?: NodeOptions): SafeClownface<D>;
blankNode(value?: SingleOrOneElementArray<string>): SingleContextClownface<D, BlankNode>;
blankNode(values: string[]): SafeClownface<D, BlankNode>;
literal(value: SingleOrOneElementArray<boolean | string | number | Term | null>, languageOrDatatype?: string | NamedNode): SingleContextClownface<D, Literal>;
literal(values: Array<boolean | string | number | Term | null>, languageOrDatatype?: string | NamedNode): SafeClownface<D, Literal>;
namedNode(value: SingleOrOneElementArray<string | NamedNode>): SingleContextClownface<D, NamedNode>;
namedNode(values: Array<string | NamedNode>): SafeClownface<D, NamedNode>;
// tslint:disable:no-unnecessary-generics
in<X extends Term = Term>(predicates: SingleOrArrayOfTerms): SafeClownface<D, X>;
out<X extends Term = Term>(predicates: SingleOrArrayOfTerms): SafeClownface<D, X>;
has<X extends Term = Term>(predicates: SingleOrArrayOfTerms, objects?: SingleOrArrayOfTermsOrLiterals): SafeClownface<D, X>;
addIn<X extends Term = Term>(predicates: SingleOrArrayOfTerms, objectsOrCallback?: SingleOrArrayOfTermsOrLiterals | AddCallback<D, X>): SafeClownface<D, X>;
addIn<X extends Term = Term>(predicates: SingleOrArrayOfTerms, objects: SingleOrArrayOfTermsOrLiterals, callback: AddCallback<D, X>): SafeClownface<D, X>;
addOut<X extends Term = Term>(predicates: SingleOrArrayOfTerms, objectsOrCallback?: SingleOrArrayOfTermsOrLiterals | AddCallback<D, X>): SafeClownface<D, X>;
addOut<X extends Term = Term>(predicates: SingleOrArrayOfTerms, objects: SingleOrArrayOfTermsOrLiterals, callback: AddCallback<D, X>): SafeClownface<D, X>;
addList<X extends Term = Term>(predicates: SingleOrArrayOfTerms, objects?: SingleOrArrayOfTermsOrLiterals, callback?: AddCallback<D, X>): SafeClownface<D, X>;
deleteIn<X extends Term = Term>(predicates?: SingleOrArrayOfTerms): SafeClownface<D, X>;
deleteOut<X extends Term = Term>(predicates?: SingleOrArrayOfTerms): SafeClownface<D, X>;
deleteList<X extends Term = Term>(predicates: SingleOrArrayOfTerms): SafeClownface<D, X>;
// tslint:enable:no-unnecessary-generics
}
interface SafeClownface<D extends DatasetCore = DatasetCore, T extends Term = Term> extends Clownface<D, T> {
filter(cb: (quad: SingleContextClownface<D, T>) => boolean): SafeClownface<D, T>;
forEach(cb: (quad: SingleContextClownface<D, T>) => void): void;
map<X>(cb: (quad: SingleContextClownface<D, T>, index: number) => X): X[];
toArray(): Array<SingleContextClownface<D, T>>;
}
interface SingleContextClownface<D extends DatasetCore = DatasetCore, T extends Term = Term> extends SafeClownface<D, T> {
readonly term: T;
readonly terms: [T];
readonly value: string;
readonly values: [string];
}
}
type ClownfaceInitWithNodes<D extends DatasetCore, T extends Term> =
clownface.ClownfaceInit<D> & clownface.WithTerms<T> |
clownface.ClownfaceInit<D> & clownface.WithValues;
type ClownfaceInitWithSingleNode<D extends DatasetCore, T extends Term> =
clownface.ClownfaceInit<D> & clownface.WithSingleTerm<T> |
clownface.ClownfaceInit<D> & clownface.WithSingleValue;
declare function clownface<D extends DatasetCore, T extends Term = Term>(options: ClownfaceInitWithNodes<D, T>): clownface.SafeClownface<D, T>;
declare function clownface<D extends DatasetCore, T extends Term = Term>(options: ClownfaceInitWithSingleNode<D, T>): clownface.SingleContextClownface<D, T>;
declare function clownface<D extends DatasetCore, T extends Term = Term>(options: clownface.ClownfaceInit<D, T>): clownface.Clownface<D, T>;
export = clownface;
| types/clownface/index.d.ts | 1 | https://github.com/DefinitelyTyped/DefinitelyTyped/commit/fed60e05ada31c2fac709c638bd797fa6fb9252b | [
0.0011840623337775469,
0.00032433075830340385,
0.00016583799151703715,
0.0001742641325108707,
0.0002990753564517945
] |
{
"id": 1,
"code_window": [
"cf = cf.node(null, { type: 'BlankNode' });\n",
"cf = cf.node('example', { datatype: node.value });\n",
"cf = cf.node('example', { datatype: node });\n",
"\n",
"// .out\n",
"cf = cf.out(node);\n",
"cf = cf.out([node, node]);\n",
"cf = cf.out(cf.node([node, node]));\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"cf = cf.out();\n"
],
"file_path": "types/clownface/clownface-tests.ts",
"type": "add",
"edit_start_line_idx": 152
} | // Type definitions for AngularFire 0.8.2
// Project: http://angularfire.com
// Definitions by: Dénes Harmath <https://github.com/thSoft>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.3
/// <reference types="angular"/>
/// <reference types="firebase"/>
interface AngularFireService {
(firebase: Firebase, config?: any): AngularFire;
}
/**
* @deprecated. Not possible with AngularFire 1.0+
*/
interface AngularFire {
$asArray(): AngularFireArray;
$asObject(): AngularFireObject;
$ref(): Firebase;
$push(data: any): ng.IPromise<Firebase>;
$set(key: string, data: any): ng.IPromise<Firebase>;
$set(data: any): ng.IPromise<Firebase>;
$remove(key?: string): ng.IPromise<Firebase>;
$update(key: string, data: Object): ng.IPromise<Firebase>;
$update(data: any): ng.IPromise<Firebase>;
$transaction(updateFn: (currentData: any) => any, applyLocally?: boolean): ng.IPromise<FirebaseDataSnapshot>;
$transaction(key:string, updateFn: (currentData: any) => any, applyLocally?: boolean): ng.IPromise<FirebaseDataSnapshot>;
}
/**
* Creates and maintains a synchronized object, with 2-way bindings between Angular and Firebase.
*/
interface AngularFireObject extends AngularFireSimpleObject {
$id: string;
$priority: number;
$value: any;
/**
* Removes all keys from the FirebaseObject and also removes
* the remote data from the server.
*
* @returns a promise which will resolve after the op completes
*/
$remove(): ng.IPromise<Firebase>;
/**
* Saves all data on the FirebaseObject back to Firebase.
* @returns a promise which will resolve after the save is completed.
*/
$save(): ng.IPromise<Firebase>;
/**
* The loaded method is invoked after the initial batch of data arrives from the server.
* When this resolves, all data which existed prior to calling $asObject() is now cached
* locally in the object.
*
* As a shortcut is also possible to pass resolve/reject methods directly into this
* method just as they would be passed to .then()
*
* @param {Function} resolve
* @param {Function} reject
* @returns a promise which resolves after initial data is downloaded from Firebase
*/
$loaded(resolve?: (x: AngularFireObject) => ng.IHttpPromise<{}>, reject?: (err: any) => any): ng.IPromise<AngularFireObject>;
/**
* The loaded method is invoked after the initial batch of data arrives from the server.
* When this resolves, all data which existed prior to calling $asObject() is now cached
* locally in the object.
*
* As a shortcut is also possible to pass resolve/reject methods directly into this
* method just as they would be passed to .then()
*
* @param {Function} resolve
* @param {Function} reject
* @returns a promise which resolves after initial data is downloaded from Firebase
*/
$loaded(resolve?: (x: AngularFireObject) => ng.IPromise<{}>, reject?: (err: any) => any): ng.IPromise<AngularFireObject>;
/**
* The loaded method is invoked after the initial batch of data arrives from the server.
* When this resolves, all data which existed prior to calling $asObject() is now cached
* locally in the object.
*
* As a shortcut is also possible to pass resolve/reject methods directly into this
* method just as they would be passed to .then()
*
* @param {Function} resolve
* @param {Function} reject
* @returns a promise which resolves after initial data is downloaded from Firebase
*/
$loaded(resolve?: (x: AngularFireObject) => void, reject?: (err: any) => any): ng.IPromise<AngularFireObject>;
/**
* @returns {Firebase} the original Firebase instance used to create this object.
*/
$ref(): Firebase;
/**
* Creates a 3-way data sync between this object, the Firebase server, and a
* scope variable. This means that any changes made to the scope variable are
* pushed to Firebase, and vice versa.
*
* If scope emits a $destroy event, the binding is automatically severed. Otherwise,
* it is possible to unbind the scope variable by using the `unbind` function
* passed into the resolve method.
*
* Can only be bound to one scope variable at a time. If a second is attempted,
* the promise will be rejected with an error.
*
* @param {object} scope
* @param {string} varName
* @returns a promise which resolves to an unbind method after data is set in scope
*/
$bindTo(scope: ng.IScope, varName: string): ng.IPromise<any>;
/**
* Listeners passed into this method are notified whenever a new change is received
* from the server. Each invocation is sent an object containing
* <code>{ type: 'value', key: 'my_firebase_id' }</code>
*
* This method returns an unbind function that can be used to detach the listener.
*
* @param {Function} cb
* @param {Object} [context]
* @returns {Function} invoke to stop observing events
*/
$watch(callback: Function, context?: any): Function;
/**
* Informs $firebase to stop sending events and clears memory being used
* by this object (delete's its local content).
*/
$destroy(): void;
}
interface AngularFireObjectService {
/**
* Creates a synchronized object with 2-way bindings between Angular and Firebase.
*
* @param {Firebase} ref
* @returns {FirebaseObject}
*/
(firebase: Firebase): AngularFireObject;
$extend(ChildClass: Object, methods?: Object): Object;
}
/**
* Creates and maintains a synchronized list of data. This is a pseudo-read-only array. One should
* not call splice(), push(), pop(), et al directly on this array, but should instead use the
* $remove and $add methods.
*
* It is acceptable to .sort() this array, but it is important to use this in conjunction with
* $watch(), so that it will be re-sorted any time the server data changes. Examples of this are
* included in the $watch documentation.
*/
interface AngularFireArray extends Array<AngularFireSimpleObject> {
/**
* Create a new record with a unique ID and add it to the end of the array.
* This should be used instead of Array.prototype.push, since those changes will not be
* synchronized with the server.
*
* Any value, including a primitive, can be added in this way. Note that when the record
* is created, the primitive value would be stored in $value (records are always objects
* by default).
*
* Returns a future which is resolved when the data has successfully saved to the server.
* The resolve callback will be passed a Firebase ref representing the new data element.
*
* @param data
* @returns a promise resolved after data is added
*/
$add(newData: any): ng.IPromise<Firebase>;
/**
* Pass either an item in the array or the index of an item and it will be saved back
* to Firebase. While the array is read-only and its structure should not be changed,
* it is okay to modify properties on the objects it contains and then save those back
* individually.
*
* Returns a future which is resolved when the data has successfully saved to the server.
* The resolve callback will be passed a Firebase ref representing the saved element.
* If passed an invalid index or an object which is not a record in this array,
* the promise will be rejected.
*
* @param {int|object} indexOrItem
* @returns a promise resolved after data is saved
*/
$save(recordOrIndex: any): ng.IPromise<Firebase>;
/**
* Pass either an existing item in this array or the index of that item and it will
* be removed both locally and in Firebase. This should be used in place of
* Array.prototype.splice for removing items out of the array, as calling splice
* will not update the value on the server.
*
* Returns a future which is resolved when the data has successfully removed from the
* server. The resolve callback will be passed a Firebase ref representing the deleted
* element. If passed an invalid index or an object which is not a record in this array,
* the promise will be rejected.
*
* @param {int|object} indexOrItem
* @returns a promise which resolves after data is removed
*/
$remove(recordOrIndex: any): ng.IPromise<Firebase>;
/**
* Returns the record for a given Firebase key (record.$id). If the record is not found
* then returns null.
*
* @param {string} key
* @returns {Object|null} a record in this array
*/
$getRecord(key: string): AngularFireSimpleObject;
/**
* Given an item in this array or the index of an item in the array, this returns the
* Firebase key (record.$id) for that record. If passed an invalid key or an item which
* does not exist in this array, it will return null.
*
* @param {int|object} indexOrItem
* @returns {null|string}
*/
$keyAt(recordOrIndex: any): string;
/**
* The inverse of $keyAt, this method takes a Firebase key (record.$id) and returns the
* index in the array where that record is stored. If the record is not in the array,
* this method returns -1.
*
* @param {String} key
* @returns {int} -1 if not found
*/
$indexFor(key: string): number;
/**
* The loaded method is invoked after the initial batch of data arrives from the server.
* When this resolves, all data which existed prior to calling $asArray() is now cached
* locally in the array.
*
* As a shortcut is also possible to pass resolve/reject methods directly into this
* method just as they would be passed to .then()
*
* @param {Function} [resolve]
* @param {Function} [reject]
* @returns a promise
*/
$loaded(resolve?: (x: AngularFireArray) => ng.IHttpPromise<{}>, reject?: (err: any) => any): ng.IPromise<AngularFireArray>;
/**
* The loaded method is invoked after the initial batch of data arrives from the server.
* When this resolves, all data which existed prior to calling $asArray() is now cached
* locally in the array.
*
* As a shortcut is also possible to pass resolve/reject methods directly into this
* method just as they would be passed to .then()
*
* @param {Function} [resolve]
* @param {Function} [reject]
* @returns a promise
*/
$loaded(resolve?: (x: AngularFireArray) => ng.IPromise<{}>, reject?: (err: any) => any): ng.IPromise<AngularFireArray>;
/**
* The loaded method is invoked after the initial batch of data arrives from the server.
* When this resolves, all data which existed prior to calling $asArray() is now cached
* locally in the array.
*
* As a shortcut is also possible to pass resolve/reject methods directly into this
* method just as they would be passed to .then()
*
* @param {Function} [resolve]
* @param {Function} [reject]
* @returns a promise
*/
$loaded(resolve?: (x: AngularFireArray) => void, reject?: (err: any) => any): ng.IPromise<AngularFireArray>;
/**
* @returns {Firebase} the original Firebase ref used to create this object.
*/
$ref(): Firebase;
/**
* Listeners passed into this method are notified whenever a new change (add, updated,
* move, remove) is received from the server. Each invocation is sent an object
* containing <code>{ type: 'child_added|child_updated|child_moved|child_removed',
* key: 'key_of_item_affected'}</code>
*
* Additionally, added and moved events receive a prevChild parameter, containing the
* key of the item before this one in the array.
*
* This method returns a function which can be invoked to stop observing events.
*
* @param {Function} cb
* @param {Object} [context]
* @returns {Function} used to stop observing
*/
$watch(cb: (event: string, key: string, prevChild: string) => void, context?: any): Function;
/**
* Informs $firebase to stop sending events and clears memory being used
* by this array (delete's its local content).
*/
$destroy(): void;
}
interface AngularFireArrayService {
(firebase: Firebase): AngularFireArray;
$extend(ChildClass: Object, methods?: Object): Object;
}
interface AngularFireSimpleObject {
$id: string;
$priority: number;
$value: any;
[key: string]: any;
}
interface AngularFireAuthService {
(firebase: Firebase): AngularFireAuth;
}
interface AngularFireAuth {
/**
* Authenticates the Firebase reference with a custom authentication token.
*
* @param {string} authToken An authentication token or a Firebase Secret. A Firebase Secret
* should only be used for authenticating a server process and provides full read / write
* access to the entire Firebase.
* @param {Object} [options] An object containing optional client arguments, such as configuring
* session persistence.
* @return {Promise<Object>} A promise fulfilled with an object containing authentication data.
*/
$authWithCustomToken(authToken: string, options?: Object): ng.IPromise<any>;
/**
* Authenticates the Firebase reference anonymously.
*
* @param {Object} [options] An object containing optional client arguments, such as configuring
* session persistence.
* @return {Promise<Object>} A promise fulfilled with an object containing authentication data.
*/
$authAnonymously(options?: Object): ng.IPromise<any>;
/**
* Authenticates the Firebase reference with an email/password user.
*
* @param {Object} credentials An object containing email and password attributes corresponding
* to the user account.
* @param {Object} [options] An object containing optional client arguments, such as configuring
* session persistence.
* @return {Promise<Object>} A promise fulfilled with an object containing authentication data.
*/
$authWithPassword(credentials: FirebaseCredentials, options?: Object): ng.IPromise<any>;
/**
* Authenticates the Firebase reference with the OAuth popup flow.
*
* @param {string} provider The unique string identifying the OAuth provider to authenticate
* with, e.g. google.
* @param {Object} [options] An object containing optional client arguments, such as configuring
* session persistence.
* @return {Promise<Object>} A promise fulfilled with an object containing authentication data.
*/
$authWithOAuthPopup(provider: string, options?: Object): ng.IPromise<any>;
/**
* Authenticates the Firebase reference with the OAuth redirect flow.
*
* @param {string} provider The unique string identifying the OAuth provider to authenticate
* with, e.g. google.
* @param {Object} [options] An object containing optional client arguments, such as configuring
* session persistence.
* @return {Promise<Object>} A promise fulfilled with an object containing authentication data.
*/
$authWithOAuthRedirect(provider: string, options?: Object): ng.IPromise<any>;
/**
* Authenticates the Firebase reference with an OAuth token.
*
* @param {string} provider The unique string identifying the OAuth provider to authenticate
* with, e.g. google.
* @param {string|Object} credentials Either a string, such as an OAuth 2.0 access token, or an
* Object of key / value pairs, such as a set of OAuth 1.0a credentials.
* @param {Object} [options] An object containing optional client arguments, such as configuring
* session persistence.
* @return {Promise<Object>} A promise fulfilled with an object containing authentication data.
*/
$authWithOAuthToken(provider: string, credentials: Object|string, options?: Object): ng.IPromise<any>;
/**
* Synchronously retrieves the current authentication data.
*
* @return {Object} The client's authentication data.
*/
$getAuth(): FirebaseAuthData;
/**
* Asynchronously fires the provided callback with the current authentication data every time
* the authentication data changes. It also fires as soon as the authentication data is
* retrieved from the server.
*
* @param {function} callback A callback that fires when the client's authenticate state
* changes. If authenticated, the callback will be passed an object containing authentication
* data according to the provider used to authenticate. Otherwise, it will be passed null.
* @param {string} [context] If provided, this object will be used as this when calling your
* callback.
* @return {function} A function which can be used to deregister the provided callback.
*/
$onAuth(callback: Function, context?: any): Function;
/**
* Unauthenticates the Firebase reference.
*/
$unauth(): void;
/**
* Utility method which can be used in a route's resolve() method to grab the current
* authentication data.
*
* @returns {Promise<Object|null>} A promise fulfilled with the client's current authentication
* state, which will be null if the client is not authenticated.
*/
$waitForAuth(): ng.IPromise<any>;
/**
* Utility method which can be used in a route's resolve() method to require that a route has
* a logged in client.
*
* @returns {Promise<Object>} A promise fulfilled with the client's current authentication
* state or rejected if the client is not authenticated.
*/
$requireAuth(): ng.IPromise<any>;
/**
* Creates a new email/password user. Note that this function only creates the user, if you
* wish to log in as the newly created user, call $authWithPassword() after the promise for
* this method has been resolved.
*
* @param {Object} credentials An object containing the email and password of the user to create.
* @return {Promise<Object>} A promise fulfilled with the user object, which contains the
* uid of the created user.
*/
$createUser(credentials: FirebaseCredentials): ng.IPromise<any>;
/**
* Removes an email/password user.
*
* @param {Object} credentials An object containing the email and password of the user to remove.
* @return {Promise<>} An empty promise fulfilled once the user is removed.
*/
$removeUser(credentials: FirebaseCredentials): ng.IPromise<any>;
/**
* Changes the email for an email/password user.
*
* @param {Object} credentials An object containing the old email, new email, and password of
* the user whose email is to change.
* @return {Promise<>} An empty promise fulfilled once the email change is complete.
*/
$changeEmail(credentials: FirebaseChangeEmailCredentials): ng.IPromise<any>;
/**
* Changes the password for an email/password user.
*
* @param {Object} credentials An object containing the email, old password, and new password of
* the user whose password is to change.
* @return {Promise<>} An empty promise fulfilled once the password change is complete.
*/
$changePassword(credentials: FirebaseChangePasswordCredentials): ng.IPromise<any>;
/**
* Sends a password reset email to an email/password user.
*
* @param {Object} credentials An object containing the email of the user to send a reset
* password email to.
* @return {Promise<>} An empty promise fulfilled once the reset password email is sent.
*/
$resetPassword(credentials: FirebaseResetPasswordCredentials): ng.IPromise<any>;
}
| types/angularfire/index.d.ts | 0 | https://github.com/DefinitelyTyped/DefinitelyTyped/commit/fed60e05ada31c2fac709c638bd797fa6fb9252b | [
0.0007418108871206641,
0.00018295466725248843,
0.0001622401614440605,
0.0001673376391408965,
0.00008356689795618877
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.